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"
2010a4972aSSaleem Abdulrasool #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 
27efa956ceSAlexey Samsonov static RequiredArgs
28efa956ceSAlexey Samsonov commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
29efa956ceSAlexey Samsonov                                   llvm::Value *This, llvm::Value *ImplicitParam,
30efa956ceSAlexey Samsonov                                   QualType ImplicitParamTy, const CallExpr *CE,
31762672a7SRichard Smith                                   CallArgList &Args, CallArgList *RtlArgs) {
32a5bf76bdSAlexey Samsonov   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
33a5bf76bdSAlexey Samsonov          isa<CXXOperatorCallExpr>(CE));
3427da15baSAnders Carlsson   assert(MD->isInstance() &&
35a5bf76bdSAlexey Samsonov          "Trying to emit a member or operator call expr on a static method!");
36034e7270SReid Kleckner   ASTContext &C = CGF.getContext();
3727da15baSAnders Carlsson 
3869d0d262SRichard Smith   // C++11 [class.mfct.non-static]p2:
3969d0d262SRichard Smith   //   If a non-static member function of a class X is called for an object that
4069d0d262SRichard Smith   //   is not of type X, or of a type derived from X, the behavior is undefined.
41a5bf76bdSAlexey Samsonov   SourceLocation CallLoc;
42a5bf76bdSAlexey Samsonov   if (CE)
43a5bf76bdSAlexey Samsonov     CallLoc = CE->getExprLoc();
44034e7270SReid Kleckner   CGF.EmitTypeCheck(isa<CXXConstructorDecl>(MD)
45034e7270SReid Kleckner                         ? CodeGenFunction::TCK_ConstructorCall
460c0b6d9aSDavid Majnemer                         : CodeGenFunction::TCK_MemberCall,
47034e7270SReid Kleckner                     CallLoc, This, C.getRecordType(MD->getParent()));
4827da15baSAnders Carlsson 
4927da15baSAnders Carlsson   // Push the this ptr.
50034e7270SReid Kleckner   const CXXRecordDecl *RD =
51034e7270SReid Kleckner       CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
52034e7270SReid Kleckner   Args.add(RValue::get(This),
53034e7270SReid Kleckner            RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
5427da15baSAnders Carlsson 
55ee6bc533STimur Iskhodzhanov   // If there is an implicit parameter (e.g. VTT), emit it.
56ee6bc533STimur Iskhodzhanov   if (ImplicitParam) {
57ee6bc533STimur Iskhodzhanov     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
58e36a6b3eSAnders Carlsson   }
59e36a6b3eSAnders Carlsson 
60a729c62bSJohn McCall   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
61419996ccSGeorge Burgess IV   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD);
62a729c62bSJohn McCall 
63a729c62bSJohn McCall   // And the rest of the call args.
64762672a7SRichard Smith   if (RtlArgs) {
65762672a7SRichard Smith     // Special case: if the caller emitted the arguments right-to-left already
66762672a7SRichard Smith     // (prior to emitting the *this argument), we're done. This happens for
67762672a7SRichard Smith     // assignment operators.
68762672a7SRichard Smith     Args.addFrom(*RtlArgs);
69762672a7SRichard Smith   } else if (CE) {
70a5bf76bdSAlexey Samsonov     // Special case: skip first argument of CXXOperatorCall (it is "this").
718e1162c7SAlexey Samsonov     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
72f05779e2SDavid Blaikie     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
738e1162c7SAlexey Samsonov                      CE->getDirectCallee());
74a5bf76bdSAlexey Samsonov   } else {
758e1162c7SAlexey Samsonov     assert(
768e1162c7SAlexey Samsonov         FPT->getNumParams() == 0 &&
778e1162c7SAlexey Samsonov         "No CallExpr specified for function with non-zero number of arguments");
78a5bf76bdSAlexey Samsonov   }
790c0b6d9aSDavid Majnemer   return required;
800c0b6d9aSDavid Majnemer }
8127da15baSAnders Carlsson 
820c0b6d9aSDavid Majnemer RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
830c0b6d9aSDavid Majnemer     const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
840c0b6d9aSDavid Majnemer     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
85762672a7SRichard Smith     const CallExpr *CE, CallArgList *RtlArgs) {
860c0b6d9aSDavid Majnemer   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
870c0b6d9aSDavid Majnemer   CallArgList Args;
880c0b6d9aSDavid Majnemer   RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
89762672a7SRichard Smith       *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
908dda7b27SJohn McCall   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
91c50c27ccSRafael Espindola                   Callee, ReturnValue, Args, MD);
9227da15baSAnders Carlsson }
9327da15baSAnders Carlsson 
94ae81bbb4SAlexey Samsonov RValue CodeGenFunction::EmitCXXDestructorCall(
95ae81bbb4SAlexey Samsonov     const CXXDestructorDecl *DD, llvm::Value *Callee, llvm::Value *This,
96ae81bbb4SAlexey Samsonov     llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
97ae81bbb4SAlexey Samsonov     StructorType Type) {
980c0b6d9aSDavid Majnemer   CallArgList Args;
99ae81bbb4SAlexey Samsonov   commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
100762672a7SRichard Smith                                     ImplicitParamTy, CE, Args, nullptr);
101ae81bbb4SAlexey Samsonov   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
102ae81bbb4SAlexey Samsonov                   Callee, ReturnValueSlot(), Args, DD);
1030c0b6d9aSDavid Majnemer }
1040c0b6d9aSDavid Majnemer 
1053b33c4ecSRafael Espindola static CXXRecordDecl *getCXXRecord(const Expr *E) {
1063b33c4ecSRafael Espindola   QualType T = E->getType();
1073b33c4ecSRafael Espindola   if (const PointerType *PTy = T->getAs<PointerType>())
1083b33c4ecSRafael Espindola     T = PTy->getPointeeType();
1093b33c4ecSRafael Espindola   const RecordType *Ty = T->castAs<RecordType>();
1103b33c4ecSRafael Espindola   return cast<CXXRecordDecl>(Ty->getDecl());
1113b33c4ecSRafael Espindola }
1123b33c4ecSRafael Espindola 
11364225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC
11464225794SFrancois Pichet // extensions allowing explicit constructor function call.
11527da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
11627da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
1172d2e8707SJohn McCall   const Expr *callee = CE->getCallee()->IgnoreParens();
1182d2e8707SJohn McCall 
1192d2e8707SJohn McCall   if (isa<BinaryOperator>(callee))
12027da15baSAnders Carlsson     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
12127da15baSAnders Carlsson 
1222d2e8707SJohn McCall   const MemberExpr *ME = cast<MemberExpr>(callee);
12327da15baSAnders Carlsson   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
12427da15baSAnders Carlsson 
12527da15baSAnders Carlsson   if (MD->isStatic()) {
12627da15baSAnders Carlsson     // The method is static, emit it as we would a regular call.
12727da15baSAnders Carlsson     llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
12870b9c01bSAlexey Samsonov     return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
12970b9c01bSAlexey Samsonov                     ReturnValue);
13027da15baSAnders Carlsson   }
13127da15baSAnders Carlsson 
132aad4af6dSNico Weber   bool HasQualifier = ME->hasQualifier();
133aad4af6dSNico Weber   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
134aad4af6dSNico Weber   bool IsArrow = ME->isArrow();
135ecbe2e97SRafael Espindola   const Expr *Base = ME->getBase();
136aad4af6dSNico Weber 
137aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
138aad4af6dSNico Weber       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
139aad4af6dSNico Weber }
140aad4af6dSNico Weber 
141aad4af6dSNico Weber RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
142aad4af6dSNico Weber     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
143aad4af6dSNico Weber     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
144aad4af6dSNico Weber     const Expr *Base) {
145aad4af6dSNico Weber   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
146aad4af6dSNico Weber 
147aad4af6dSNico Weber   // Compute the object pointer.
148aad4af6dSNico Weber   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
149ecbe2e97SRafael Espindola 
1508a13c418SCraig Topper   const CXXMethodDecl *DevirtualizedMethod = nullptr;
1517463ed7cSBenjamin Kramer   if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
1523b33c4ecSRafael Espindola     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
1533b33c4ecSRafael Espindola     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
1543b33c4ecSRafael Espindola     assert(DevirtualizedMethod);
1553b33c4ecSRafael Espindola     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
1563b33c4ecSRafael Espindola     const Expr *Inner = Base->ignoreParenBaseCasts();
1575bd68794SAlexey Bataev     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
1585bd68794SAlexey Bataev         MD->getReturnType().getCanonicalType())
1595bd68794SAlexey Bataev       // If the return types are not the same, this might be a case where more
1605bd68794SAlexey Bataev       // code needs to run to compensate for it. For example, the derived
1615bd68794SAlexey Bataev       // method might return a type that inherits form from the return
1625bd68794SAlexey Bataev       // type of MD and has a prefix.
1635bd68794SAlexey Bataev       // For now we just avoid devirtualizing these covariant cases.
1645bd68794SAlexey Bataev       DevirtualizedMethod = nullptr;
1655bd68794SAlexey Bataev     else if (getCXXRecord(Inner) == DevirtualizedClass)
1663b33c4ecSRafael Espindola       // If the class of the Inner expression is where the dynamic method
1673b33c4ecSRafael Espindola       // is defined, build the this pointer from it.
1683b33c4ecSRafael Espindola       Base = Inner;
1693b33c4ecSRafael Espindola     else if (getCXXRecord(Base) != DevirtualizedClass) {
1703b33c4ecSRafael Espindola       // If the method is defined in a class that is not the best dynamic
1713b33c4ecSRafael Espindola       // one or the one of the full expression, we would have to build
1723b33c4ecSRafael Espindola       // a derived-to-base cast to compute the correct this pointer, but
1733b33c4ecSRafael Espindola       // we don't have support for that yet, so do a virtual call.
1748a13c418SCraig Topper       DevirtualizedMethod = nullptr;
1753b33c4ecSRafael Espindola     }
1763b33c4ecSRafael Espindola   }
177ecbe2e97SRafael Espindola 
178762672a7SRichard Smith   // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
179762672a7SRichard Smith   // operator before the LHS.
180762672a7SRichard Smith   CallArgList RtlArgStorage;
181762672a7SRichard Smith   CallArgList *RtlArgs = nullptr;
182762672a7SRichard Smith   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
183762672a7SRichard Smith     if (OCE->isAssignmentOp()) {
184762672a7SRichard Smith       RtlArgs = &RtlArgStorage;
185762672a7SRichard Smith       EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
186762672a7SRichard Smith                    drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
187a560ccf2SRichard Smith                    /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
188762672a7SRichard Smith     }
189762672a7SRichard Smith   }
190762672a7SRichard Smith 
1917f416cc4SJohn McCall   Address This = Address::invalid();
192aad4af6dSNico Weber   if (IsArrow)
1937f416cc4SJohn McCall     This = EmitPointerWithAlignment(Base);
194f93ac894SFariborz Jahanian   else
1953b33c4ecSRafael Espindola     This = EmitLValue(Base).getAddress();
196ecbe2e97SRafael Espindola 
19727da15baSAnders Carlsson 
198419bd094SRichard Smith   if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
1998a13c418SCraig Topper     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
20064225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
20164225794SFrancois Pichet         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
2028a13c418SCraig Topper       return RValue::get(nullptr);
2030d635f53SJohn McCall 
204aad4af6dSNico Weber     if (!MD->getParent()->mayInsertExtraPadding()) {
20522653bacSSebastian Redl       if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
20622653bacSSebastian Redl         // We don't like to generate the trivial copy/move assignment operator
20722653bacSSebastian Redl         // when it isn't necessary; just produce the proper effect here.
208762672a7SRichard Smith         LValue RHS = isa<CXXOperatorCallExpr>(CE)
209762672a7SRichard Smith                          ? MakeNaturalAlignAddrLValue(
210762672a7SRichard Smith                                (*RtlArgs)[0].RV.getScalarVal(),
211762672a7SRichard Smith                                (*(CE->arg_begin() + 1))->getType())
212762672a7SRichard Smith                          : EmitLValue(*CE->arg_begin());
213762672a7SRichard Smith         EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
2147f416cc4SJohn McCall         return RValue::get(This.getPointer());
21527da15baSAnders Carlsson       }
21627da15baSAnders Carlsson 
21764225794SFrancois Pichet       if (isa<CXXConstructorDecl>(MD) &&
21822653bacSSebastian Redl           cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
21922653bacSSebastian Redl         // Trivial move and copy ctor are the same.
220525bf650SAlexey Samsonov         assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2217f416cc4SJohn McCall         Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
222f48ee448SBenjamin Kramer         EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
2237f416cc4SJohn McCall         return RValue::get(This.getPointer());
22464225794SFrancois Pichet       }
22564225794SFrancois Pichet       llvm_unreachable("unknown trivial member function");
22664225794SFrancois Pichet     }
227aad4af6dSNico Weber   }
22864225794SFrancois Pichet 
2290d635f53SJohn McCall   // Compute the function type we're calling.
2303abfe958SNico Weber   const CXXMethodDecl *CalleeDecl =
2313abfe958SNico Weber       DevirtualizedMethod ? DevirtualizedMethod : MD;
2328a13c418SCraig Topper   const CGFunctionInfo *FInfo = nullptr;
2333abfe958SNico Weber   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
2348d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2358d2a19b4SRafael Espindola         Dtor, StructorType::Complete);
2363abfe958SNico Weber   else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
2378d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2388d2a19b4SRafael Espindola         Ctor, StructorType::Complete);
23964225794SFrancois Pichet   else
240ade60977SEli Friedman     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
2410d635f53SJohn McCall 
242e7de47efSReid Kleckner   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
2430d635f53SJohn McCall 
24427da15baSAnders Carlsson   // C++ [class.virtual]p12:
24527da15baSAnders Carlsson   //   Explicit qualification with the scope operator (5.1) suppresses the
24627da15baSAnders Carlsson   //   virtual call mechanism.
24727da15baSAnders Carlsson   //
24827da15baSAnders Carlsson   // We also don't emit a virtual call if the base expression has a record type
24927da15baSAnders Carlsson   // because then we know what the type is.
2503b33c4ecSRafael Espindola   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
25119cee187SStephen Lin   llvm::Value *Callee;
2529dc6eef7SStephen Lin 
2530d635f53SJohn McCall   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
25419cee187SStephen Lin     assert(CE->arg_begin() == CE->arg_end() &&
2559dc6eef7SStephen Lin            "Destructor shouldn't have explicit parameters");
2569dc6eef7SStephen Lin     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
2579dc6eef7SStephen Lin     if (UseVirtualCall) {
258aad4af6dSNico Weber       CGM.getCXXABI().EmitVirtualDestructorCall(
259aad4af6dSNico Weber           *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
26027da15baSAnders Carlsson     } else {
261aad4af6dSNico Weber       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
262aad4af6dSNico Weber         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
2633b33c4ecSRafael Espindola       else if (!DevirtualizedMethod)
2641ac0ec86SRafael Espindola         Callee =
2651ac0ec86SRafael Espindola             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
26649e860b2SRafael Espindola       else {
2673b33c4ecSRafael Espindola         const CXXDestructorDecl *DDtor =
2683b33c4ecSRafael Espindola           cast<CXXDestructorDecl>(DevirtualizedMethod);
26949e860b2SRafael Espindola         Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
27049e860b2SRafael Espindola       }
2717f416cc4SJohn McCall       EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(),
272762672a7SRichard Smith                                   /*ImplicitParam=*/nullptr, QualType(), CE,
273762672a7SRichard Smith                                   nullptr);
27427da15baSAnders Carlsson     }
2758a13c418SCraig Topper     return RValue::get(nullptr);
2769dc6eef7SStephen Lin   }
2779dc6eef7SStephen Lin 
2789dc6eef7SStephen Lin   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
27964225794SFrancois Pichet     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
2800d635f53SJohn McCall   } else if (UseVirtualCall) {
2816708c4a1SPeter Collingbourne     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
2826708c4a1SPeter Collingbourne                                                        CE->getLocStart());
28327da15baSAnders Carlsson   } else {
2841a7488afSPeter Collingbourne     if (SanOpts.has(SanitizerKind::CFINVCall) &&
2851a7488afSPeter Collingbourne         MD->getParent()->isDynamicClass()) {
2864b1ac72cSPiotr Padlewski       llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent());
287fb532b9aSPeter Collingbourne       EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall,
288fb532b9aSPeter Collingbourne                                 CE->getLocStart());
2891a7488afSPeter Collingbourne     }
2901a7488afSPeter Collingbourne 
291aad4af6dSNico Weber     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
292aad4af6dSNico Weber       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
2933b33c4ecSRafael Espindola     else if (!DevirtualizedMethod)
294727a771aSRafael Espindola       Callee = CGM.GetAddrOfFunction(MD, Ty);
29549e860b2SRafael Espindola     else {
2963b33c4ecSRafael Espindola       Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
29749e860b2SRafael Espindola     }
29827da15baSAnders Carlsson   }
29927da15baSAnders Carlsson 
300f1749427STimur Iskhodzhanov   if (MD->isVirtual()) {
301f1749427STimur Iskhodzhanov     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
3024b60f30aSReid Kleckner         *this, CalleeDecl, This, UseVirtualCall);
303f1749427STimur Iskhodzhanov   }
30488fd439aSTimur Iskhodzhanov 
3057f416cc4SJohn McCall   return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(),
306762672a7SRichard Smith                                      /*ImplicitParam=*/nullptr, QualType(), CE,
307762672a7SRichard Smith                                      RtlArgs);
30827da15baSAnders Carlsson }
30927da15baSAnders Carlsson 
31027da15baSAnders Carlsson RValue
31127da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
31227da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
31327da15baSAnders Carlsson   const BinaryOperator *BO =
31427da15baSAnders Carlsson       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
31527da15baSAnders Carlsson   const Expr *BaseExpr = BO->getLHS();
31627da15baSAnders Carlsson   const Expr *MemFnExpr = BO->getRHS();
31727da15baSAnders Carlsson 
31827da15baSAnders Carlsson   const MemberPointerType *MPT =
3190009fcc3SJohn McCall     MemFnExpr->getType()->castAs<MemberPointerType>();
320475999dcSJohn McCall 
32127da15baSAnders Carlsson   const FunctionProtoType *FPT =
3220009fcc3SJohn McCall     MPT->getPointeeType()->castAs<FunctionProtoType>();
32327da15baSAnders Carlsson   const CXXRecordDecl *RD =
32427da15baSAnders Carlsson     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
32527da15baSAnders Carlsson 
32627da15baSAnders Carlsson   // Emit the 'this' pointer.
3277f416cc4SJohn McCall   Address This = Address::invalid();
328e302792bSJohn McCall   if (BO->getOpcode() == BO_PtrMemI)
3297f416cc4SJohn McCall     This = EmitPointerWithAlignment(BaseExpr);
33027da15baSAnders Carlsson   else
33127da15baSAnders Carlsson     This = EmitLValue(BaseExpr).getAddress();
33227da15baSAnders Carlsson 
3337f416cc4SJohn McCall   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
334e30752c9SRichard Smith                 QualType(MPT->getClass(), 0));
33569d0d262SRichard Smith 
336bde62d78SRichard Smith   // Get the member function pointer.
337bde62d78SRichard Smith   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
338bde62d78SRichard Smith 
339475999dcSJohn McCall   // Ask the ABI to load the callee.  Note that This is modified.
3407f416cc4SJohn McCall   llvm::Value *ThisPtrForCall = nullptr;
341475999dcSJohn McCall   llvm::Value *Callee =
3427f416cc4SJohn McCall     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
3437f416cc4SJohn McCall                                              ThisPtrForCall, MemFnPtr, MPT);
34427da15baSAnders Carlsson 
34527da15baSAnders Carlsson   CallArgList Args;
34627da15baSAnders Carlsson 
34727da15baSAnders Carlsson   QualType ThisType =
34827da15baSAnders Carlsson     getContext().getPointerType(getContext().getTagDeclType(RD));
34927da15baSAnders Carlsson 
35027da15baSAnders Carlsson   // Push the this ptr.
3517f416cc4SJohn McCall   Args.add(RValue::get(ThisPtrForCall), ThisType);
35227da15baSAnders Carlsson 
353419996ccSGeorge Burgess IV   RequiredArgs required =
354419996ccSGeorge Burgess IV       RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
3558dda7b27SJohn McCall 
35627da15baSAnders Carlsson   // And the rest of the call args
357419996ccSGeorge Burgess IV   EmitCallArgs(Args, FPT, E->arguments());
3585fa40c3bSNick Lewycky   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
3595fa40c3bSNick Lewycky                   Callee, ReturnValue, Args);
36027da15baSAnders Carlsson }
36127da15baSAnders Carlsson 
36227da15baSAnders Carlsson RValue
36327da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
36427da15baSAnders Carlsson                                                const CXXMethodDecl *MD,
36527da15baSAnders Carlsson                                                ReturnValueSlot ReturnValue) {
36627da15baSAnders Carlsson   assert(MD->isInstance() &&
36727da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
368aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
369aad4af6dSNico Weber       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
370aad4af6dSNico Weber       /*IsArrow=*/false, E->getArg(0));
37127da15baSAnders Carlsson }
37227da15baSAnders Carlsson 
373fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
374fe883422SPeter Collingbourne                                                ReturnValueSlot ReturnValue) {
375fe883422SPeter Collingbourne   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
376fe883422SPeter Collingbourne }
377fe883422SPeter Collingbourne 
378fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
3797f416cc4SJohn McCall                                             Address DestPtr,
380fde961dbSEli Friedman                                             const CXXRecordDecl *Base) {
381fde961dbSEli Friedman   if (Base->isEmpty())
382fde961dbSEli Friedman     return;
383fde961dbSEli Friedman 
3847f416cc4SJohn McCall   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
385fde961dbSEli Friedman 
386fde961dbSEli Friedman   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
3878671c6e0SDavid Majnemer   CharUnits NVSize = Layout.getNonVirtualSize();
3888671c6e0SDavid Majnemer 
3898671c6e0SDavid Majnemer   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
3908671c6e0SDavid Majnemer   // present, they are initialized by the most derived class before calling the
3918671c6e0SDavid Majnemer   // constructor.
3928671c6e0SDavid Majnemer   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
3938671c6e0SDavid Majnemer   Stores.emplace_back(CharUnits::Zero(), NVSize);
3948671c6e0SDavid Majnemer 
3958671c6e0SDavid Majnemer   // Each store is split by the existence of a vbptr.
3968671c6e0SDavid Majnemer   CharUnits VBPtrWidth = CGF.getPointerSize();
3978671c6e0SDavid Majnemer   std::vector<CharUnits> VBPtrOffsets =
3988671c6e0SDavid Majnemer       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
3998671c6e0SDavid Majnemer   for (CharUnits VBPtrOffset : VBPtrOffsets) {
4007f980d84SDavid Majnemer     // Stop before we hit any virtual base pointers located in virtual bases.
4017f980d84SDavid Majnemer     if (VBPtrOffset >= NVSize)
4027f980d84SDavid Majnemer       break;
4038671c6e0SDavid Majnemer     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
4048671c6e0SDavid Majnemer     CharUnits LastStoreOffset = LastStore.first;
4058671c6e0SDavid Majnemer     CharUnits LastStoreSize = LastStore.second;
4068671c6e0SDavid Majnemer 
4078671c6e0SDavid Majnemer     CharUnits SplitBeforeOffset = LastStoreOffset;
4088671c6e0SDavid Majnemer     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
4098671c6e0SDavid Majnemer     assert(!SplitBeforeSize.isNegative() && "negative store size!");
4108671c6e0SDavid Majnemer     if (!SplitBeforeSize.isZero())
4118671c6e0SDavid Majnemer       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
4128671c6e0SDavid Majnemer 
4138671c6e0SDavid Majnemer     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
4148671c6e0SDavid Majnemer     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
4158671c6e0SDavid Majnemer     assert(!SplitAfterSize.isNegative() && "negative store size!");
4168671c6e0SDavid Majnemer     if (!SplitAfterSize.isZero())
4178671c6e0SDavid Majnemer       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
4188671c6e0SDavid Majnemer   }
419fde961dbSEli Friedman 
420fde961dbSEli Friedman   // If the type contains a pointer to data member we can't memset it to zero.
421fde961dbSEli Friedman   // Instead, create a null constant and copy it to the destination.
422fde961dbSEli Friedman   // TODO: there are other patterns besides zero that we can usefully memset,
423fde961dbSEli Friedman   // like -1, which happens to be the pattern used by member-pointers.
424fde961dbSEli Friedman   // TODO: isZeroInitializable can be over-conservative in the case where a
425fde961dbSEli Friedman   // virtual base contains a member pointer.
4268671c6e0SDavid Majnemer   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
4278671c6e0SDavid Majnemer   if (!NullConstantForBase->isNullValue()) {
4288671c6e0SDavid Majnemer     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
4298671c6e0SDavid Majnemer         CGF.CGM.getModule(), NullConstantForBase->getType(),
4308671c6e0SDavid Majnemer         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
4318671c6e0SDavid Majnemer         NullConstantForBase, Twine());
4327f416cc4SJohn McCall 
4337f416cc4SJohn McCall     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
4347f416cc4SJohn McCall                                DestPtr.getAlignment());
435fde961dbSEli Friedman     NullVariable->setAlignment(Align.getQuantity());
4367f416cc4SJohn McCall 
4377f416cc4SJohn McCall     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
438fde961dbSEli Friedman 
439fde961dbSEli Friedman     // Get and call the appropriate llvm.memcpy overload.
4408671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
4418671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
4428671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
4438671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
4448671c6e0SDavid Majnemer       CGF.Builder.CreateMemCpy(
4458671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
4468671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
4478671c6e0SDavid Majnemer           StoreSizeVal);
448fde961dbSEli Friedman     }
449fde961dbSEli Friedman 
450fde961dbSEli Friedman   // Otherwise, just memset the whole thing to zero.  This is legal
451fde961dbSEli Friedman   // because in LLVM, all default initializers (other than the ones we just
452fde961dbSEli Friedman   // handled above) are guaranteed to have a bit pattern of all zeros.
4538671c6e0SDavid Majnemer   } else {
4548671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
4558671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
4568671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
4578671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
4588671c6e0SDavid Majnemer       CGF.Builder.CreateMemSet(
4598671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
4608671c6e0SDavid Majnemer           CGF.Builder.getInt8(0), StoreSizeVal);
4618671c6e0SDavid Majnemer     }
4628671c6e0SDavid Majnemer   }
463fde961dbSEli Friedman }
464fde961dbSEli Friedman 
46527da15baSAnders Carlsson void
4667a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
4677a626f63SJohn McCall                                       AggValueSlot Dest) {
4687a626f63SJohn McCall   assert(!Dest.isIgnored() && "Must have a destination!");
46927da15baSAnders Carlsson   const CXXConstructorDecl *CD = E->getConstructor();
470630c76efSDouglas Gregor 
471630c76efSDouglas Gregor   // If we require zero initialization before (or instead of) calling the
472630c76efSDouglas Gregor   // constructor, as can be the case with a non-user-provided default
47303535265SArgyrios Kyrtzidis   // constructor, emit the zero initialization now, unless destination is
47403535265SArgyrios Kyrtzidis   // already zeroed.
475fde961dbSEli Friedman   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
476fde961dbSEli Friedman     switch (E->getConstructionKind()) {
477fde961dbSEli Friedman     case CXXConstructExpr::CK_Delegating:
478fde961dbSEli Friedman     case CXXConstructExpr::CK_Complete:
4797f416cc4SJohn McCall       EmitNullInitialization(Dest.getAddress(), E->getType());
480fde961dbSEli Friedman       break;
481fde961dbSEli Friedman     case CXXConstructExpr::CK_VirtualBase:
482fde961dbSEli Friedman     case CXXConstructExpr::CK_NonVirtualBase:
4837f416cc4SJohn McCall       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
4847f416cc4SJohn McCall                                       CD->getParent());
485fde961dbSEli Friedman       break;
486fde961dbSEli Friedman     }
487fde961dbSEli Friedman   }
488630c76efSDouglas Gregor 
489630c76efSDouglas Gregor   // If this is a call to a trivial default constructor, do nothing.
490630c76efSDouglas Gregor   if (CD->isTrivial() && CD->isDefaultConstructor())
49127da15baSAnders Carlsson     return;
492630c76efSDouglas Gregor 
4938ea46b66SJohn McCall   // Elide the constructor if we're constructing from a temporary.
4948ea46b66SJohn McCall   // The temporary check is required because Sema sets this on NRVO
4958ea46b66SJohn McCall   // returns.
4969c6890a7SRichard Smith   if (getLangOpts().ElideConstructors && E->isElidable()) {
4978ea46b66SJohn McCall     assert(getContext().hasSameUnqualifiedType(E->getType(),
4988ea46b66SJohn McCall                                                E->getArg(0)->getType()));
4997a626f63SJohn McCall     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
5007a626f63SJohn McCall       EmitAggExpr(E->getArg(0), Dest);
50127da15baSAnders Carlsson       return;
50227da15baSAnders Carlsson     }
503222cf0efSDouglas Gregor   }
504630c76efSDouglas Gregor 
505e7545b33SAlexey Bataev   if (const ArrayType *arrayType
506e7545b33SAlexey Bataev         = getContext().getAsArrayType(E->getType())) {
5077f416cc4SJohn McCall     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
508f677a8e9SJohn McCall   } else {
509bceca20aSCameron Esfahani     CXXCtorType Type = Ctor_Complete;
510271c3681SAlexis Hunt     bool ForVirtualBase = false;
51161535005SDouglas Gregor     bool Delegating = false;
512271c3681SAlexis Hunt 
513271c3681SAlexis Hunt     switch (E->getConstructionKind()) {
514271c3681SAlexis Hunt      case CXXConstructExpr::CK_Delegating:
51561bc1737SAlexis Hunt       // We should be emitting a constructor; GlobalDecl will assert this
51661bc1737SAlexis Hunt       Type = CurGD.getCtorType();
51761535005SDouglas Gregor       Delegating = true;
518271c3681SAlexis Hunt       break;
51961bc1737SAlexis Hunt 
520271c3681SAlexis Hunt      case CXXConstructExpr::CK_Complete:
521271c3681SAlexis Hunt       Type = Ctor_Complete;
522271c3681SAlexis Hunt       break;
523271c3681SAlexis Hunt 
524271c3681SAlexis Hunt      case CXXConstructExpr::CK_VirtualBase:
525271c3681SAlexis Hunt       ForVirtualBase = true;
526271c3681SAlexis Hunt       // fall-through
527271c3681SAlexis Hunt 
528271c3681SAlexis Hunt      case CXXConstructExpr::CK_NonVirtualBase:
529271c3681SAlexis Hunt       Type = Ctor_Base;
530271c3681SAlexis Hunt     }
531e11f9ce9SAnders Carlsson 
53227da15baSAnders Carlsson     // Call the constructor.
5337f416cc4SJohn McCall     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
5347f416cc4SJohn McCall                            Dest.getAddress(), E);
53527da15baSAnders Carlsson   }
536e11f9ce9SAnders Carlsson }
53727da15baSAnders Carlsson 
5387f416cc4SJohn McCall void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
53950198098SFariborz Jahanian                                                  const Expr *Exp) {
5405d413781SJohn McCall   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
541e988bdacSFariborz Jahanian     Exp = E->getSubExpr();
542e988bdacSFariborz Jahanian   assert(isa<CXXConstructExpr>(Exp) &&
543e988bdacSFariborz Jahanian          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
544e988bdacSFariborz Jahanian   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
545e988bdacSFariborz Jahanian   const CXXConstructorDecl *CD = E->getConstructor();
546e988bdacSFariborz Jahanian   RunCleanupsScope Scope(*this);
547e988bdacSFariborz Jahanian 
548e988bdacSFariborz Jahanian   // If we require zero initialization before (or instead of) calling the
549e988bdacSFariborz Jahanian   // constructor, as can be the case with a non-user-provided default
550e988bdacSFariborz Jahanian   // constructor, emit the zero initialization now.
551e988bdacSFariborz Jahanian   // FIXME. Do I still need this for a copy ctor synthesis?
552e988bdacSFariborz Jahanian   if (E->requiresZeroInitialization())
553e988bdacSFariborz Jahanian     EmitNullInitialization(Dest, E->getType());
554e988bdacSFariborz Jahanian 
55599da11cfSChandler Carruth   assert(!getContext().getAsConstantArrayType(E->getType())
55699da11cfSChandler Carruth          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
557525bf650SAlexey Samsonov   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
558e988bdacSFariborz Jahanian }
559e988bdacSFariborz Jahanian 
5608ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
5618ed55a54SJohn McCall                                         const CXXNewExpr *E) {
56221122cf6SAnders Carlsson   if (!E->isArray())
5633eb55cfeSKen Dyck     return CharUnits::Zero();
56421122cf6SAnders Carlsson 
5657ec4b434SJohn McCall   // No cookie is required if the operator new[] being used is the
5667ec4b434SJohn McCall   // reserved placement operator new[].
5677ec4b434SJohn McCall   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
5683eb55cfeSKen Dyck     return CharUnits::Zero();
569399f499fSAnders Carlsson 
570284c48ffSJohn McCall   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
57159486a2dSAnders Carlsson }
57259486a2dSAnders Carlsson 
573036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
574036f2f6bSJohn McCall                                         const CXXNewExpr *e,
575f862eb6aSSebastian Redl                                         unsigned minElements,
576036f2f6bSJohn McCall                                         llvm::Value *&numElements,
577036f2f6bSJohn McCall                                         llvm::Value *&sizeWithoutCookie) {
578036f2f6bSJohn McCall   QualType type = e->getAllocatedType();
57959486a2dSAnders Carlsson 
580036f2f6bSJohn McCall   if (!e->isArray()) {
581036f2f6bSJohn McCall     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
582036f2f6bSJohn McCall     sizeWithoutCookie
583036f2f6bSJohn McCall       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
584036f2f6bSJohn McCall     return sizeWithoutCookie;
58505fc5be3SDouglas Gregor   }
58659486a2dSAnders Carlsson 
587036f2f6bSJohn McCall   // The width of size_t.
588036f2f6bSJohn McCall   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
589036f2f6bSJohn McCall 
5908ed55a54SJohn McCall   // Figure out the cookie size.
591036f2f6bSJohn McCall   llvm::APInt cookieSize(sizeWidth,
592036f2f6bSJohn McCall                          CalculateCookiePadding(CGF, e).getQuantity());
5938ed55a54SJohn McCall 
59459486a2dSAnders Carlsson   // Emit the array size expression.
5957648fb46SArgyrios Kyrtzidis   // We multiply the size of all dimensions for NumElements.
5967648fb46SArgyrios Kyrtzidis   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
597036f2f6bSJohn McCall   numElements = CGF.EmitScalarExpr(e->getArraySize());
598036f2f6bSJohn McCall   assert(isa<llvm::IntegerType>(numElements->getType()));
5998ed55a54SJohn McCall 
600036f2f6bSJohn McCall   // The number of elements can be have an arbitrary integer type;
601036f2f6bSJohn McCall   // essentially, we need to multiply it by a constant factor, add a
602036f2f6bSJohn McCall   // cookie size, and verify that the result is representable as a
603036f2f6bSJohn McCall   // size_t.  That's just a gloss, though, and it's wrong in one
604036f2f6bSJohn McCall   // important way: if the count is negative, it's an error even if
605036f2f6bSJohn McCall   // the cookie size would bring the total size >= 0.
6066ab2fa8fSDouglas Gregor   bool isSigned
6076ab2fa8fSDouglas Gregor     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
6082192fe50SChris Lattner   llvm::IntegerType *numElementsType
609036f2f6bSJohn McCall     = cast<llvm::IntegerType>(numElements->getType());
610036f2f6bSJohn McCall   unsigned numElementsWidth = numElementsType->getBitWidth();
611036f2f6bSJohn McCall 
612036f2f6bSJohn McCall   // Compute the constant factor.
613036f2f6bSJohn McCall   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
6147648fb46SArgyrios Kyrtzidis   while (const ConstantArrayType *CAT
615036f2f6bSJohn McCall              = CGF.getContext().getAsConstantArrayType(type)) {
616036f2f6bSJohn McCall     type = CAT->getElementType();
617036f2f6bSJohn McCall     arraySizeMultiplier *= CAT->getSize();
6187648fb46SArgyrios Kyrtzidis   }
61959486a2dSAnders Carlsson 
620036f2f6bSJohn McCall   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
621036f2f6bSJohn McCall   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
622036f2f6bSJohn McCall   typeSizeMultiplier *= arraySizeMultiplier;
623036f2f6bSJohn McCall 
624036f2f6bSJohn McCall   // This will be a size_t.
625036f2f6bSJohn McCall   llvm::Value *size;
62632ac583dSChris Lattner 
62732ac583dSChris Lattner   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
62832ac583dSChris Lattner   // Don't bloat the -O0 code.
629036f2f6bSJohn McCall   if (llvm::ConstantInt *numElementsC =
630036f2f6bSJohn McCall         dyn_cast<llvm::ConstantInt>(numElements)) {
631036f2f6bSJohn McCall     const llvm::APInt &count = numElementsC->getValue();
63232ac583dSChris Lattner 
633036f2f6bSJohn McCall     bool hasAnyOverflow = false;
63432ac583dSChris Lattner 
635036f2f6bSJohn McCall     // If 'count' was a negative number, it's an overflow.
636036f2f6bSJohn McCall     if (isSigned && count.isNegative())
637036f2f6bSJohn McCall       hasAnyOverflow = true;
6388ed55a54SJohn McCall 
639036f2f6bSJohn McCall     // We want to do all this arithmetic in size_t.  If numElements is
640036f2f6bSJohn McCall     // wider than that, check whether it's already too big, and if so,
641036f2f6bSJohn McCall     // overflow.
642036f2f6bSJohn McCall     else if (numElementsWidth > sizeWidth &&
643036f2f6bSJohn McCall              numElementsWidth - sizeWidth > count.countLeadingZeros())
644036f2f6bSJohn McCall       hasAnyOverflow = true;
645036f2f6bSJohn McCall 
646036f2f6bSJohn McCall     // Okay, compute a count at the right width.
647036f2f6bSJohn McCall     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
648036f2f6bSJohn McCall 
649f862eb6aSSebastian Redl     // If there is a brace-initializer, we cannot allocate fewer elements than
650f862eb6aSSebastian Redl     // there are initializers. If we do, that's treated like an overflow.
651f862eb6aSSebastian Redl     if (adjustedCount.ult(minElements))
652f862eb6aSSebastian Redl       hasAnyOverflow = true;
653f862eb6aSSebastian Redl 
654036f2f6bSJohn McCall     // Scale numElements by that.  This might overflow, but we don't
655036f2f6bSJohn McCall     // care because it only overflows if allocationSize does, too, and
656036f2f6bSJohn McCall     // if that overflows then we shouldn't use this.
657036f2f6bSJohn McCall     numElements = llvm::ConstantInt::get(CGF.SizeTy,
658036f2f6bSJohn McCall                                          adjustedCount * arraySizeMultiplier);
659036f2f6bSJohn McCall 
660036f2f6bSJohn McCall     // Compute the size before cookie, and track whether it overflowed.
661036f2f6bSJohn McCall     bool overflow;
662036f2f6bSJohn McCall     llvm::APInt allocationSize
663036f2f6bSJohn McCall       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
664036f2f6bSJohn McCall     hasAnyOverflow |= overflow;
665036f2f6bSJohn McCall 
666036f2f6bSJohn McCall     // Add in the cookie, and check whether it's overflowed.
667036f2f6bSJohn McCall     if (cookieSize != 0) {
668036f2f6bSJohn McCall       // Save the current size without a cookie.  This shouldn't be
669036f2f6bSJohn McCall       // used if there was overflow.
670036f2f6bSJohn McCall       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
671036f2f6bSJohn McCall 
672036f2f6bSJohn McCall       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
673036f2f6bSJohn McCall       hasAnyOverflow |= overflow;
6748ed55a54SJohn McCall     }
6758ed55a54SJohn McCall 
676036f2f6bSJohn McCall     // On overflow, produce a -1 so operator new will fail.
677455f42c9SAaron Ballman     if (hasAnyOverflow) {
678455f42c9SAaron Ballman       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
679455f42c9SAaron Ballman     } else {
680036f2f6bSJohn McCall       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
681455f42c9SAaron Ballman     }
68232ac583dSChris Lattner 
683036f2f6bSJohn McCall   // Otherwise, we might need to use the overflow intrinsics.
6848ed55a54SJohn McCall   } else {
685f862eb6aSSebastian Redl     // There are up to five conditions we need to test for:
686036f2f6bSJohn McCall     // 1) if isSigned, we need to check whether numElements is negative;
687036f2f6bSJohn McCall     // 2) if numElementsWidth > sizeWidth, we need to check whether
688036f2f6bSJohn McCall     //   numElements is larger than something representable in size_t;
689f862eb6aSSebastian Redl     // 3) if minElements > 0, we need to check whether numElements is smaller
690f862eb6aSSebastian Redl     //    than that.
691f862eb6aSSebastian Redl     // 4) we need to compute
692036f2f6bSJohn McCall     //      sizeWithoutCookie := numElements * typeSizeMultiplier
693036f2f6bSJohn McCall     //    and check whether it overflows; and
694f862eb6aSSebastian Redl     // 5) if we need a cookie, we need to compute
695036f2f6bSJohn McCall     //      size := sizeWithoutCookie + cookieSize
696036f2f6bSJohn McCall     //    and check whether it overflows.
6978ed55a54SJohn McCall 
6988a13c418SCraig Topper     llvm::Value *hasOverflow = nullptr;
6998ed55a54SJohn McCall 
700036f2f6bSJohn McCall     // If numElementsWidth > sizeWidth, then one way or another, we're
701036f2f6bSJohn McCall     // going to have to do a comparison for (2), and this happens to
702036f2f6bSJohn McCall     // take care of (1), too.
703036f2f6bSJohn McCall     if (numElementsWidth > sizeWidth) {
704036f2f6bSJohn McCall       llvm::APInt threshold(numElementsWidth, 1);
705036f2f6bSJohn McCall       threshold <<= sizeWidth;
7068ed55a54SJohn McCall 
707036f2f6bSJohn McCall       llvm::Value *thresholdV
708036f2f6bSJohn McCall         = llvm::ConstantInt::get(numElementsType, threshold);
709036f2f6bSJohn McCall 
710036f2f6bSJohn McCall       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
711036f2f6bSJohn McCall       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
712036f2f6bSJohn McCall 
713036f2f6bSJohn McCall     // Otherwise, if we're signed, we want to sext up to size_t.
714036f2f6bSJohn McCall     } else if (isSigned) {
715036f2f6bSJohn McCall       if (numElementsWidth < sizeWidth)
716036f2f6bSJohn McCall         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
717036f2f6bSJohn McCall 
718036f2f6bSJohn McCall       // If there's a non-1 type size multiplier, then we can do the
719036f2f6bSJohn McCall       // signedness check at the same time as we do the multiply
720036f2f6bSJohn McCall       // because a negative number times anything will cause an
721f862eb6aSSebastian Redl       // unsigned overflow.  Otherwise, we have to do it here. But at least
722f862eb6aSSebastian Redl       // in this case, we can subsume the >= minElements check.
723036f2f6bSJohn McCall       if (typeSizeMultiplier == 1)
724036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
725f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
726036f2f6bSJohn McCall 
727036f2f6bSJohn McCall     // Otherwise, zext up to size_t if necessary.
728036f2f6bSJohn McCall     } else if (numElementsWidth < sizeWidth) {
729036f2f6bSJohn McCall       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
730036f2f6bSJohn McCall     }
731036f2f6bSJohn McCall 
732036f2f6bSJohn McCall     assert(numElements->getType() == CGF.SizeTy);
733036f2f6bSJohn McCall 
734f862eb6aSSebastian Redl     if (minElements) {
735f862eb6aSSebastian Redl       // Don't allow allocation of fewer elements than we have initializers.
736f862eb6aSSebastian Redl       if (!hasOverflow) {
737f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
738f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
739f862eb6aSSebastian Redl       } else if (numElementsWidth > sizeWidth) {
740f862eb6aSSebastian Redl         // The other existing overflow subsumes this check.
741f862eb6aSSebastian Redl         // We do an unsigned comparison, since any signed value < -1 is
742f862eb6aSSebastian Redl         // taken care of either above or below.
743f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
744f862eb6aSSebastian Redl                           CGF.Builder.CreateICmpULT(numElements,
745f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
746f862eb6aSSebastian Redl       }
747f862eb6aSSebastian Redl     }
748f862eb6aSSebastian Redl 
749036f2f6bSJohn McCall     size = numElements;
750036f2f6bSJohn McCall 
751036f2f6bSJohn McCall     // Multiply by the type size if necessary.  This multiplier
752036f2f6bSJohn McCall     // includes all the factors for nested arrays.
7538ed55a54SJohn McCall     //
754036f2f6bSJohn McCall     // This step also causes numElements to be scaled up by the
755036f2f6bSJohn McCall     // nested-array factor if necessary.  Overflow on this computation
756036f2f6bSJohn McCall     // can be ignored because the result shouldn't be used if
757036f2f6bSJohn McCall     // allocation fails.
758036f2f6bSJohn McCall     if (typeSizeMultiplier != 1) {
759036f2f6bSJohn McCall       llvm::Value *umul_with_overflow
7608d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
7618ed55a54SJohn McCall 
762036f2f6bSJohn McCall       llvm::Value *tsmV =
763036f2f6bSJohn McCall         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
764036f2f6bSJohn McCall       llvm::Value *result =
76543f9bb73SDavid Blaikie           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
7668ed55a54SJohn McCall 
767036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
768036f2f6bSJohn McCall       if (hasOverflow)
769036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
7708ed55a54SJohn McCall       else
771036f2f6bSJohn McCall         hasOverflow = overflowed;
77259486a2dSAnders Carlsson 
773036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
774036f2f6bSJohn McCall 
775036f2f6bSJohn McCall       // Also scale up numElements by the array size multiplier.
776036f2f6bSJohn McCall       if (arraySizeMultiplier != 1) {
777036f2f6bSJohn McCall         // If the base element type size is 1, then we can re-use the
778036f2f6bSJohn McCall         // multiply we just did.
779036f2f6bSJohn McCall         if (typeSize.isOne()) {
780036f2f6bSJohn McCall           assert(arraySizeMultiplier == typeSizeMultiplier);
781036f2f6bSJohn McCall           numElements = size;
782036f2f6bSJohn McCall 
783036f2f6bSJohn McCall         // Otherwise we need a separate multiply.
784036f2f6bSJohn McCall         } else {
785036f2f6bSJohn McCall           llvm::Value *asmV =
786036f2f6bSJohn McCall             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
787036f2f6bSJohn McCall           numElements = CGF.Builder.CreateMul(numElements, asmV);
788036f2f6bSJohn McCall         }
789036f2f6bSJohn McCall       }
790036f2f6bSJohn McCall     } else {
791036f2f6bSJohn McCall       // numElements doesn't need to be scaled.
792036f2f6bSJohn McCall       assert(arraySizeMultiplier == 1);
793036f2f6bSJohn McCall     }
794036f2f6bSJohn McCall 
795036f2f6bSJohn McCall     // Add in the cookie size if necessary.
796036f2f6bSJohn McCall     if (cookieSize != 0) {
797036f2f6bSJohn McCall       sizeWithoutCookie = size;
798036f2f6bSJohn McCall 
799036f2f6bSJohn McCall       llvm::Value *uadd_with_overflow
8008d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
801036f2f6bSJohn McCall 
802036f2f6bSJohn McCall       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
803036f2f6bSJohn McCall       llvm::Value *result =
80443f9bb73SDavid Blaikie           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
805036f2f6bSJohn McCall 
806036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
807036f2f6bSJohn McCall       if (hasOverflow)
808036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
809036f2f6bSJohn McCall       else
810036f2f6bSJohn McCall         hasOverflow = overflowed;
811036f2f6bSJohn McCall 
812036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
813036f2f6bSJohn McCall     }
814036f2f6bSJohn McCall 
815036f2f6bSJohn McCall     // If we had any possibility of dynamic overflow, make a select to
816036f2f6bSJohn McCall     // overwrite 'size' with an all-ones value, which should cause
817036f2f6bSJohn McCall     // operator new to throw.
818036f2f6bSJohn McCall     if (hasOverflow)
819455f42c9SAaron Ballman       size = CGF.Builder.CreateSelect(hasOverflow,
820455f42c9SAaron Ballman                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
821036f2f6bSJohn McCall                                       size);
822036f2f6bSJohn McCall   }
823036f2f6bSJohn McCall 
824036f2f6bSJohn McCall   if (cookieSize == 0)
825036f2f6bSJohn McCall     sizeWithoutCookie = size;
826036f2f6bSJohn McCall   else
827036f2f6bSJohn McCall     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
828036f2f6bSJohn McCall 
829036f2f6bSJohn McCall   return size;
83059486a2dSAnders Carlsson }
83159486a2dSAnders Carlsson 
832f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
8337f416cc4SJohn McCall                                     QualType AllocType, Address NewPtr) {
8341c96bc5dSRichard Smith   // FIXME: Refactor with EmitExprAsInit.
83547fb9508SJohn McCall   switch (CGF.getEvaluationKind(AllocType)) {
83647fb9508SJohn McCall   case TEK_Scalar:
837a2c1124fSDavid Blaikie     CGF.EmitScalarInit(Init, nullptr,
8387f416cc4SJohn McCall                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
83947fb9508SJohn McCall     return;
84047fb9508SJohn McCall   case TEK_Complex:
8417f416cc4SJohn McCall     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
84247fb9508SJohn McCall                                   /*isInit*/ true);
84347fb9508SJohn McCall     return;
84447fb9508SJohn McCall   case TEK_Aggregate: {
8457a626f63SJohn McCall     AggValueSlot Slot
8467f416cc4SJohn McCall       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
8478d6fc958SJohn McCall                               AggValueSlot::IsDestructed,
84846759f4fSJohn McCall                               AggValueSlot::DoesNotNeedGCBarriers,
849615ed1a3SChad Rosier                               AggValueSlot::IsNotAliased);
8507a626f63SJohn McCall     CGF.EmitAggExpr(Init, Slot);
85147fb9508SJohn McCall     return;
8527a626f63SJohn McCall   }
853d5202e09SFariborz Jahanian   }
85447fb9508SJohn McCall   llvm_unreachable("bad evaluation kind");
85547fb9508SJohn McCall }
856d5202e09SFariborz Jahanian 
857fb901c7aSDavid Blaikie void CodeGenFunction::EmitNewArrayInitializer(
858fb901c7aSDavid Blaikie     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
8597f416cc4SJohn McCall     Address BeginPtr, llvm::Value *NumElements,
86006a67e2cSRichard Smith     llvm::Value *AllocSizeWithoutCookie) {
86106a67e2cSRichard Smith   // If we have a type with trivial initialization and no initializer,
86206a67e2cSRichard Smith   // there's nothing to do.
8636047f07eSSebastian Redl   if (!E->hasInitializer())
86406a67e2cSRichard Smith     return;
865b66b08efSFariborz Jahanian 
8667f416cc4SJohn McCall   Address CurPtr = BeginPtr;
867d5202e09SFariborz Jahanian 
86806a67e2cSRichard Smith   unsigned InitListElements = 0;
869f862eb6aSSebastian Redl 
870f862eb6aSSebastian Redl   const Expr *Init = E->getInitializer();
8717f416cc4SJohn McCall   Address EndOfInit = Address::invalid();
87206a67e2cSRichard Smith   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
87306a67e2cSRichard Smith   EHScopeStack::stable_iterator Cleanup;
87406a67e2cSRichard Smith   llvm::Instruction *CleanupDominator = nullptr;
8751c96bc5dSRichard Smith 
8767f416cc4SJohn McCall   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
8777f416cc4SJohn McCall   CharUnits ElementAlign =
8787f416cc4SJohn McCall     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
8797f416cc4SJohn McCall 
8800511d23aSRichard Smith   // Attempt to perform zero-initialization using memset.
8810511d23aSRichard Smith   auto TryMemsetInitialization = [&]() -> bool {
8820511d23aSRichard Smith     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
8830511d23aSRichard Smith     // we can initialize with a memset to -1.
8840511d23aSRichard Smith     if (!CGM.getTypes().isZeroInitializable(ElementType))
8850511d23aSRichard Smith       return false;
8860511d23aSRichard Smith 
8870511d23aSRichard Smith     // Optimization: since zero initialization will just set the memory
8880511d23aSRichard Smith     // to all zeroes, generate a single memset to do it in one shot.
8890511d23aSRichard Smith 
8900511d23aSRichard Smith     // Subtract out the size of any elements we've already initialized.
8910511d23aSRichard Smith     auto *RemainingSize = AllocSizeWithoutCookie;
8920511d23aSRichard Smith     if (InitListElements) {
8930511d23aSRichard Smith       // We know this can't overflow; we check this when doing the allocation.
8940511d23aSRichard Smith       auto *InitializedSize = llvm::ConstantInt::get(
8950511d23aSRichard Smith           RemainingSize->getType(),
8960511d23aSRichard Smith           getContext().getTypeSizeInChars(ElementType).getQuantity() *
8970511d23aSRichard Smith               InitListElements);
8980511d23aSRichard Smith       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
8990511d23aSRichard Smith     }
9000511d23aSRichard Smith 
9010511d23aSRichard Smith     // Create the memset.
9020511d23aSRichard Smith     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
9030511d23aSRichard Smith     return true;
9040511d23aSRichard Smith   };
9050511d23aSRichard Smith 
906f862eb6aSSebastian Redl   // If the initializer is an initializer list, first do the explicit elements.
907f862eb6aSSebastian Redl   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
9080511d23aSRichard Smith     // Initializing from a (braced) string literal is a special case; the init
9090511d23aSRichard Smith     // list element does not initialize a (single) array element.
9100511d23aSRichard Smith     if (ILE->isStringLiteralInit()) {
9110511d23aSRichard Smith       // Initialize the initial portion of length equal to that of the string
9120511d23aSRichard Smith       // literal. The allocation must be for at least this much; we emitted a
9130511d23aSRichard Smith       // check for that earlier.
9140511d23aSRichard Smith       AggValueSlot Slot =
9150511d23aSRichard Smith           AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
9160511d23aSRichard Smith                                 AggValueSlot::IsDestructed,
9170511d23aSRichard Smith                                 AggValueSlot::DoesNotNeedGCBarriers,
9180511d23aSRichard Smith                                 AggValueSlot::IsNotAliased);
9190511d23aSRichard Smith       EmitAggExpr(ILE->getInit(0), Slot);
9200511d23aSRichard Smith 
9210511d23aSRichard Smith       // Move past these elements.
9220511d23aSRichard Smith       InitListElements =
9230511d23aSRichard Smith           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
9240511d23aSRichard Smith               ->getSize().getZExtValue();
9250511d23aSRichard Smith       CurPtr =
9260511d23aSRichard Smith           Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
9270511d23aSRichard Smith                                             Builder.getSize(InitListElements),
9280511d23aSRichard Smith                                             "string.init.end"),
9290511d23aSRichard Smith                   CurPtr.getAlignment().alignmentAtOffset(InitListElements *
9300511d23aSRichard Smith                                                           ElementSize));
9310511d23aSRichard Smith 
9320511d23aSRichard Smith       // Zero out the rest, if any remain.
9330511d23aSRichard Smith       llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
9340511d23aSRichard Smith       if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
9350511d23aSRichard Smith         bool OK = TryMemsetInitialization();
9360511d23aSRichard Smith         (void)OK;
9370511d23aSRichard Smith         assert(OK && "couldn't memset character type?");
9380511d23aSRichard Smith       }
9390511d23aSRichard Smith       return;
9400511d23aSRichard Smith     }
9410511d23aSRichard Smith 
94206a67e2cSRichard Smith     InitListElements = ILE->getNumInits();
943f62290a1SChad Rosier 
9441c96bc5dSRichard Smith     // If this is a multi-dimensional array new, we will initialize multiple
9451c96bc5dSRichard Smith     // elements with each init list element.
9461c96bc5dSRichard Smith     QualType AllocType = E->getAllocatedType();
9471c96bc5dSRichard Smith     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
9481c96bc5dSRichard Smith             AllocType->getAsArrayTypeUnsafe())) {
949fb901c7aSDavid Blaikie       ElementTy = ConvertTypeForMem(AllocType);
9507f416cc4SJohn McCall       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
95106a67e2cSRichard Smith       InitListElements *= getContext().getConstantArrayElementCount(CAT);
9521c96bc5dSRichard Smith     }
9531c96bc5dSRichard Smith 
95406a67e2cSRichard Smith     // Enter a partial-destruction Cleanup if necessary.
95506a67e2cSRichard Smith     if (needsEHCleanup(DtorKind)) {
95606a67e2cSRichard Smith       // In principle we could tell the Cleanup where we are more
957f62290a1SChad Rosier       // directly, but the control flow can get so varied here that it
958f62290a1SChad Rosier       // would actually be quite complex.  Therefore we go through an
959f62290a1SChad Rosier       // alloca.
9607f416cc4SJohn McCall       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
9617f416cc4SJohn McCall                                    "array.init.end");
9627f416cc4SJohn McCall       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
9637f416cc4SJohn McCall       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
9647f416cc4SJohn McCall                                        ElementType, ElementAlign,
96506a67e2cSRichard Smith                                        getDestroyer(DtorKind));
96606a67e2cSRichard Smith       Cleanup = EHStack.stable_begin();
967f62290a1SChad Rosier     }
968f62290a1SChad Rosier 
9697f416cc4SJohn McCall     CharUnits StartAlign = CurPtr.getAlignment();
970f862eb6aSSebastian Redl     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
971f62290a1SChad Rosier       // Tell the cleanup that it needs to destroy up to this
972f62290a1SChad Rosier       // element.  TODO: some of these stores can be trivially
973f62290a1SChad Rosier       // observed to be unnecessary.
9747f416cc4SJohn McCall       if (EndOfInit.isValid()) {
9757f416cc4SJohn McCall         auto FinishedPtr =
9767f416cc4SJohn McCall           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
9777f416cc4SJohn McCall         Builder.CreateStore(FinishedPtr, EndOfInit);
9787f416cc4SJohn McCall       }
97906a67e2cSRichard Smith       // FIXME: If the last initializer is an incomplete initializer list for
98006a67e2cSRichard Smith       // an array, and we have an array filler, we can fold together the two
98106a67e2cSRichard Smith       // initialization loops.
9821c96bc5dSRichard Smith       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
98306a67e2cSRichard Smith                               ILE->getInit(i)->getType(), CurPtr);
9847f416cc4SJohn McCall       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
9857f416cc4SJohn McCall                                                  Builder.getSize(1),
9867f416cc4SJohn McCall                                                  "array.exp.next"),
9877f416cc4SJohn McCall                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
988f862eb6aSSebastian Redl     }
989f862eb6aSSebastian Redl 
990f862eb6aSSebastian Redl     // The remaining elements are filled with the array filler expression.
991f862eb6aSSebastian Redl     Init = ILE->getArrayFiller();
9921c96bc5dSRichard Smith 
99306a67e2cSRichard Smith     // Extract the initializer for the individual array elements by pulling
99406a67e2cSRichard Smith     // out the array filler from all the nested initializer lists. This avoids
99506a67e2cSRichard Smith     // generating a nested loop for the initialization.
99606a67e2cSRichard Smith     while (Init && Init->getType()->isConstantArrayType()) {
99706a67e2cSRichard Smith       auto *SubILE = dyn_cast<InitListExpr>(Init);
99806a67e2cSRichard Smith       if (!SubILE)
99906a67e2cSRichard Smith         break;
100006a67e2cSRichard Smith       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
100106a67e2cSRichard Smith       Init = SubILE->getArrayFiller();
1002f862eb6aSSebastian Redl     }
1003f862eb6aSSebastian Redl 
100406a67e2cSRichard Smith     // Switch back to initializing one base element at a time.
10057f416cc4SJohn McCall     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1006f62290a1SChad Rosier   }
1007e6c980c4SChandler Carruth 
1008454a7cdfSRichard Smith   // If all elements have already been initialized, skip any further
1009454a7cdfSRichard Smith   // initialization.
1010454a7cdfSRichard Smith   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1011454a7cdfSRichard Smith   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1012454a7cdfSRichard Smith     // If there was a Cleanup, deactivate it.
1013454a7cdfSRichard Smith     if (CleanupDominator)
1014454a7cdfSRichard Smith       DeactivateCleanupBlock(Cleanup, CleanupDominator);
1015454a7cdfSRichard Smith     return;
1016454a7cdfSRichard Smith   }
1017454a7cdfSRichard Smith 
1018454a7cdfSRichard Smith   assert(Init && "have trailing elements to initialize but no initializer");
1019454a7cdfSRichard Smith 
102006a67e2cSRichard Smith   // If this is a constructor call, try to optimize it out, and failing that
102106a67e2cSRichard Smith   // emit a single loop to initialize all remaining elements.
1022454a7cdfSRichard Smith   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10236047f07eSSebastian Redl     CXXConstructorDecl *Ctor = CCE->getConstructor();
1024d153103cSDouglas Gregor     if (Ctor->isTrivial()) {
102505fc5be3SDouglas Gregor       // If new expression did not specify value-initialization, then there
102605fc5be3SDouglas Gregor       // is no initialization.
10276047f07eSSebastian Redl       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
102805fc5be3SDouglas Gregor         return;
102905fc5be3SDouglas Gregor 
103006a67e2cSRichard Smith       if (TryMemsetInitialization())
10313a202f60SAnders Carlsson         return;
10323a202f60SAnders Carlsson     }
103305fc5be3SDouglas Gregor 
103406a67e2cSRichard Smith     // Store the new Cleanup position for irregular Cleanups.
103506a67e2cSRichard Smith     //
103606a67e2cSRichard Smith     // FIXME: Share this cleanup with the constructor call emission rather than
103706a67e2cSRichard Smith     // having it create a cleanup of its own.
10387f416cc4SJohn McCall     if (EndOfInit.isValid())
10397f416cc4SJohn McCall       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
104006a67e2cSRichard Smith 
104106a67e2cSRichard Smith     // Emit a constructor call loop to initialize the remaining elements.
104206a67e2cSRichard Smith     if (InitListElements)
104306a67e2cSRichard Smith       NumElements = Builder.CreateSub(
104406a67e2cSRichard Smith           NumElements,
104506a67e2cSRichard Smith           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
104670b9c01bSAlexey Samsonov     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
104748ddcf2cSEli Friedman                                CCE->requiresZeroInitialization());
104805fc5be3SDouglas Gregor     return;
10496047f07eSSebastian Redl   }
105006a67e2cSRichard Smith 
105106a67e2cSRichard Smith   // If this is value-initialization, we can usually use memset.
105206a67e2cSRichard Smith   ImplicitValueInitExpr IVIE(ElementType);
1053454a7cdfSRichard Smith   if (isa<ImplicitValueInitExpr>(Init)) {
105406a67e2cSRichard Smith     if (TryMemsetInitialization())
105506a67e2cSRichard Smith       return;
105606a67e2cSRichard Smith 
105706a67e2cSRichard Smith     // Switch to an ImplicitValueInitExpr for the element type. This handles
105806a67e2cSRichard Smith     // only one case: multidimensional array new of pointers to members. In
105906a67e2cSRichard Smith     // all other cases, we already have an initializer for the array element.
106006a67e2cSRichard Smith     Init = &IVIE;
106106a67e2cSRichard Smith   }
106206a67e2cSRichard Smith 
106306a67e2cSRichard Smith   // At this point we should have found an initializer for the individual
106406a67e2cSRichard Smith   // elements of the array.
106506a67e2cSRichard Smith   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
106606a67e2cSRichard Smith          "got wrong type of element to initialize");
106706a67e2cSRichard Smith 
1068454a7cdfSRichard Smith   // If we have an empty initializer list, we can usually use memset.
1069454a7cdfSRichard Smith   if (auto *ILE = dyn_cast<InitListExpr>(Init))
1070454a7cdfSRichard Smith     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1071d5202e09SFariborz Jahanian       return;
107259486a2dSAnders Carlsson 
1073cb77930dSYunzhong Gao   // If we have a struct whose every field is value-initialized, we can
1074cb77930dSYunzhong Gao   // usually use memset.
1075cb77930dSYunzhong Gao   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1076cb77930dSYunzhong Gao     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1077cb77930dSYunzhong Gao       if (RType->getDecl()->isStruct()) {
1078872307e2SRichard Smith         unsigned NumElements = 0;
1079872307e2SRichard Smith         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1080872307e2SRichard Smith           NumElements = CXXRD->getNumBases();
1081cb77930dSYunzhong Gao         for (auto *Field : RType->getDecl()->fields())
1082cb77930dSYunzhong Gao           if (!Field->isUnnamedBitfield())
1083872307e2SRichard Smith             ++NumElements;
1084872307e2SRichard Smith         // FIXME: Recurse into nested InitListExprs.
1085872307e2SRichard Smith         if (ILE->getNumInits() == NumElements)
1086cb77930dSYunzhong Gao           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1087cb77930dSYunzhong Gao             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1088872307e2SRichard Smith               --NumElements;
1089872307e2SRichard Smith         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1090cb77930dSYunzhong Gao           return;
1091cb77930dSYunzhong Gao       }
1092cb77930dSYunzhong Gao     }
1093cb77930dSYunzhong Gao   }
1094cb77930dSYunzhong Gao 
109506a67e2cSRichard Smith   // Create the loop blocks.
109606a67e2cSRichard Smith   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
109706a67e2cSRichard Smith   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
109806a67e2cSRichard Smith   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
109959486a2dSAnders Carlsson 
110006a67e2cSRichard Smith   // Find the end of the array, hoisted out of the loop.
110106a67e2cSRichard Smith   llvm::Value *EndPtr =
11027f416cc4SJohn McCall     Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
110306a67e2cSRichard Smith 
110406a67e2cSRichard Smith   // If the number of elements isn't constant, we have to now check if there is
110506a67e2cSRichard Smith   // anything left to initialize.
110606a67e2cSRichard Smith   if (!ConstNum) {
11077f416cc4SJohn McCall     llvm::Value *IsEmpty =
11087f416cc4SJohn McCall       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
110906a67e2cSRichard Smith     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
111006a67e2cSRichard Smith   }
111106a67e2cSRichard Smith 
111206a67e2cSRichard Smith   // Enter the loop.
111306a67e2cSRichard Smith   EmitBlock(LoopBB);
111406a67e2cSRichard Smith 
111506a67e2cSRichard Smith   // Set up the current-element phi.
111606a67e2cSRichard Smith   llvm::PHINode *CurPtrPhi =
11177f416cc4SJohn McCall     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
11187f416cc4SJohn McCall   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
11197f416cc4SJohn McCall 
11207f416cc4SJohn McCall   CurPtr = Address(CurPtrPhi, ElementAlign);
112106a67e2cSRichard Smith 
112206a67e2cSRichard Smith   // Store the new Cleanup position for irregular Cleanups.
11237f416cc4SJohn McCall   if (EndOfInit.isValid())
11247f416cc4SJohn McCall     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
112506a67e2cSRichard Smith 
112606a67e2cSRichard Smith   // Enter a partial-destruction Cleanup if necessary.
112706a67e2cSRichard Smith   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
11287f416cc4SJohn McCall     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
11297f416cc4SJohn McCall                                    ElementType, ElementAlign,
113006a67e2cSRichard Smith                                    getDestroyer(DtorKind));
113106a67e2cSRichard Smith     Cleanup = EHStack.stable_begin();
113206a67e2cSRichard Smith     CleanupDominator = Builder.CreateUnreachable();
113306a67e2cSRichard Smith   }
113406a67e2cSRichard Smith 
113506a67e2cSRichard Smith   // Emit the initializer into this element.
113606a67e2cSRichard Smith   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
113706a67e2cSRichard Smith 
113806a67e2cSRichard Smith   // Leave the Cleanup if we entered one.
113906a67e2cSRichard Smith   if (CleanupDominator) {
114006a67e2cSRichard Smith     DeactivateCleanupBlock(Cleanup, CleanupDominator);
114106a67e2cSRichard Smith     CleanupDominator->eraseFromParent();
114206a67e2cSRichard Smith   }
114306a67e2cSRichard Smith 
114406a67e2cSRichard Smith   // Advance to the next element by adjusting the pointer type as necessary.
114506a67e2cSRichard Smith   llvm::Value *NextPtr =
11467f416cc4SJohn McCall     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
11477f416cc4SJohn McCall                                        "array.next");
114806a67e2cSRichard Smith 
114906a67e2cSRichard Smith   // Check whether we've gotten to the end of the array and, if so,
115006a67e2cSRichard Smith   // exit the loop.
115106a67e2cSRichard Smith   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
115206a67e2cSRichard Smith   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
115306a67e2cSRichard Smith   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
115406a67e2cSRichard Smith 
115506a67e2cSRichard Smith   EmitBlock(ContBB);
115606a67e2cSRichard Smith }
115706a67e2cSRichard Smith 
115806a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1159fb901c7aSDavid Blaikie                                QualType ElementType, llvm::Type *ElementTy,
11607f416cc4SJohn McCall                                Address NewPtr, llvm::Value *NumElements,
116106a67e2cSRichard Smith                                llvm::Value *AllocSizeWithoutCookie) {
11629b479666SDavid Blaikie   ApplyDebugLocation DL(CGF, E);
116306a67e2cSRichard Smith   if (E->isArray())
1164fb901c7aSDavid Blaikie     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
116506a67e2cSRichard Smith                                 AllocSizeWithoutCookie);
116606a67e2cSRichard Smith   else if (const Expr *Init = E->getInitializer())
116766e4197fSDavid Blaikie     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
116859486a2dSAnders Carlsson }
116959486a2dSAnders Carlsson 
11708d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly
11718d0dc31dSRichard Smith /// created by new-expressions and delete-expressions.
11728d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
11738d0dc31dSRichard Smith                                 const FunctionDecl *Callee,
11748d0dc31dSRichard Smith                                 const FunctionProtoType *CalleeType,
11758d0dc31dSRichard Smith                                 const CallArgList &Args) {
11768d0dc31dSRichard Smith   llvm::Instruction *CallOrInvoke;
11771235a8daSRichard Smith   llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
11788d0dc31dSRichard Smith   RValue RV =
1179f770683fSPeter Collingbourne       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1180f770683fSPeter Collingbourne                        Args, CalleeType, /*chainCall=*/false),
1181f770683fSPeter Collingbourne                    CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
11828d0dc31dSRichard Smith 
11838d0dc31dSRichard Smith   /// C++1y [expr.new]p10:
11848d0dc31dSRichard Smith   ///   [In a new-expression,] an implementation is allowed to omit a call
11858d0dc31dSRichard Smith   ///   to a replaceable global allocation function.
11868d0dc31dSRichard Smith   ///
11878d0dc31dSRichard Smith   /// We model such elidable calls with the 'builtin' attribute.
11886956d587SRafael Espindola   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
11891235a8daSRichard Smith   if (Callee->isReplaceableGlobalAllocationFunction() &&
11906956d587SRafael Espindola       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
11918d0dc31dSRichard Smith     // FIXME: Add addAttribute to CallSite.
11928d0dc31dSRichard Smith     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
11938d0dc31dSRichard Smith       CI->addAttribute(llvm::AttributeSet::FunctionIndex,
11948d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
11958d0dc31dSRichard Smith     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
11968d0dc31dSRichard Smith       II->addAttribute(llvm::AttributeSet::FunctionIndex,
11978d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
11988d0dc31dSRichard Smith     else
11998d0dc31dSRichard Smith       llvm_unreachable("unexpected kind of call instruction");
12008d0dc31dSRichard Smith   }
12018d0dc31dSRichard Smith 
12028d0dc31dSRichard Smith   return RV;
12038d0dc31dSRichard Smith }
12048d0dc31dSRichard Smith 
1205760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1206760520bcSRichard Smith                                                  const Expr *Arg,
1207760520bcSRichard Smith                                                  bool IsDelete) {
1208760520bcSRichard Smith   CallArgList Args;
1209760520bcSRichard Smith   const Stmt *ArgS = Arg;
1210f05779e2SDavid Blaikie   EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1211760520bcSRichard Smith   // Find the allocation or deallocation function that we're calling.
1212760520bcSRichard Smith   ASTContext &Ctx = getContext();
1213760520bcSRichard Smith   DeclarationName Name = Ctx.DeclarationNames
1214760520bcSRichard Smith       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1215760520bcSRichard Smith   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1216599bed75SRichard Smith     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1217599bed75SRichard Smith       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1218760520bcSRichard Smith         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1219760520bcSRichard Smith   llvm_unreachable("predeclared global operator new/delete is missing");
1220760520bcSRichard Smith }
1221760520bcSRichard Smith 
1222*e9abe648SDaniel Jasper namespace {
1223*e9abe648SDaniel Jasper   /// A cleanup to call the given 'operator delete' function upon
1224*e9abe648SDaniel Jasper   /// abnormal exit from a new expression.
1225*e9abe648SDaniel Jasper   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1226*e9abe648SDaniel Jasper     size_t NumPlacementArgs;
1227*e9abe648SDaniel Jasper     const FunctionDecl *OperatorDelete;
1228*e9abe648SDaniel Jasper     llvm::Value *Ptr;
1229*e9abe648SDaniel Jasper     llvm::Value *AllocSize;
1230*e9abe648SDaniel Jasper 
1231*e9abe648SDaniel Jasper     RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1232*e9abe648SDaniel Jasper 
1233*e9abe648SDaniel Jasper   public:
1234*e9abe648SDaniel Jasper     static size_t getExtraSize(size_t NumPlacementArgs) {
1235*e9abe648SDaniel Jasper       return NumPlacementArgs * sizeof(RValue);
1236*e9abe648SDaniel Jasper     }
1237*e9abe648SDaniel Jasper 
1238*e9abe648SDaniel Jasper     CallDeleteDuringNew(size_t NumPlacementArgs,
1239*e9abe648SDaniel Jasper                         const FunctionDecl *OperatorDelete,
1240*e9abe648SDaniel Jasper                         llvm::Value *Ptr,
1241*e9abe648SDaniel Jasper                         llvm::Value *AllocSize)
1242*e9abe648SDaniel Jasper       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1243*e9abe648SDaniel Jasper         Ptr(Ptr), AllocSize(AllocSize) {}
1244*e9abe648SDaniel Jasper 
1245*e9abe648SDaniel Jasper     void setPlacementArg(unsigned I, RValue Arg) {
1246*e9abe648SDaniel Jasper       assert(I < NumPlacementArgs && "index out of range");
1247*e9abe648SDaniel Jasper       getPlacementArgs()[I] = Arg;
1248*e9abe648SDaniel Jasper     }
1249*e9abe648SDaniel Jasper 
1250*e9abe648SDaniel Jasper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1251*e9abe648SDaniel Jasper       const FunctionProtoType *FPT
1252*e9abe648SDaniel Jasper         = OperatorDelete->getType()->getAs<FunctionProtoType>();
1253*e9abe648SDaniel Jasper       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1254*e9abe648SDaniel Jasper              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
1255*e9abe648SDaniel Jasper 
1256*e9abe648SDaniel Jasper       CallArgList DeleteArgs;
1257824c2f53SJohn McCall 
1258189e52fcSRichard Smith       // The first argument is always a void*.
1259*e9abe648SDaniel Jasper       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
1260*e9abe648SDaniel Jasper       DeleteArgs.add(RValue::get(Ptr), *AI++);
1261189e52fcSRichard Smith 
1262*e9abe648SDaniel Jasper       // A member 'operator delete' can take an extra 'size_t' argument.
1263*e9abe648SDaniel Jasper       if (FPT->getNumParams() == NumPlacementArgs + 2)
1264*e9abe648SDaniel Jasper         DeleteArgs.add(RValue::get(AllocSize), *AI++);
1265189e52fcSRichard Smith 
1266*e9abe648SDaniel Jasper       // Pass the rest of the arguments, which must match exactly.
1267*e9abe648SDaniel Jasper       for (unsigned I = 0; I != NumPlacementArgs; ++I)
1268*e9abe648SDaniel Jasper         DeleteArgs.add(getPlacementArgs()[I], *AI++);
1269*e9abe648SDaniel Jasper 
1270*e9abe648SDaniel Jasper       // Call 'operator delete'.
1271*e9abe648SDaniel Jasper       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1272189e52fcSRichard Smith     }
1273189e52fcSRichard Smith   };
1274189e52fcSRichard Smith 
1275*e9abe648SDaniel Jasper   /// A cleanup to call the given 'operator delete' function upon
1276*e9abe648SDaniel Jasper   /// abnormal exit from a new expression when the new expression is
1277*e9abe648SDaniel Jasper   /// conditional.
1278*e9abe648SDaniel Jasper   class CallDeleteDuringConditionalNew final : public EHScopeStack::Cleanup {
1279*e9abe648SDaniel Jasper     size_t NumPlacementArgs;
1280189e52fcSRichard Smith     const FunctionDecl *OperatorDelete;
1281*e9abe648SDaniel Jasper     DominatingValue<RValue>::saved_type Ptr;
1282*e9abe648SDaniel Jasper     DominatingValue<RValue>::saved_type AllocSize;
1283189e52fcSRichard Smith 
1284*e9abe648SDaniel Jasper     DominatingValue<RValue>::saved_type *getPlacementArgs() {
1285*e9abe648SDaniel Jasper       return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
1286189e52fcSRichard Smith     }
1287824c2f53SJohn McCall 
1288824c2f53SJohn McCall   public:
1289824c2f53SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
1290*e9abe648SDaniel Jasper       return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
1291824c2f53SJohn McCall     }
1292824c2f53SJohn McCall 
1293*e9abe648SDaniel Jasper     CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1294*e9abe648SDaniel Jasper                                    const FunctionDecl *OperatorDelete,
1295*e9abe648SDaniel Jasper                                    DominatingValue<RValue>::saved_type Ptr,
1296*e9abe648SDaniel Jasper                               DominatingValue<RValue>::saved_type AllocSize)
1297*e9abe648SDaniel Jasper       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1298*e9abe648SDaniel Jasper         Ptr(Ptr), AllocSize(AllocSize) {}
1299824c2f53SJohn McCall 
1300*e9abe648SDaniel Jasper     void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
1301824c2f53SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
1302*e9abe648SDaniel Jasper       getPlacementArgs()[I] = Arg;
1303824c2f53SJohn McCall     }
1304824c2f53SJohn McCall 
13054f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1306*e9abe648SDaniel Jasper       const FunctionProtoType *FPT
1307*e9abe648SDaniel Jasper         = OperatorDelete->getType()->getAs<FunctionProtoType>();
1308*e9abe648SDaniel Jasper       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1309*e9abe648SDaniel Jasper              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
1310*e9abe648SDaniel Jasper 
1311824c2f53SJohn McCall       CallArgList DeleteArgs;
1312824c2f53SJohn McCall 
1313824c2f53SJohn McCall       // The first argument is always a void*.
1314*e9abe648SDaniel Jasper       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
1315*e9abe648SDaniel Jasper       DeleteArgs.add(Ptr.restore(CGF), *AI++);
1316824c2f53SJohn McCall 
1317*e9abe648SDaniel Jasper       // A member 'operator delete' can take an extra 'size_t' argument.
1318*e9abe648SDaniel Jasper       if (FPT->getNumParams() == NumPlacementArgs + 2) {
1319*e9abe648SDaniel Jasper         RValue RV = AllocSize.restore(CGF);
1320*e9abe648SDaniel Jasper         DeleteArgs.add(RV, *AI++);
13217f9c92a9SJohn McCall       }
13227f9c92a9SJohn McCall 
13237f9c92a9SJohn McCall       // Pass the rest of the arguments, which must match exactly.
13247f9c92a9SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1325*e9abe648SDaniel Jasper         RValue RV = getPlacementArgs()[I].restore(CGF);
1326*e9abe648SDaniel Jasper         DeleteArgs.add(RV, *AI++);
13277f9c92a9SJohn McCall       }
13287f9c92a9SJohn McCall 
13297f9c92a9SJohn McCall       // Call 'operator delete'.
13308d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
13317f9c92a9SJohn McCall     }
13327f9c92a9SJohn McCall   };
1333ab9db510SAlexander Kornienko }
13347f9c92a9SJohn McCall 
13357f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a
13367f9c92a9SJohn McCall /// new-expression throws.
13377f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
13387f9c92a9SJohn McCall                                   const CXXNewExpr *E,
13397f416cc4SJohn McCall                                   Address NewPtr,
13407f9c92a9SJohn McCall                                   llvm::Value *AllocSize,
13417f9c92a9SJohn McCall                                   const CallArgList &NewArgs) {
13427f9c92a9SJohn McCall   // If we're not inside a conditional branch, then the cleanup will
13437f9c92a9SJohn McCall   // dominate and we can do the easier (and more efficient) thing.
13447f9c92a9SJohn McCall   if (!CGF.isInConditionalBranch()) {
1345*e9abe648SDaniel Jasper     CallDeleteDuringNew *Cleanup = CGF.EHStack
1346*e9abe648SDaniel Jasper       .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
13477f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
13487f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
13497f416cc4SJohn McCall                                                  NewPtr.getPointer(),
1350*e9abe648SDaniel Jasper                                                  AllocSize);
1351*e9abe648SDaniel Jasper     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1352*e9abe648SDaniel Jasper       Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
13537f9c92a9SJohn McCall 
13547f9c92a9SJohn McCall     return;
13557f9c92a9SJohn McCall   }
13567f9c92a9SJohn McCall 
13577f9c92a9SJohn McCall   // Otherwise, we need to save all this stuff.
1358cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedNewPtr =
13597f416cc4SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1360cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedAllocSize =
1361cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
13627f9c92a9SJohn McCall 
1363*e9abe648SDaniel Jasper   CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
1364*e9abe648SDaniel Jasper     .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
13657f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
13667f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
13677f9c92a9SJohn McCall                                                  SavedNewPtr,
1368*e9abe648SDaniel Jasper                                                  SavedAllocSize);
1369*e9abe648SDaniel Jasper   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1370*e9abe648SDaniel Jasper     Cleanup->setPlacementArg(I,
1371*e9abe648SDaniel Jasper                      DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
13727f9c92a9SJohn McCall 
1373f4beacd0SJohn McCall   CGF.initFullExprCleanup();
1374824c2f53SJohn McCall }
1375824c2f53SJohn McCall 
137659486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
137775f9498aSJohn McCall   // The element type being allocated.
137875f9498aSJohn McCall   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
13798ed55a54SJohn McCall 
138075f9498aSJohn McCall   // 1. Build a call to the allocation function.
138175f9498aSJohn McCall   FunctionDecl *allocator = E->getOperatorNew();
138259486a2dSAnders Carlsson 
1383f862eb6aSSebastian Redl   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1384f862eb6aSSebastian Redl   unsigned minElements = 0;
1385f862eb6aSSebastian Redl   if (E->isArray() && E->hasInitializer()) {
13860511d23aSRichard Smith     const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
13870511d23aSRichard Smith     if (ILE && ILE->isStringLiteralInit())
13880511d23aSRichard Smith       minElements =
13890511d23aSRichard Smith           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
13900511d23aSRichard Smith               ->getSize().getZExtValue();
13910511d23aSRichard Smith     else if (ILE)
1392f862eb6aSSebastian Redl       minElements = ILE->getNumInits();
1393f862eb6aSSebastian Redl   }
1394f862eb6aSSebastian Redl 
13958a13c418SCraig Topper   llvm::Value *numElements = nullptr;
13968a13c418SCraig Topper   llvm::Value *allocSizeWithoutCookie = nullptr;
139775f9498aSJohn McCall   llvm::Value *allocSize =
1398f862eb6aSSebastian Redl     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1399f862eb6aSSebastian Redl                         allocSizeWithoutCookie);
140059486a2dSAnders Carlsson 
14017f416cc4SJohn McCall   // Emit the allocation call.  If the allocator is a global placement
14027f416cc4SJohn McCall   // operator, just "inline" it directly.
14037f416cc4SJohn McCall   Address allocation = Address::invalid();
14047f416cc4SJohn McCall   CallArgList allocatorArgs;
14057f416cc4SJohn McCall   if (allocator->isReservedGlobalPlacementOperator()) {
140653dcf94dSJohn McCall     assert(E->getNumPlacementArgs() == 1);
140753dcf94dSJohn McCall     const Expr *arg = *E->placement_arguments().begin();
140853dcf94dSJohn McCall 
14097f416cc4SJohn McCall     AlignmentSource alignSource;
141053dcf94dSJohn McCall     allocation = EmitPointerWithAlignment(arg, &alignSource);
14117f416cc4SJohn McCall 
14127f416cc4SJohn McCall     // The pointer expression will, in many cases, be an opaque void*.
14137f416cc4SJohn McCall     // In these cases, discard the computed alignment and use the
14147f416cc4SJohn McCall     // formal alignment of the allocated type.
1415*e9abe648SDaniel Jasper     if (alignSource != AlignmentSource::Decl) {
1416*e9abe648SDaniel Jasper       allocation = Address(allocation.getPointer(),
1417*e9abe648SDaniel Jasper                            getContext().getTypeAlignInChars(allocType));
1418*e9abe648SDaniel Jasper     }
14197f416cc4SJohn McCall 
142053dcf94dSJohn McCall     // Set up allocatorArgs for the call to operator delete if it's not
142153dcf94dSJohn McCall     // the reserved global operator.
142253dcf94dSJohn McCall     if (E->getOperatorDelete() &&
142353dcf94dSJohn McCall         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
142453dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
142553dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
142653dcf94dSJohn McCall     }
142753dcf94dSJohn McCall 
14287f416cc4SJohn McCall   } else {
14297f416cc4SJohn McCall     const FunctionProtoType *allocatorType =
14307f416cc4SJohn McCall       allocator->getType()->castAs<FunctionProtoType>();
14317f416cc4SJohn McCall 
14327f416cc4SJohn McCall     // The allocation size is the first argument.
14337f416cc4SJohn McCall     QualType sizeType = getContext().getSizeType();
143443dca6a8SEli Friedman     allocatorArgs.add(RValue::get(allocSize), sizeType);
143559486a2dSAnders Carlsson 
1436*e9abe648SDaniel Jasper     // We start at 1 here because the first argument (the allocation size)
1437*e9abe648SDaniel Jasper     // has already been emitted.
1438f05779e2SDavid Blaikie     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1439*e9abe648SDaniel Jasper                  /* CalleeDecl */ nullptr,
1440*e9abe648SDaniel Jasper                  /*ParamsToSkip*/ 1);
144159486a2dSAnders Carlsson 
14427f416cc4SJohn McCall     RValue RV =
14437f416cc4SJohn McCall       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
14447f416cc4SJohn McCall 
1445*e9abe648SDaniel Jasper     // For now, only assume that the allocation function returns
1446*e9abe648SDaniel Jasper     // something satisfactorily aligned for the element type, plus
1447*e9abe648SDaniel Jasper     // the cookie if we have one.
1448*e9abe648SDaniel Jasper     CharUnits allocationAlign =
1449*e9abe648SDaniel Jasper       getContext().getTypeAlignInChars(allocType);
1450*e9abe648SDaniel Jasper     if (allocSize != allocSizeWithoutCookie) {
1451*e9abe648SDaniel Jasper       CharUnits cookieAlign = getSizeAlign(); // FIXME?
1452*e9abe648SDaniel Jasper       allocationAlign = std::max(allocationAlign, cookieAlign);
14537f416cc4SJohn McCall     }
14547f416cc4SJohn McCall 
14557f416cc4SJohn McCall     allocation = Address(RV.getScalarVal(), allocationAlign);
14567ec4b434SJohn McCall   }
145759486a2dSAnders Carlsson 
145875f9498aSJohn McCall   // Emit a null check on the allocation result if the allocation
145975f9498aSJohn McCall   // function is allowed to return null (because it has a non-throwing
1460902a0238SRichard Smith   // exception spec or is the reserved placement new) and we have an
146175f9498aSJohn McCall   // interesting initializer.
1462902a0238SRichard Smith   bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
14636047f07eSSebastian Redl     (!allocType.isPODType(getContext()) || E->hasInitializer());
146459486a2dSAnders Carlsson 
14658a13c418SCraig Topper   llvm::BasicBlock *nullCheckBB = nullptr;
14668a13c418SCraig Topper   llvm::BasicBlock *contBB = nullptr;
146759486a2dSAnders Carlsson 
1468f7dcf320SJohn McCall   // The null-check means that the initializer is conditionally
1469f7dcf320SJohn McCall   // evaluated.
1470f7dcf320SJohn McCall   ConditionalEvaluation conditional(*this);
1471f7dcf320SJohn McCall 
147275f9498aSJohn McCall   if (nullCheck) {
1473f7dcf320SJohn McCall     conditional.begin(*this);
147475f9498aSJohn McCall 
147575f9498aSJohn McCall     nullCheckBB = Builder.GetInsertBlock();
147675f9498aSJohn McCall     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
147775f9498aSJohn McCall     contBB = createBasicBlock("new.cont");
147875f9498aSJohn McCall 
14797f416cc4SJohn McCall     llvm::Value *isNull =
14807f416cc4SJohn McCall       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
148175f9498aSJohn McCall     Builder.CreateCondBr(isNull, contBB, notNullBB);
148275f9498aSJohn McCall     EmitBlock(notNullBB);
148359486a2dSAnders Carlsson   }
148459486a2dSAnders Carlsson 
1485824c2f53SJohn McCall   // If there's an operator delete, enter a cleanup to call it if an
1486824c2f53SJohn McCall   // exception is thrown.
148775f9498aSJohn McCall   EHScopeStack::stable_iterator operatorDeleteCleanup;
14888a13c418SCraig Topper   llvm::Instruction *cleanupDominator = nullptr;
14897ec4b434SJohn McCall   if (E->getOperatorDelete() &&
14907ec4b434SJohn McCall       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1491*e9abe648SDaniel Jasper     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
149275f9498aSJohn McCall     operatorDeleteCleanup = EHStack.stable_begin();
1493f4beacd0SJohn McCall     cleanupDominator = Builder.CreateUnreachable();
1494824c2f53SJohn McCall   }
1495824c2f53SJohn McCall 
1496cf9b1f65SEli Friedman   assert((allocSize == allocSizeWithoutCookie) ==
1497cf9b1f65SEli Friedman          CalculateCookiePadding(*this, E).isZero());
1498cf9b1f65SEli Friedman   if (allocSize != allocSizeWithoutCookie) {
1499cf9b1f65SEli Friedman     assert(E->isArray());
1500cf9b1f65SEli Friedman     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1501cf9b1f65SEli Friedman                                                        numElements,
1502cf9b1f65SEli Friedman                                                        E, allocType);
1503cf9b1f65SEli Friedman   }
1504cf9b1f65SEli Friedman 
1505fb901c7aSDavid Blaikie   llvm::Type *elementTy = ConvertTypeForMem(allocType);
15067f416cc4SJohn McCall   Address result = Builder.CreateElementBitCast(allocation, elementTy);
1507824c2f53SJohn McCall 
1508338c9d0aSPiotr Padlewski   // Passing pointer through invariant.group.barrier to avoid propagation of
1509338c9d0aSPiotr Padlewski   // vptrs information which may be included in previous type.
1510338c9d0aSPiotr Padlewski   if (CGM.getCodeGenOpts().StrictVTablePointers &&
1511338c9d0aSPiotr Padlewski       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1512338c9d0aSPiotr Padlewski       allocator->isReservedGlobalPlacementOperator())
1513338c9d0aSPiotr Padlewski     result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1514338c9d0aSPiotr Padlewski                      result.getAlignment());
1515338c9d0aSPiotr Padlewski 
1516fb901c7aSDavid Blaikie   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
151799210dc9SJohn McCall                      allocSizeWithoutCookie);
15188ed55a54SJohn McCall   if (E->isArray()) {
15198ed55a54SJohn McCall     // NewPtr is a pointer to the base element type.  If we're
15208ed55a54SJohn McCall     // allocating an array of arrays, we'll need to cast back to the
15218ed55a54SJohn McCall     // array pointer type.
15222192fe50SChris Lattner     llvm::Type *resultType = ConvertTypeForMem(E->getType());
15237f416cc4SJohn McCall     if (result.getType() != resultType)
152475f9498aSJohn McCall       result = Builder.CreateBitCast(result, resultType);
152547b4629bSFariborz Jahanian   }
152659486a2dSAnders Carlsson 
1527824c2f53SJohn McCall   // Deactivate the 'operator delete' cleanup if we finished
1528824c2f53SJohn McCall   // initialization.
1529f4beacd0SJohn McCall   if (operatorDeleteCleanup.isValid()) {
1530f4beacd0SJohn McCall     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1531f4beacd0SJohn McCall     cleanupDominator->eraseFromParent();
1532f4beacd0SJohn McCall   }
1533824c2f53SJohn McCall 
15347f416cc4SJohn McCall   llvm::Value *resultPtr = result.getPointer();
153575f9498aSJohn McCall   if (nullCheck) {
1536f7dcf320SJohn McCall     conditional.end(*this);
1537f7dcf320SJohn McCall 
153875f9498aSJohn McCall     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
153975f9498aSJohn McCall     EmitBlock(contBB);
154059486a2dSAnders Carlsson 
15417f416cc4SJohn McCall     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
15427f416cc4SJohn McCall     PHI->addIncoming(resultPtr, notNullBB);
15437f416cc4SJohn McCall     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
154475f9498aSJohn McCall                      nullCheckBB);
154559486a2dSAnders Carlsson 
15467f416cc4SJohn McCall     resultPtr = PHI;
154759486a2dSAnders Carlsson   }
154859486a2dSAnders Carlsson 
15497f416cc4SJohn McCall   return resultPtr;
155059486a2dSAnders Carlsson }
155159486a2dSAnders Carlsson 
155259486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1553*e9abe648SDaniel Jasper                                      llvm::Value *Ptr,
1554*e9abe648SDaniel Jasper                                      QualType DeleteTy) {
1555*e9abe648SDaniel Jasper   assert(DeleteFD->getOverloadedOperator() == OO_Delete);
15568ed55a54SJohn McCall 
155759486a2dSAnders Carlsson   const FunctionProtoType *DeleteFTy =
155859486a2dSAnders Carlsson     DeleteFD->getType()->getAs<FunctionProtoType>();
155959486a2dSAnders Carlsson 
156059486a2dSAnders Carlsson   CallArgList DeleteArgs;
156159486a2dSAnders Carlsson 
1562*e9abe648SDaniel Jasper   // Check if we need to pass the size to the delete operator.
1563*e9abe648SDaniel Jasper   llvm::Value *Size = nullptr;
1564*e9abe648SDaniel Jasper   QualType SizeTy;
1565*e9abe648SDaniel Jasper   if (DeleteFTy->getNumParams() == 2) {
1566*e9abe648SDaniel Jasper     SizeTy = DeleteFTy->getParamType(1);
1567*e9abe648SDaniel Jasper     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1568*e9abe648SDaniel Jasper     Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1569*e9abe648SDaniel Jasper                                   DeleteTypeSize.getQuantity());
1570*e9abe648SDaniel Jasper   }
157121122cf6SAnders Carlsson 
1572*e9abe648SDaniel Jasper   QualType ArgTy = DeleteFTy->getParamType(0);
157359486a2dSAnders Carlsson   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
157443dca6a8SEli Friedman   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
157559486a2dSAnders Carlsson 
1576*e9abe648SDaniel Jasper   if (Size)
1577*e9abe648SDaniel Jasper     DeleteArgs.add(RValue::get(Size), SizeTy);
157859486a2dSAnders Carlsson 
157959486a2dSAnders Carlsson   // Emit the call to delete.
15808d0dc31dSRichard Smith   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
158159486a2dSAnders Carlsson }
158259486a2dSAnders Carlsson 
15838ed55a54SJohn McCall namespace {
15848ed55a54SJohn McCall   /// Calls the given 'operator delete' on a single object.
15857e70d680SDavid Blaikie   struct CallObjectDelete final : EHScopeStack::Cleanup {
15868ed55a54SJohn McCall     llvm::Value *Ptr;
15878ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
15888ed55a54SJohn McCall     QualType ElementType;
15898ed55a54SJohn McCall 
15908ed55a54SJohn McCall     CallObjectDelete(llvm::Value *Ptr,
15918ed55a54SJohn McCall                      const FunctionDecl *OperatorDelete,
15928ed55a54SJohn McCall                      QualType ElementType)
15938ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
15948ed55a54SJohn McCall 
15954f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
15968ed55a54SJohn McCall       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
15978ed55a54SJohn McCall     }
15988ed55a54SJohn McCall   };
1599ab9db510SAlexander Kornienko }
16008ed55a54SJohn McCall 
16010c0b6d9aSDavid Majnemer void
16020c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
16030c0b6d9aSDavid Majnemer                                              llvm::Value *CompletePtr,
16040c0b6d9aSDavid Majnemer                                              QualType ElementType) {
16050c0b6d9aSDavid Majnemer   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
16060c0b6d9aSDavid Majnemer                                         OperatorDelete, ElementType);
16070c0b6d9aSDavid Majnemer }
16080c0b6d9aSDavid Majnemer 
16098ed55a54SJohn McCall /// Emit the code for deleting a single object.
16108ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF,
16110868137aSDavid Majnemer                              const CXXDeleteExpr *DE,
16127f416cc4SJohn McCall                              Address Ptr,
16130868137aSDavid Majnemer                              QualType ElementType) {
16148ed55a54SJohn McCall   // Find the destructor for the type, if applicable.  If the
16158ed55a54SJohn McCall   // destructor is virtual, we'll just emit the vcall and return.
16168a13c418SCraig Topper   const CXXDestructorDecl *Dtor = nullptr;
16178ed55a54SJohn McCall   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
16188ed55a54SJohn McCall     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1619b23533dbSEli Friedman     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
16208ed55a54SJohn McCall       Dtor = RD->getDestructor();
16218ed55a54SJohn McCall 
16228ed55a54SJohn McCall       if (Dtor->isVirtual()) {
16230868137aSDavid Majnemer         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
16240868137aSDavid Majnemer                                                     Dtor);
16258ed55a54SJohn McCall         return;
16268ed55a54SJohn McCall       }
16278ed55a54SJohn McCall     }
16288ed55a54SJohn McCall   }
16298ed55a54SJohn McCall 
16308ed55a54SJohn McCall   // Make sure that we call delete even if the dtor throws.
1631e4df6c8dSJohn McCall   // This doesn't have to a conditional cleanup because we're going
1632e4df6c8dSJohn McCall   // to pop it off in a second.
16330868137aSDavid Majnemer   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
16348ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
16357f416cc4SJohn McCall                                             Ptr.getPointer(),
16367f416cc4SJohn McCall                                             OperatorDelete, ElementType);
16378ed55a54SJohn McCall 
16388ed55a54SJohn McCall   if (Dtor)
16398ed55a54SJohn McCall     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
164061535005SDouglas Gregor                               /*ForVirtualBase=*/false,
164161535005SDouglas Gregor                               /*Delegating=*/false,
164261535005SDouglas Gregor                               Ptr);
1643460ce58fSJohn McCall   else if (auto Lifetime = ElementType.getObjCLifetime()) {
1644460ce58fSJohn McCall     switch (Lifetime) {
164531168b07SJohn McCall     case Qualifiers::OCL_None:
164631168b07SJohn McCall     case Qualifiers::OCL_ExplicitNone:
164731168b07SJohn McCall     case Qualifiers::OCL_Autoreleasing:
164831168b07SJohn McCall       break;
164931168b07SJohn McCall 
16507f416cc4SJohn McCall     case Qualifiers::OCL_Strong:
16517f416cc4SJohn McCall       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
165231168b07SJohn McCall       break;
165331168b07SJohn McCall 
165431168b07SJohn McCall     case Qualifiers::OCL_Weak:
165531168b07SJohn McCall       CGF.EmitARCDestroyWeak(Ptr);
165631168b07SJohn McCall       break;
165731168b07SJohn McCall     }
165831168b07SJohn McCall   }
16598ed55a54SJohn McCall 
16608ed55a54SJohn McCall   CGF.PopCleanupBlock();
16618ed55a54SJohn McCall }
16628ed55a54SJohn McCall 
16638ed55a54SJohn McCall namespace {
16648ed55a54SJohn McCall   /// Calls the given 'operator delete' on an array of objects.
16657e70d680SDavid Blaikie   struct CallArrayDelete final : EHScopeStack::Cleanup {
16668ed55a54SJohn McCall     llvm::Value *Ptr;
16678ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
16688ed55a54SJohn McCall     llvm::Value *NumElements;
16698ed55a54SJohn McCall     QualType ElementType;
16708ed55a54SJohn McCall     CharUnits CookieSize;
16718ed55a54SJohn McCall 
16728ed55a54SJohn McCall     CallArrayDelete(llvm::Value *Ptr,
16738ed55a54SJohn McCall                     const FunctionDecl *OperatorDelete,
16748ed55a54SJohn McCall                     llvm::Value *NumElements,
16758ed55a54SJohn McCall                     QualType ElementType,
16768ed55a54SJohn McCall                     CharUnits CookieSize)
16778ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
16788ed55a54SJohn McCall         ElementType(ElementType), CookieSize(CookieSize) {}
16798ed55a54SJohn McCall 
16804f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1681*e9abe648SDaniel Jasper       const FunctionProtoType *DeleteFTy =
1682*e9abe648SDaniel Jasper         OperatorDelete->getType()->getAs<FunctionProtoType>();
1683*e9abe648SDaniel Jasper       assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
1684*e9abe648SDaniel Jasper 
1685*e9abe648SDaniel Jasper       CallArgList Args;
1686*e9abe648SDaniel Jasper 
1687*e9abe648SDaniel Jasper       // Pass the pointer as the first argument.
1688*e9abe648SDaniel Jasper       QualType VoidPtrTy = DeleteFTy->getParamType(0);
1689*e9abe648SDaniel Jasper       llvm::Value *DeletePtr
1690*e9abe648SDaniel Jasper         = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1691*e9abe648SDaniel Jasper       Args.add(RValue::get(DeletePtr), VoidPtrTy);
1692*e9abe648SDaniel Jasper 
1693*e9abe648SDaniel Jasper       // Pass the original requested size as the second argument.
1694*e9abe648SDaniel Jasper       if (DeleteFTy->getNumParams() == 2) {
1695*e9abe648SDaniel Jasper         QualType size_t = DeleteFTy->getParamType(1);
1696*e9abe648SDaniel Jasper         llvm::IntegerType *SizeTy
1697*e9abe648SDaniel Jasper           = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1698*e9abe648SDaniel Jasper 
1699*e9abe648SDaniel Jasper         CharUnits ElementTypeSize =
1700*e9abe648SDaniel Jasper           CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1701*e9abe648SDaniel Jasper 
1702*e9abe648SDaniel Jasper         // The size of an element, multiplied by the number of elements.
1703*e9abe648SDaniel Jasper         llvm::Value *Size
1704*e9abe648SDaniel Jasper           = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1705*e9abe648SDaniel Jasper         if (NumElements)
1706*e9abe648SDaniel Jasper           Size = CGF.Builder.CreateMul(Size, NumElements);
1707*e9abe648SDaniel Jasper 
1708*e9abe648SDaniel Jasper         // Plus the size of the cookie if applicable.
1709*e9abe648SDaniel Jasper         if (!CookieSize.isZero()) {
1710*e9abe648SDaniel Jasper           llvm::Value *CookieSizeV
1711*e9abe648SDaniel Jasper             = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1712*e9abe648SDaniel Jasper           Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1713*e9abe648SDaniel Jasper         }
1714*e9abe648SDaniel Jasper 
1715*e9abe648SDaniel Jasper         Args.add(RValue::get(Size), size_t);
1716*e9abe648SDaniel Jasper       }
1717*e9abe648SDaniel Jasper 
1718*e9abe648SDaniel Jasper       // Emit the call to delete.
1719*e9abe648SDaniel Jasper       EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
17208ed55a54SJohn McCall     }
17218ed55a54SJohn McCall   };
1722ab9db510SAlexander Kornienko }
17238ed55a54SJohn McCall 
17248ed55a54SJohn McCall /// Emit the code for deleting an array of objects.
17258ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF,
1726284c48ffSJohn McCall                             const CXXDeleteExpr *E,
17277f416cc4SJohn McCall                             Address deletedPtr,
1728ca2c56f2SJohn McCall                             QualType elementType) {
17298a13c418SCraig Topper   llvm::Value *numElements = nullptr;
17308a13c418SCraig Topper   llvm::Value *allocatedPtr = nullptr;
1731ca2c56f2SJohn McCall   CharUnits cookieSize;
1732ca2c56f2SJohn McCall   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1733ca2c56f2SJohn McCall                                       numElements, allocatedPtr, cookieSize);
17348ed55a54SJohn McCall 
1735ca2c56f2SJohn McCall   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
17368ed55a54SJohn McCall 
17378ed55a54SJohn McCall   // Make sure that we call delete even if one of the dtors throws.
1738ca2c56f2SJohn McCall   const FunctionDecl *operatorDelete = E->getOperatorDelete();
17398ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1740ca2c56f2SJohn McCall                                            allocatedPtr, operatorDelete,
1741ca2c56f2SJohn McCall                                            numElements, elementType,
1742ca2c56f2SJohn McCall                                            cookieSize);
17438ed55a54SJohn McCall 
1744ca2c56f2SJohn McCall   // Destroy the elements.
1745ca2c56f2SJohn McCall   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1746ca2c56f2SJohn McCall     assert(numElements && "no element count for a type with a destructor!");
174731168b07SJohn McCall 
17487f416cc4SJohn McCall     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
17497f416cc4SJohn McCall     CharUnits elementAlign =
17507f416cc4SJohn McCall       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
17517f416cc4SJohn McCall 
17527f416cc4SJohn McCall     llvm::Value *arrayBegin = deletedPtr.getPointer();
1753ca2c56f2SJohn McCall     llvm::Value *arrayEnd =
17547f416cc4SJohn McCall       CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
175597eab0a2SJohn McCall 
175697eab0a2SJohn McCall     // Note that it is legal to allocate a zero-length array, and we
175797eab0a2SJohn McCall     // can never fold the check away because the length should always
175897eab0a2SJohn McCall     // come from a cookie.
17597f416cc4SJohn McCall     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1760ca2c56f2SJohn McCall                          CGF.getDestroyer(dtorKind),
176197eab0a2SJohn McCall                          /*checkZeroLength*/ true,
1762ca2c56f2SJohn McCall                          CGF.needsEHCleanup(dtorKind));
17638ed55a54SJohn McCall   }
17648ed55a54SJohn McCall 
1765ca2c56f2SJohn McCall   // Pop the cleanup block.
17668ed55a54SJohn McCall   CGF.PopCleanupBlock();
17678ed55a54SJohn McCall }
17688ed55a54SJohn McCall 
176959486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
177059486a2dSAnders Carlsson   const Expr *Arg = E->getArgument();
17717f416cc4SJohn McCall   Address Ptr = EmitPointerWithAlignment(Arg);
177259486a2dSAnders Carlsson 
177359486a2dSAnders Carlsson   // Null check the pointer.
177459486a2dSAnders Carlsson   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
177559486a2dSAnders Carlsson   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
177659486a2dSAnders Carlsson 
17777f416cc4SJohn McCall   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
177859486a2dSAnders Carlsson 
177959486a2dSAnders Carlsson   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
178059486a2dSAnders Carlsson   EmitBlock(DeleteNotNull);
178159486a2dSAnders Carlsson 
17828ed55a54SJohn McCall   // We might be deleting a pointer to array.  If so, GEP down to the
17838ed55a54SJohn McCall   // first non-array element.
17848ed55a54SJohn McCall   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
17858ed55a54SJohn McCall   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
17868ed55a54SJohn McCall   if (DeleteTy->isConstantArrayType()) {
17878ed55a54SJohn McCall     llvm::Value *Zero = Builder.getInt32(0);
17880e62c1ccSChris Lattner     SmallVector<llvm::Value*,8> GEP;
178959486a2dSAnders Carlsson 
17908ed55a54SJohn McCall     GEP.push_back(Zero); // point at the outermost array
17918ed55a54SJohn McCall 
17928ed55a54SJohn McCall     // For each layer of array type we're pointing at:
17938ed55a54SJohn McCall     while (const ConstantArrayType *Arr
17948ed55a54SJohn McCall              = getContext().getAsConstantArrayType(DeleteTy)) {
17958ed55a54SJohn McCall       // 1. Unpeel the array type.
17968ed55a54SJohn McCall       DeleteTy = Arr->getElementType();
17978ed55a54SJohn McCall 
17988ed55a54SJohn McCall       // 2. GEP to the first element of the array.
17998ed55a54SJohn McCall       GEP.push_back(Zero);
18008ed55a54SJohn McCall     }
18018ed55a54SJohn McCall 
18027f416cc4SJohn McCall     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
18037f416cc4SJohn McCall                   Ptr.getAlignment());
18048ed55a54SJohn McCall   }
18058ed55a54SJohn McCall 
18067f416cc4SJohn McCall   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
18078ed55a54SJohn McCall 
18087270ef57SReid Kleckner   if (E->isArrayForm()) {
18097270ef57SReid Kleckner     EmitArrayDelete(*this, E, Ptr, DeleteTy);
18107270ef57SReid Kleckner   } else {
18117270ef57SReid Kleckner     EmitObjectDelete(*this, E, Ptr, DeleteTy);
18127270ef57SReid Kleckner   }
181359486a2dSAnders Carlsson 
181459486a2dSAnders Carlsson   EmitBlock(DeleteEnd);
181559486a2dSAnders Carlsson }
181659486a2dSAnders Carlsson 
18171c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) {
18181c3d95ebSDavid Majnemer   E = E->IgnoreParens();
18191c3d95ebSDavid Majnemer 
18201c3d95ebSDavid Majnemer   if (const auto *CE = dyn_cast<CastExpr>(E)) {
18211c3d95ebSDavid Majnemer     if (!CE->getSubExpr()->isGLValue())
18221c3d95ebSDavid Majnemer       return false;
18231c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(CE->getSubExpr());
18241c3d95ebSDavid Majnemer   }
18251c3d95ebSDavid Majnemer 
18261c3d95ebSDavid Majnemer   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
18271c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(OVE->getSourceExpr());
18281c3d95ebSDavid Majnemer 
18291c3d95ebSDavid Majnemer   if (const auto *BO = dyn_cast<BinaryOperator>(E))
18301c3d95ebSDavid Majnemer     if (BO->getOpcode() == BO_Comma)
18311c3d95ebSDavid Majnemer       return isGLValueFromPointerDeref(BO->getRHS());
18321c3d95ebSDavid Majnemer 
18331c3d95ebSDavid Majnemer   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
18341c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
18351c3d95ebSDavid Majnemer            isGLValueFromPointerDeref(ACO->getFalseExpr());
18361c3d95ebSDavid Majnemer 
18371c3d95ebSDavid Majnemer   // C++11 [expr.sub]p1:
18381c3d95ebSDavid Majnemer   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
18391c3d95ebSDavid Majnemer   if (isa<ArraySubscriptExpr>(E))
18401c3d95ebSDavid Majnemer     return true;
18411c3d95ebSDavid Majnemer 
18421c3d95ebSDavid Majnemer   if (const auto *UO = dyn_cast<UnaryOperator>(E))
18431c3d95ebSDavid Majnemer     if (UO->getOpcode() == UO_Deref)
18441c3d95ebSDavid Majnemer       return true;
18451c3d95ebSDavid Majnemer 
18461c3d95ebSDavid Majnemer   return false;
18471c3d95ebSDavid Majnemer }
18481c3d95ebSDavid Majnemer 
1849747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
18502192fe50SChris Lattner                                          llvm::Type *StdTypeInfoPtrTy) {
1851940f02d2SAnders Carlsson   // Get the vtable pointer.
18527f416cc4SJohn McCall   Address ThisPtr = CGF.EmitLValue(E).getAddress();
1853940f02d2SAnders Carlsson 
1854940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1855940f02d2SAnders Carlsson   //   If the glvalue expression is obtained by applying the unary * operator to
1856940f02d2SAnders Carlsson   //   a pointer and the pointer is a null pointer value, the typeid expression
1857940f02d2SAnders Carlsson   //   throws the std::bad_typeid exception.
18581c3d95ebSDavid Majnemer   //
18591c3d95ebSDavid Majnemer   // However, this paragraph's intent is not clear.  We choose a very generous
18601c3d95ebSDavid Majnemer   // interpretation which implores us to consider comma operators, conditional
18611c3d95ebSDavid Majnemer   // operators, parentheses and other such constructs.
18621162d25cSDavid Majnemer   QualType SrcRecordTy = E->getType();
18631c3d95ebSDavid Majnemer   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
18641c3d95ebSDavid Majnemer           isGLValueFromPointerDeref(E), SrcRecordTy)) {
1865940f02d2SAnders Carlsson     llvm::BasicBlock *BadTypeidBlock =
1866940f02d2SAnders Carlsson         CGF.createBasicBlock("typeid.bad_typeid");
18671162d25cSDavid Majnemer     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
1868940f02d2SAnders Carlsson 
18697f416cc4SJohn McCall     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
1870940f02d2SAnders Carlsson     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1871940f02d2SAnders Carlsson 
1872940f02d2SAnders Carlsson     CGF.EmitBlock(BadTypeidBlock);
18731162d25cSDavid Majnemer     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1874940f02d2SAnders Carlsson     CGF.EmitBlock(EndBlock);
1875940f02d2SAnders Carlsson   }
1876940f02d2SAnders Carlsson 
18771162d25cSDavid Majnemer   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
18781162d25cSDavid Majnemer                                         StdTypeInfoPtrTy);
1879940f02d2SAnders Carlsson }
1880940f02d2SAnders Carlsson 
188159486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
18822192fe50SChris Lattner   llvm::Type *StdTypeInfoPtrTy =
1883940f02d2SAnders Carlsson     ConvertType(E->getType())->getPointerTo();
1884fd7dfeb7SAnders Carlsson 
18853f4336cbSAnders Carlsson   if (E->isTypeOperand()) {
18863f4336cbSAnders Carlsson     llvm::Constant *TypeInfo =
1887143c55eaSDavid Majnemer         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
1888940f02d2SAnders Carlsson     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
18893f4336cbSAnders Carlsson   }
1890fd7dfeb7SAnders Carlsson 
1891940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1892940f02d2SAnders Carlsson   //   When typeid is applied to a glvalue expression whose type is a
1893940f02d2SAnders Carlsson   //   polymorphic class type, the result refers to a std::type_info object
1894940f02d2SAnders Carlsson   //   representing the type of the most derived object (that is, the dynamic
1895940f02d2SAnders Carlsson   //   type) to which the glvalue refers.
1896ef8bf436SRichard Smith   if (E->isPotentiallyEvaluated())
1897940f02d2SAnders Carlsson     return EmitTypeidFromVTable(*this, E->getExprOperand(),
1898940f02d2SAnders Carlsson                                 StdTypeInfoPtrTy);
1899940f02d2SAnders Carlsson 
1900940f02d2SAnders Carlsson   QualType OperandTy = E->getExprOperand()->getType();
1901940f02d2SAnders Carlsson   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1902940f02d2SAnders Carlsson                                StdTypeInfoPtrTy);
190359486a2dSAnders Carlsson }
190459486a2dSAnders Carlsson 
1905c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1906c1c9971cSAnders Carlsson                                           QualType DestTy) {
19072192fe50SChris Lattner   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1908c1c9971cSAnders Carlsson   if (DestTy->isPointerType())
1909c1c9971cSAnders Carlsson     return llvm::Constant::getNullValue(DestLTy);
1910c1c9971cSAnders Carlsson 
1911c1c9971cSAnders Carlsson   /// C++ [expr.dynamic.cast]p9:
1912c1c9971cSAnders Carlsson   ///   A failed cast to reference type throws std::bad_cast
19131162d25cSDavid Majnemer   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
19141162d25cSDavid Majnemer     return nullptr;
1915c1c9971cSAnders Carlsson 
1916c1c9971cSAnders Carlsson   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1917c1c9971cSAnders Carlsson   return llvm::UndefValue::get(DestLTy);
1918c1c9971cSAnders Carlsson }
1919c1c9971cSAnders Carlsson 
19207f416cc4SJohn McCall llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
192159486a2dSAnders Carlsson                                               const CXXDynamicCastExpr *DCE) {
19222bf9b4c0SAlexey Bataev   CGM.EmitExplicitCastExprType(DCE, this);
19233f4336cbSAnders Carlsson   QualType DestTy = DCE->getTypeAsWritten();
19243f4336cbSAnders Carlsson 
1925c1c9971cSAnders Carlsson   if (DCE->isAlwaysNull())
19261162d25cSDavid Majnemer     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
19271162d25cSDavid Majnemer       return T;
1928c1c9971cSAnders Carlsson 
1929c1c9971cSAnders Carlsson   QualType SrcTy = DCE->getSubExpr()->getType();
1930c1c9971cSAnders Carlsson 
19311162d25cSDavid Majnemer   // C++ [expr.dynamic.cast]p7:
19321162d25cSDavid Majnemer   //   If T is "pointer to cv void," then the result is a pointer to the most
19331162d25cSDavid Majnemer   //   derived object pointed to by v.
19341162d25cSDavid Majnemer   const PointerType *DestPTy = DestTy->getAs<PointerType>();
19351162d25cSDavid Majnemer 
19361162d25cSDavid Majnemer   bool isDynamicCastToVoid;
19371162d25cSDavid Majnemer   QualType SrcRecordTy;
19381162d25cSDavid Majnemer   QualType DestRecordTy;
19391162d25cSDavid Majnemer   if (DestPTy) {
19401162d25cSDavid Majnemer     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
19411162d25cSDavid Majnemer     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
19421162d25cSDavid Majnemer     DestRecordTy = DestPTy->getPointeeType();
19431162d25cSDavid Majnemer   } else {
19441162d25cSDavid Majnemer     isDynamicCastToVoid = false;
19451162d25cSDavid Majnemer     SrcRecordTy = SrcTy;
19461162d25cSDavid Majnemer     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
19471162d25cSDavid Majnemer   }
19481162d25cSDavid Majnemer 
19491162d25cSDavid Majnemer   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
19501162d25cSDavid Majnemer 
1951882d790fSAnders Carlsson   // C++ [expr.dynamic.cast]p4:
1952882d790fSAnders Carlsson   //   If the value of v is a null pointer value in the pointer case, the result
1953882d790fSAnders Carlsson   //   is the null pointer value of type T.
19541162d25cSDavid Majnemer   bool ShouldNullCheckSrcValue =
19551162d25cSDavid Majnemer       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
19561162d25cSDavid Majnemer                                                          SrcRecordTy);
195759486a2dSAnders Carlsson 
19588a13c418SCraig Topper   llvm::BasicBlock *CastNull = nullptr;
19598a13c418SCraig Topper   llvm::BasicBlock *CastNotNull = nullptr;
1960882d790fSAnders Carlsson   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
1961fa8b4955SDouglas Gregor 
1962882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1963882d790fSAnders Carlsson     CastNull = createBasicBlock("dynamic_cast.null");
1964882d790fSAnders Carlsson     CastNotNull = createBasicBlock("dynamic_cast.notnull");
1965882d790fSAnders Carlsson 
19667f416cc4SJohn McCall     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
1967882d790fSAnders Carlsson     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1968882d790fSAnders Carlsson     EmitBlock(CastNotNull);
196959486a2dSAnders Carlsson   }
197059486a2dSAnders Carlsson 
19717f416cc4SJohn McCall   llvm::Value *Value;
19721162d25cSDavid Majnemer   if (isDynamicCastToVoid) {
19737f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
19741162d25cSDavid Majnemer                                                   DestTy);
19751162d25cSDavid Majnemer   } else {
19761162d25cSDavid Majnemer     assert(DestRecordTy->isRecordType() &&
19771162d25cSDavid Majnemer            "destination type must be a record type!");
19787f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
19791162d25cSDavid Majnemer                                                 DestTy, DestRecordTy, CastEnd);
198067528eaaSDavid Majnemer     CastNotNull = Builder.GetInsertBlock();
19811162d25cSDavid Majnemer   }
19823f4336cbSAnders Carlsson 
1983882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1984882d790fSAnders Carlsson     EmitBranch(CastEnd);
198559486a2dSAnders Carlsson 
1986882d790fSAnders Carlsson     EmitBlock(CastNull);
1987882d790fSAnders Carlsson     EmitBranch(CastEnd);
198859486a2dSAnders Carlsson   }
198959486a2dSAnders Carlsson 
1990882d790fSAnders Carlsson   EmitBlock(CastEnd);
199159486a2dSAnders Carlsson 
1992882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1993882d790fSAnders Carlsson     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1994882d790fSAnders Carlsson     PHI->addIncoming(Value, CastNotNull);
1995882d790fSAnders Carlsson     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
199659486a2dSAnders Carlsson 
1997882d790fSAnders Carlsson     Value = PHI;
199859486a2dSAnders Carlsson   }
199959486a2dSAnders Carlsson 
2000882d790fSAnders Carlsson   return Value;
200159486a2dSAnders Carlsson }
2002c370a7eeSEli Friedman 
2003c370a7eeSEli Friedman void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
20048631f3e8SEli Friedman   RunCleanupsScope Scope(*this);
20057f416cc4SJohn McCall   LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
20068631f3e8SEli Friedman 
2007c370a7eeSEli Friedman   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
200853c7616eSJames Y Knight   for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
2009c370a7eeSEli Friedman                                                e = E->capture_init_end();
2010c370a7eeSEli Friedman        i != e; ++i, ++CurField) {
2011c370a7eeSEli Friedman     // Emit initialization
201240ed2973SDavid Blaikie     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
201339c81e28SAlexey Bataev     if (CurField->hasCapturedVLAType()) {
201439c81e28SAlexey Bataev       auto VAT = CurField->getCapturedVLAType();
201539c81e28SAlexey Bataev       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
201639c81e28SAlexey Bataev     } else {
20175f1a04ffSEli Friedman       ArrayRef<VarDecl *> ArrayIndexes;
20185f1a04ffSEli Friedman       if (CurField->getType()->isArrayType())
20195f1a04ffSEli Friedman         ArrayIndexes = E->getCaptureInitIndexVars(i);
202040ed2973SDavid Blaikie       EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
2021c370a7eeSEli Friedman     }
2022c370a7eeSEli Friedman   }
202339c81e28SAlexey Bataev }
2024