xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/CGExprCXX.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This contains code dealing with code generation of C++ expressions
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CGCUDARuntime.h"
140b57cec5SDimitry Andric #include "CGCXXABI.h"
150b57cec5SDimitry Andric #include "CGDebugInfo.h"
160b57cec5SDimitry Andric #include "CGObjCRuntime.h"
170b57cec5SDimitry Andric #include "CodeGenFunction.h"
180b57cec5SDimitry Andric #include "ConstantEmitter.h"
190b57cec5SDimitry Andric #include "TargetInfo.h"
200b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
210b57cec5SDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
220b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
230b57cec5SDimitry Andric 
240b57cec5SDimitry Andric using namespace clang;
250b57cec5SDimitry Andric using namespace CodeGen;
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric namespace {
280b57cec5SDimitry Andric struct MemberCallInfo {
290b57cec5SDimitry Andric   RequiredArgs ReqArgs;
300b57cec5SDimitry Andric   // Number of prefix arguments for the call. Ignores the `this` pointer.
310b57cec5SDimitry Andric   unsigned PrefixSize;
320b57cec5SDimitry Andric };
330b57cec5SDimitry Andric }
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric static MemberCallInfo
361ac55f4cSDimitry Andric commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, GlobalDecl GD,
370b57cec5SDimitry Andric                                   llvm::Value *This, llvm::Value *ImplicitParam,
380b57cec5SDimitry Andric                                   QualType ImplicitParamTy, const CallExpr *CE,
390b57cec5SDimitry Andric                                   CallArgList &Args, CallArgList *RtlArgs) {
401ac55f4cSDimitry Andric   auto *MD = cast<CXXMethodDecl>(GD.getDecl());
411ac55f4cSDimitry Andric 
420b57cec5SDimitry Andric   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
430b57cec5SDimitry Andric          isa<CXXOperatorCallExpr>(CE));
445f757f3fSDimitry Andric   assert(MD->isImplicitObjectMemberFunction() &&
450b57cec5SDimitry Andric          "Trying to emit a member or operator call expr on a static method!");
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric   // Push the this ptr.
480b57cec5SDimitry Andric   const CXXRecordDecl *RD =
491ac55f4cSDimitry Andric       CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(GD);
500b57cec5SDimitry Andric   Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD));
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric   // If there is an implicit parameter (e.g. VTT), emit it.
530b57cec5SDimitry Andric   if (ImplicitParam) {
540b57cec5SDimitry Andric     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
550b57cec5SDimitry Andric   }
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
580b57cec5SDimitry Andric   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
590b57cec5SDimitry Andric   unsigned PrefixSize = Args.size() - 1;
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric   // And the rest of the call args.
620b57cec5SDimitry Andric   if (RtlArgs) {
630b57cec5SDimitry Andric     // Special case: if the caller emitted the arguments right-to-left already
640b57cec5SDimitry Andric     // (prior to emitting the *this argument), we're done. This happens for
650b57cec5SDimitry Andric     // assignment operators.
660b57cec5SDimitry Andric     Args.addFrom(*RtlArgs);
670b57cec5SDimitry Andric   } else if (CE) {
680b57cec5SDimitry Andric     // Special case: skip first argument of CXXOperatorCall (it is "this").
695f757f3fSDimitry Andric     unsigned ArgsToSkip = 0;
705f757f3fSDimitry Andric     if (const auto *Op = dyn_cast<CXXOperatorCallExpr>(CE)) {
715f757f3fSDimitry Andric       if (const auto *M = dyn_cast<CXXMethodDecl>(Op->getCalleeDecl()))
725f757f3fSDimitry Andric         ArgsToSkip =
735f757f3fSDimitry Andric             static_cast<unsigned>(!M->isExplicitObjectMemberFunction());
745f757f3fSDimitry Andric     }
750b57cec5SDimitry Andric     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
760b57cec5SDimitry Andric                      CE->getDirectCallee());
770b57cec5SDimitry Andric   } else {
780b57cec5SDimitry Andric     assert(
790b57cec5SDimitry Andric         FPT->getNumParams() == 0 &&
800b57cec5SDimitry Andric         "No CallExpr specified for function with non-zero number of arguments");
810b57cec5SDimitry Andric   }
820b57cec5SDimitry Andric   return {required, PrefixSize};
830b57cec5SDimitry Andric }
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
860b57cec5SDimitry Andric     const CXXMethodDecl *MD, const CGCallee &Callee,
870b57cec5SDimitry Andric     ReturnValueSlot ReturnValue,
880b57cec5SDimitry Andric     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
890b57cec5SDimitry Andric     const CallExpr *CE, CallArgList *RtlArgs) {
900b57cec5SDimitry Andric   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
910b57cec5SDimitry Andric   CallArgList Args;
920b57cec5SDimitry Andric   MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
930b57cec5SDimitry Andric       *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
940b57cec5SDimitry Andric   auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
950b57cec5SDimitry Andric       Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
960b57cec5SDimitry Andric   return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
97fe6060f1SDimitry Andric                   CE && CE == MustTailCall,
980b57cec5SDimitry Andric                   CE ? CE->getExprLoc() : SourceLocation());
990b57cec5SDimitry Andric }
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXDestructorCall(
1020b57cec5SDimitry Andric     GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy,
1030b57cec5SDimitry Andric     llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) {
1040b57cec5SDimitry Andric   const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl());
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric   assert(!ThisTy.isNull());
1070b57cec5SDimitry Andric   assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&
1080b57cec5SDimitry Andric          "Pointer/Object mixup");
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   LangAS SrcAS = ThisTy.getAddressSpace();
1110b57cec5SDimitry Andric   LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
1120b57cec5SDimitry Andric   if (SrcAS != DstAS) {
1130b57cec5SDimitry Andric     QualType DstTy = DtorDecl->getThisType();
1140b57cec5SDimitry Andric     llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy);
1150b57cec5SDimitry Andric     This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS,
1160b57cec5SDimitry Andric                                                  NewType);
1170b57cec5SDimitry Andric   }
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric   CallArgList Args;
1201ac55f4cSDimitry Andric   commonEmitCXXMemberOrOperatorCall(*this, Dtor, This, ImplicitParam,
1210b57cec5SDimitry Andric                                     ImplicitParamTy, CE, Args, nullptr);
1220b57cec5SDimitry Andric   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee,
123fe6060f1SDimitry Andric                   ReturnValueSlot(), Args, nullptr, CE && CE == MustTailCall,
124c3ca3130SDimitry Andric                   CE ? CE->getExprLoc() : SourceLocation{});
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
1280b57cec5SDimitry Andric                                             const CXXPseudoDestructorExpr *E) {
1290b57cec5SDimitry Andric   QualType DestroyedType = E->getDestroyedType();
1300b57cec5SDimitry Andric   if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
1310b57cec5SDimitry Andric     // Automatic Reference Counting:
1320b57cec5SDimitry Andric     //   If the pseudo-expression names a retainable object with weak or
1330b57cec5SDimitry Andric     //   strong lifetime, the object shall be released.
1340b57cec5SDimitry Andric     Expr *BaseExpr = E->getBase();
1350b57cec5SDimitry Andric     Address BaseValue = Address::invalid();
1360b57cec5SDimitry Andric     Qualifiers BaseQuals;
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric     // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
1390b57cec5SDimitry Andric     if (E->isArrow()) {
1400b57cec5SDimitry Andric       BaseValue = EmitPointerWithAlignment(BaseExpr);
141480093f4SDimitry Andric       const auto *PTy = BaseExpr->getType()->castAs<PointerType>();
1420b57cec5SDimitry Andric       BaseQuals = PTy->getPointeeType().getQualifiers();
1430b57cec5SDimitry Andric     } else {
1440b57cec5SDimitry Andric       LValue BaseLV = EmitLValue(BaseExpr);
145*0fca6ea1SDimitry Andric       BaseValue = BaseLV.getAddress();
1460b57cec5SDimitry Andric       QualType BaseTy = BaseExpr->getType();
1470b57cec5SDimitry Andric       BaseQuals = BaseTy.getQualifiers();
1480b57cec5SDimitry Andric     }
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric     switch (DestroyedType.getObjCLifetime()) {
1510b57cec5SDimitry Andric     case Qualifiers::OCL_None:
1520b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
1530b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
1540b57cec5SDimitry Andric       break;
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
1570b57cec5SDimitry Andric       EmitARCRelease(Builder.CreateLoad(BaseValue,
1580b57cec5SDimitry Andric                         DestroyedType.isVolatileQualified()),
1590b57cec5SDimitry Andric                      ARCPreciseLifetime);
1600b57cec5SDimitry Andric       break;
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
1630b57cec5SDimitry Andric       EmitARCDestroyWeak(BaseValue);
1640b57cec5SDimitry Andric       break;
1650b57cec5SDimitry Andric     }
1660b57cec5SDimitry Andric   } else {
1670b57cec5SDimitry Andric     // C++ [expr.pseudo]p1:
1680b57cec5SDimitry Andric     //   The result shall only be used as the operand for the function call
1690b57cec5SDimitry Andric     //   operator (), and the result of such a call has type void. The only
1700b57cec5SDimitry Andric     //   effect is the evaluation of the postfix-expression before the dot or
1710b57cec5SDimitry Andric     //   arrow.
1720b57cec5SDimitry Andric     EmitIgnoredExpr(E->getBase());
1730b57cec5SDimitry Andric   }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   return RValue::get(nullptr);
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric static CXXRecordDecl *getCXXRecord(const Expr *E) {
1790b57cec5SDimitry Andric   QualType T = E->getType();
1800b57cec5SDimitry Andric   if (const PointerType *PTy = T->getAs<PointerType>())
1810b57cec5SDimitry Andric     T = PTy->getPointeeType();
1820b57cec5SDimitry Andric   const RecordType *Ty = T->castAs<RecordType>();
1830b57cec5SDimitry Andric   return cast<CXXRecordDecl>(Ty->getDecl());
1840b57cec5SDimitry Andric }
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric // Note: This function also emit constructor calls to support a MSVC
1870b57cec5SDimitry Andric // extensions allowing explicit constructor function call.
1880b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
1890b57cec5SDimitry Andric                                               ReturnValueSlot ReturnValue) {
1900b57cec5SDimitry Andric   const Expr *callee = CE->getCallee()->IgnoreParens();
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   if (isa<BinaryOperator>(callee))
1930b57cec5SDimitry Andric     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   const MemberExpr *ME = cast<MemberExpr>(callee);
1960b57cec5SDimitry Andric   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric   if (MD->isStatic()) {
1990b57cec5SDimitry Andric     // The method is static, emit it as we would a regular call.
2000b57cec5SDimitry Andric     CGCallee callee =
2010b57cec5SDimitry Andric         CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));
2020b57cec5SDimitry Andric     return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
2030b57cec5SDimitry Andric                     ReturnValue);
2040b57cec5SDimitry Andric   }
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   bool HasQualifier = ME->hasQualifier();
2070b57cec5SDimitry Andric   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
2080b57cec5SDimitry Andric   bool IsArrow = ME->isArrow();
2090b57cec5SDimitry Andric   const Expr *Base = ME->getBase();
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric   return EmitCXXMemberOrOperatorMemberCallExpr(
2120b57cec5SDimitry Andric       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
2160b57cec5SDimitry Andric     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
2170b57cec5SDimitry Andric     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
2180b57cec5SDimitry Andric     const Expr *Base) {
2190b57cec5SDimitry Andric   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   // Compute the object pointer.
2220b57cec5SDimitry Andric   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric   const CXXMethodDecl *DevirtualizedMethod = nullptr;
2250b57cec5SDimitry Andric   if (CanUseVirtualCall &&
2260b57cec5SDimitry Andric       MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
2270b57cec5SDimitry Andric     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2280b57cec5SDimitry Andric     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
2290b57cec5SDimitry Andric     assert(DevirtualizedMethod);
2300b57cec5SDimitry Andric     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
231e8d8bef9SDimitry Andric     const Expr *Inner = Base->IgnoreParenBaseCasts();
2320b57cec5SDimitry Andric     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
2330b57cec5SDimitry Andric         MD->getReturnType().getCanonicalType())
2340b57cec5SDimitry Andric       // If the return types are not the same, this might be a case where more
2350b57cec5SDimitry Andric       // code needs to run to compensate for it. For example, the derived
2360b57cec5SDimitry Andric       // method might return a type that inherits form from the return
2370b57cec5SDimitry Andric       // type of MD and has a prefix.
2380b57cec5SDimitry Andric       // For now we just avoid devirtualizing these covariant cases.
2390b57cec5SDimitry Andric       DevirtualizedMethod = nullptr;
2400b57cec5SDimitry Andric     else if (getCXXRecord(Inner) == DevirtualizedClass)
2410b57cec5SDimitry Andric       // If the class of the Inner expression is where the dynamic method
2420b57cec5SDimitry Andric       // is defined, build the this pointer from it.
2430b57cec5SDimitry Andric       Base = Inner;
2440b57cec5SDimitry Andric     else if (getCXXRecord(Base) != DevirtualizedClass) {
2450b57cec5SDimitry Andric       // If the method is defined in a class that is not the best dynamic
2460b57cec5SDimitry Andric       // one or the one of the full expression, we would have to build
2470b57cec5SDimitry Andric       // a derived-to-base cast to compute the correct this pointer, but
2480b57cec5SDimitry Andric       // we don't have support for that yet, so do a virtual call.
2490b57cec5SDimitry Andric       DevirtualizedMethod = nullptr;
2500b57cec5SDimitry Andric     }
2510b57cec5SDimitry Andric   }
2520b57cec5SDimitry Andric 
253480093f4SDimitry Andric   bool TrivialForCodegen =
254480093f4SDimitry Andric       MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion());
255480093f4SDimitry Andric   bool TrivialAssignment =
256480093f4SDimitry Andric       TrivialForCodegen &&
257480093f4SDimitry Andric       (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
258480093f4SDimitry Andric       !MD->getParent()->mayInsertExtraPadding();
259480093f4SDimitry Andric 
2600b57cec5SDimitry Andric   // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
2610b57cec5SDimitry Andric   // operator before the LHS.
2620b57cec5SDimitry Andric   CallArgList RtlArgStorage;
2630b57cec5SDimitry Andric   CallArgList *RtlArgs = nullptr;
264480093f4SDimitry Andric   LValue TrivialAssignmentRHS;
2650b57cec5SDimitry Andric   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
2660b57cec5SDimitry Andric     if (OCE->isAssignmentOp()) {
267480093f4SDimitry Andric       if (TrivialAssignment) {
268480093f4SDimitry Andric         TrivialAssignmentRHS = EmitLValue(CE->getArg(1));
269480093f4SDimitry Andric       } else {
2700b57cec5SDimitry Andric         RtlArgs = &RtlArgStorage;
2710b57cec5SDimitry Andric         EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
2720b57cec5SDimitry Andric                      drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
2730b57cec5SDimitry Andric                      /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
2740b57cec5SDimitry Andric       }
2750b57cec5SDimitry Andric     }
276480093f4SDimitry Andric   }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   LValue This;
2790b57cec5SDimitry Andric   if (IsArrow) {
2800b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
2810b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo;
2820b57cec5SDimitry Andric     Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
283*0fca6ea1SDimitry Andric     This = MakeAddrLValue(ThisValue, Base->getType()->getPointeeType(),
284*0fca6ea1SDimitry Andric                           BaseInfo, TBAAInfo);
2850b57cec5SDimitry Andric   } else {
2860b57cec5SDimitry Andric     This = EmitLValue(Base);
2870b57cec5SDimitry Andric   }
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2900b57cec5SDimitry Andric     // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
2910b57cec5SDimitry Andric     // constructing a new complete object of type Ctor.
2920b57cec5SDimitry Andric     assert(!RtlArgs);
2930b57cec5SDimitry Andric     assert(ReturnValue.isNull() && "Constructor shouldn't have return value");
2940b57cec5SDimitry Andric     CallArgList Args;
2950b57cec5SDimitry Andric     commonEmitCXXMemberOrOperatorCall(
2961ac55f4cSDimitry Andric         *this, {Ctor, Ctor_Complete}, This.getPointer(*this),
2971ac55f4cSDimitry Andric         /*ImplicitParam=*/nullptr,
2980b57cec5SDimitry Andric         /*ImplicitParamTy=*/QualType(), CE, Args, nullptr);
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric     EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
301*0fca6ea1SDimitry Andric                            /*Delegating=*/false, This.getAddress(), Args,
3020b57cec5SDimitry Andric                            AggValueSlot::DoesNotOverlap, CE->getExprLoc(),
3030b57cec5SDimitry Andric                            /*NewPointerIsChecked=*/false);
3040b57cec5SDimitry Andric     return RValue::get(nullptr);
3050b57cec5SDimitry Andric   }
3060b57cec5SDimitry Andric 
307480093f4SDimitry Andric   if (TrivialForCodegen) {
308480093f4SDimitry Andric     if (isa<CXXDestructorDecl>(MD))
309480093f4SDimitry Andric       return RValue::get(nullptr);
310480093f4SDimitry Andric 
311480093f4SDimitry Andric     if (TrivialAssignment) {
3120b57cec5SDimitry Andric       // We don't like to generate the trivial copy/move assignment operator
3130b57cec5SDimitry Andric       // when it isn't necessary; just produce the proper effect here.
314480093f4SDimitry Andric       // It's important that we use the result of EmitLValue here rather than
315480093f4SDimitry Andric       // emitting call arguments, in order to preserve TBAA information from
316480093f4SDimitry Andric       // the RHS.
3170b57cec5SDimitry Andric       LValue RHS = isa<CXXOperatorCallExpr>(CE)
318480093f4SDimitry Andric                        ? TrivialAssignmentRHS
3190b57cec5SDimitry Andric                        : EmitLValue(*CE->arg_begin());
3200b57cec5SDimitry Andric       EmitAggregateAssign(This, RHS, CE->getType());
321480093f4SDimitry Andric       return RValue::get(This.getPointer(*this));
3220b57cec5SDimitry Andric     }
323480093f4SDimitry Andric 
324480093f4SDimitry Andric     assert(MD->getParent()->mayInsertExtraPadding() &&
325480093f4SDimitry Andric            "unknown trivial member function");
3260b57cec5SDimitry Andric   }
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric   // Compute the function type we're calling.
3290b57cec5SDimitry Andric   const CXXMethodDecl *CalleeDecl =
3300b57cec5SDimitry Andric       DevirtualizedMethod ? DevirtualizedMethod : MD;
3310b57cec5SDimitry Andric   const CGFunctionInfo *FInfo = nullptr;
3320b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
3330b57cec5SDimitry Andric     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
3340b57cec5SDimitry Andric         GlobalDecl(Dtor, Dtor_Complete));
3350b57cec5SDimitry Andric   else
3360b57cec5SDimitry Andric     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   // C++11 [class.mfct.non-static]p2:
3410b57cec5SDimitry Andric   //   If a non-static member function of a class X is called for an object that
3420b57cec5SDimitry Andric   //   is not of type X, or of a type derived from X, the behavior is undefined.
3430b57cec5SDimitry Andric   SourceLocation CallLoc;
3440b57cec5SDimitry Andric   ASTContext &C = getContext();
3450b57cec5SDimitry Andric   if (CE)
3460b57cec5SDimitry Andric     CallLoc = CE->getExprLoc();
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric   SanitizerSet SkippedChecks;
3490b57cec5SDimitry Andric   if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
3500b57cec5SDimitry Andric     auto *IOA = CMCE->getImplicitObjectArgument();
3510b57cec5SDimitry Andric     bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
3520b57cec5SDimitry Andric     if (IsImplicitObjectCXXThis)
3530b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::Alignment, true);
3540b57cec5SDimitry Andric     if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
3550b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::Null, true);
3560b57cec5SDimitry Andric   }
357*0fca6ea1SDimitry Andric 
358*0fca6ea1SDimitry Andric   if (sanitizePerformTypeCheck())
359480093f4SDimitry Andric     EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc,
360*0fca6ea1SDimitry Andric                   This.emitRawPointer(*this),
3610b57cec5SDimitry Andric                   C.getRecordType(CalleeDecl->getParent()),
3620b57cec5SDimitry Andric                   /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   // C++ [class.virtual]p12:
3650b57cec5SDimitry Andric   //   Explicit qualification with the scope operator (5.1) suppresses the
3660b57cec5SDimitry Andric   //   virtual call mechanism.
3670b57cec5SDimitry Andric   //
3680b57cec5SDimitry Andric   // We also don't emit a virtual call if the base expression has a record type
3690b57cec5SDimitry Andric   // because then we know what the type is.
3700b57cec5SDimitry Andric   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) {
3730b57cec5SDimitry Andric     assert(CE->arg_begin() == CE->arg_end() &&
3740b57cec5SDimitry Andric            "Destructor shouldn't have explicit parameters");
3750b57cec5SDimitry Andric     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
3760b57cec5SDimitry Andric     if (UseVirtualCall) {
377480093f4SDimitry Andric       CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
378*0fca6ea1SDimitry Andric                                                 This.getAddress(),
3790b57cec5SDimitry Andric                                                 cast<CXXMemberCallExpr>(CE));
3800b57cec5SDimitry Andric     } else {
3810b57cec5SDimitry Andric       GlobalDecl GD(Dtor, Dtor_Complete);
3820b57cec5SDimitry Andric       CGCallee Callee;
3830b57cec5SDimitry Andric       if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier)
3840b57cec5SDimitry Andric         Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty);
3850b57cec5SDimitry Andric       else if (!DevirtualizedMethod)
3860b57cec5SDimitry Andric         Callee =
3870b57cec5SDimitry Andric             CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD);
3880b57cec5SDimitry Andric       else {
3890b57cec5SDimitry Andric         Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD);
3900b57cec5SDimitry Andric       }
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric       QualType ThisTy =
3930b57cec5SDimitry Andric           IsArrow ? Base->getType()->getPointeeType() : Base->getType();
394480093f4SDimitry Andric       EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy,
3950b57cec5SDimitry Andric                             /*ImplicitParam=*/nullptr,
396c3ca3130SDimitry Andric                             /*ImplicitParamTy=*/QualType(), CE);
3970b57cec5SDimitry Andric     }
3980b57cec5SDimitry Andric     return RValue::get(nullptr);
3990b57cec5SDimitry Andric   }
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric   // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
4020b57cec5SDimitry Andric   // 'CalleeDecl' instead.
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric   CGCallee Callee;
4050b57cec5SDimitry Andric   if (UseVirtualCall) {
406*0fca6ea1SDimitry Andric     Callee = CGCallee::forVirtual(CE, MD, This.getAddress(), Ty);
4070b57cec5SDimitry Andric   } else {
4080b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::CFINVCall) &&
4090b57cec5SDimitry Andric         MD->getParent()->isDynamicClass()) {
4100b57cec5SDimitry Andric       llvm::Value *VTable;
4110b57cec5SDimitry Andric       const CXXRecordDecl *RD;
412480093f4SDimitry Andric       std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr(
413*0fca6ea1SDimitry Andric           *this, This.getAddress(), CalleeDecl->getParent());
4140b57cec5SDimitry Andric       EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());
4150b57cec5SDimitry Andric     }
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
4180b57cec5SDimitry Andric       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
4190b57cec5SDimitry Andric     else if (!DevirtualizedMethod)
4200b57cec5SDimitry Andric       Callee =
4210b57cec5SDimitry Andric           CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));
4220b57cec5SDimitry Andric     else {
4230b57cec5SDimitry Andric       Callee =
4240b57cec5SDimitry Andric           CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
4250b57cec5SDimitry Andric                               GlobalDecl(DevirtualizedMethod));
4260b57cec5SDimitry Andric     }
4270b57cec5SDimitry Andric   }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   if (MD->isVirtual()) {
4300b57cec5SDimitry Andric     Address NewThisAddr =
4310b57cec5SDimitry Andric         CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
432*0fca6ea1SDimitry Andric             *this, CalleeDecl, This.getAddress(), UseVirtualCall);
4330b57cec5SDimitry Andric     This.setAddress(NewThisAddr);
4340b57cec5SDimitry Andric   }
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric   return EmitCXXMemberOrOperatorCall(
437480093f4SDimitry Andric       CalleeDecl, Callee, ReturnValue, This.getPointer(*this),
4380b57cec5SDimitry Andric       /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
4390b57cec5SDimitry Andric }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric RValue
4420b57cec5SDimitry Andric CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
4430b57cec5SDimitry Andric                                               ReturnValueSlot ReturnValue) {
4440b57cec5SDimitry Andric   const BinaryOperator *BO =
4450b57cec5SDimitry Andric       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
4460b57cec5SDimitry Andric   const Expr *BaseExpr = BO->getLHS();
4470b57cec5SDimitry Andric   const Expr *MemFnExpr = BO->getRHS();
4480b57cec5SDimitry Andric 
449a7dea167SDimitry Andric   const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();
450a7dea167SDimitry Andric   const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();
451a7dea167SDimitry Andric   const auto *RD =
452a7dea167SDimitry Andric       cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric   // Emit the 'this' pointer.
4550b57cec5SDimitry Andric   Address This = Address::invalid();
4560b57cec5SDimitry Andric   if (BO->getOpcode() == BO_PtrMemI)
45706c3fb27SDimitry Andric     This = EmitPointerWithAlignment(BaseExpr, nullptr, nullptr, KnownNonNull);
4580b57cec5SDimitry Andric   else
459*0fca6ea1SDimitry Andric     This = EmitLValue(BaseExpr, KnownNonNull).getAddress();
4600b57cec5SDimitry Andric 
461*0fca6ea1SDimitry Andric   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.emitRawPointer(*this),
4620b57cec5SDimitry Andric                 QualType(MPT->getClass(), 0));
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   // Get the member function pointer.
4650b57cec5SDimitry Andric   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   // Ask the ABI to load the callee.  Note that This is modified.
4680b57cec5SDimitry Andric   llvm::Value *ThisPtrForCall = nullptr;
4690b57cec5SDimitry Andric   CGCallee Callee =
4700b57cec5SDimitry Andric     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
4710b57cec5SDimitry Andric                                              ThisPtrForCall, MemFnPtr, MPT);
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   CallArgList Args;
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric   QualType ThisType =
4760b57cec5SDimitry Andric     getContext().getPointerType(getContext().getTagDeclType(RD));
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   // Push the this ptr.
4790b57cec5SDimitry Andric   Args.add(RValue::get(ThisPtrForCall), ThisType);
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   // And the rest of the call args
4840b57cec5SDimitry Andric   EmitCallArgs(Args, FPT, E->arguments());
4850b57cec5SDimitry Andric   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
4860b57cec5SDimitry Andric                                                       /*PrefixSize=*/0),
487fe6060f1SDimitry Andric                   Callee, ReturnValue, Args, nullptr, E == MustTailCall,
488fe6060f1SDimitry Andric                   E->getExprLoc());
4890b57cec5SDimitry Andric }
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric RValue
4920b57cec5SDimitry Andric CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
4930b57cec5SDimitry Andric                                                const CXXMethodDecl *MD,
4940b57cec5SDimitry Andric                                                ReturnValueSlot ReturnValue) {
4955f757f3fSDimitry Andric   assert(MD->isImplicitObjectMemberFunction() &&
4960b57cec5SDimitry Andric          "Trying to emit a member call expr on a static method!");
4970b57cec5SDimitry Andric   return EmitCXXMemberOrOperatorMemberCallExpr(
4980b57cec5SDimitry Andric       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
4990b57cec5SDimitry Andric       /*IsArrow=*/false, E->getArg(0));
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
5030b57cec5SDimitry Andric                                                ReturnValueSlot ReturnValue) {
5040b57cec5SDimitry Andric   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
5050b57cec5SDimitry Andric }
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
5080b57cec5SDimitry Andric                                             Address DestPtr,
5090b57cec5SDimitry Andric                                             const CXXRecordDecl *Base) {
5100b57cec5SDimitry Andric   if (Base->isEmpty())
5110b57cec5SDimitry Andric     return;
5120b57cec5SDimitry Andric 
51306c3fb27SDimitry Andric   DestPtr = DestPtr.withElementType(CGF.Int8Ty);
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
5160b57cec5SDimitry Andric   CharUnits NVSize = Layout.getNonVirtualSize();
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
5190b57cec5SDimitry Andric   // present, they are initialized by the most derived class before calling the
5200b57cec5SDimitry Andric   // constructor.
5210b57cec5SDimitry Andric   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
5220b57cec5SDimitry Andric   Stores.emplace_back(CharUnits::Zero(), NVSize);
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   // Each store is split by the existence of a vbptr.
5250b57cec5SDimitry Andric   CharUnits VBPtrWidth = CGF.getPointerSize();
5260b57cec5SDimitry Andric   std::vector<CharUnits> VBPtrOffsets =
5270b57cec5SDimitry Andric       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
5280b57cec5SDimitry Andric   for (CharUnits VBPtrOffset : VBPtrOffsets) {
5290b57cec5SDimitry Andric     // Stop before we hit any virtual base pointers located in virtual bases.
5300b57cec5SDimitry Andric     if (VBPtrOffset >= NVSize)
5310b57cec5SDimitry Andric       break;
5320b57cec5SDimitry Andric     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
5330b57cec5SDimitry Andric     CharUnits LastStoreOffset = LastStore.first;
5340b57cec5SDimitry Andric     CharUnits LastStoreSize = LastStore.second;
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric     CharUnits SplitBeforeOffset = LastStoreOffset;
5370b57cec5SDimitry Andric     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
5380b57cec5SDimitry Andric     assert(!SplitBeforeSize.isNegative() && "negative store size!");
5390b57cec5SDimitry Andric     if (!SplitBeforeSize.isZero())
5400b57cec5SDimitry Andric       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
5430b57cec5SDimitry Andric     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
5440b57cec5SDimitry Andric     assert(!SplitAfterSize.isNegative() && "negative store size!");
5450b57cec5SDimitry Andric     if (!SplitAfterSize.isZero())
5460b57cec5SDimitry Andric       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
5470b57cec5SDimitry Andric   }
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric   // If the type contains a pointer to data member we can't memset it to zero.
5500b57cec5SDimitry Andric   // Instead, create a null constant and copy it to the destination.
5510b57cec5SDimitry Andric   // TODO: there are other patterns besides zero that we can usefully memset,
5520b57cec5SDimitry Andric   // like -1, which happens to be the pattern used by member-pointers.
5530b57cec5SDimitry Andric   // TODO: isZeroInitializable can be over-conservative in the case where a
5540b57cec5SDimitry Andric   // virtual base contains a member pointer.
5550b57cec5SDimitry Andric   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
5560b57cec5SDimitry Andric   if (!NullConstantForBase->isNullValue()) {
5570b57cec5SDimitry Andric     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
5580b57cec5SDimitry Andric         CGF.CGM.getModule(), NullConstantForBase->getType(),
5590b57cec5SDimitry Andric         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
5600b57cec5SDimitry Andric         NullConstantForBase, Twine());
5610b57cec5SDimitry Andric 
56281ad6265SDimitry Andric     CharUnits Align =
56381ad6265SDimitry Andric         std::max(Layout.getNonVirtualAlignment(), DestPtr.getAlignment());
564a7dea167SDimitry Andric     NullVariable->setAlignment(Align.getAsAlign());
5650b57cec5SDimitry Andric 
56606c3fb27SDimitry Andric     Address SrcPtr(NullVariable, CGF.Int8Ty, Align);
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric     // Get and call the appropriate llvm.memcpy overload.
5690b57cec5SDimitry Andric     for (std::pair<CharUnits, CharUnits> Store : Stores) {
5700b57cec5SDimitry Andric       CharUnits StoreOffset = Store.first;
5710b57cec5SDimitry Andric       CharUnits StoreSize = Store.second;
5720b57cec5SDimitry Andric       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5730b57cec5SDimitry Andric       CGF.Builder.CreateMemCpy(
5740b57cec5SDimitry Andric           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5750b57cec5SDimitry Andric           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
5760b57cec5SDimitry Andric           StoreSizeVal);
5770b57cec5SDimitry Andric     }
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric   // Otherwise, just memset the whole thing to zero.  This is legal
5800b57cec5SDimitry Andric   // because in LLVM, all default initializers (other than the ones we just
5810b57cec5SDimitry Andric   // handled above) are guaranteed to have a bit pattern of all zeros.
5820b57cec5SDimitry Andric   } else {
5830b57cec5SDimitry Andric     for (std::pair<CharUnits, CharUnits> Store : Stores) {
5840b57cec5SDimitry Andric       CharUnits StoreOffset = Store.first;
5850b57cec5SDimitry Andric       CharUnits StoreSize = Store.second;
5860b57cec5SDimitry Andric       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5870b57cec5SDimitry Andric       CGF.Builder.CreateMemSet(
5880b57cec5SDimitry Andric           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5890b57cec5SDimitry Andric           CGF.Builder.getInt8(0), StoreSizeVal);
5900b57cec5SDimitry Andric     }
5910b57cec5SDimitry Andric   }
5920b57cec5SDimitry Andric }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric void
5950b57cec5SDimitry Andric CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
5960b57cec5SDimitry Andric                                       AggValueSlot Dest) {
5970b57cec5SDimitry Andric   assert(!Dest.isIgnored() && "Must have a destination!");
5980b57cec5SDimitry Andric   const CXXConstructorDecl *CD = E->getConstructor();
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric   // If we require zero initialization before (or instead of) calling the
6010b57cec5SDimitry Andric   // constructor, as can be the case with a non-user-provided default
6020b57cec5SDimitry Andric   // constructor, emit the zero initialization now, unless destination is
6030b57cec5SDimitry Andric   // already zeroed.
6040b57cec5SDimitry Andric   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
6050b57cec5SDimitry Andric     switch (E->getConstructionKind()) {
6065f757f3fSDimitry Andric     case CXXConstructionKind::Delegating:
6075f757f3fSDimitry Andric     case CXXConstructionKind::Complete:
6080b57cec5SDimitry Andric       EmitNullInitialization(Dest.getAddress(), E->getType());
6090b57cec5SDimitry Andric       break;
6105f757f3fSDimitry Andric     case CXXConstructionKind::VirtualBase:
6115f757f3fSDimitry Andric     case CXXConstructionKind::NonVirtualBase:
6120b57cec5SDimitry Andric       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
6130b57cec5SDimitry Andric                                       CD->getParent());
6140b57cec5SDimitry Andric       break;
6150b57cec5SDimitry Andric     }
6160b57cec5SDimitry Andric   }
6170b57cec5SDimitry Andric 
6180b57cec5SDimitry Andric   // If this is a call to a trivial default constructor, do nothing.
6190b57cec5SDimitry Andric   if (CD->isTrivial() && CD->isDefaultConstructor())
6200b57cec5SDimitry Andric     return;
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric   // Elide the constructor if we're constructing from a temporary.
6230b57cec5SDimitry Andric   if (getLangOpts().ElideConstructors && E->isElidable()) {
62428a41182SDimitry Andric     // FIXME: This only handles the simplest case, where the source object
62528a41182SDimitry Andric     //        is passed directly as the first argument to the constructor.
62628a41182SDimitry Andric     //        This should also handle stepping though implicit casts and
62728a41182SDimitry Andric     //        conversion sequences which involve two steps, with a
62828a41182SDimitry Andric     //        conversion operator followed by a converting constructor.
62928a41182SDimitry Andric     const Expr *SrcObj = E->getArg(0);
63028a41182SDimitry Andric     assert(SrcObj->isTemporaryObject(getContext(), CD->getParent()));
63128a41182SDimitry Andric     assert(
63228a41182SDimitry Andric         getContext().hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
63328a41182SDimitry Andric     EmitAggExpr(SrcObj, Dest);
6340b57cec5SDimitry Andric     return;
6350b57cec5SDimitry Andric   }
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   if (const ArrayType *arrayType
6380b57cec5SDimitry Andric         = getContext().getAsArrayType(E->getType())) {
6390b57cec5SDimitry Andric     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,
6400b57cec5SDimitry Andric                                Dest.isSanitizerChecked());
6410b57cec5SDimitry Andric   } else {
6420b57cec5SDimitry Andric     CXXCtorType Type = Ctor_Complete;
6430b57cec5SDimitry Andric     bool ForVirtualBase = false;
6440b57cec5SDimitry Andric     bool Delegating = false;
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric     switch (E->getConstructionKind()) {
6475f757f3fSDimitry Andric     case CXXConstructionKind::Delegating:
6480b57cec5SDimitry Andric       // We should be emitting a constructor; GlobalDecl will assert this
6490b57cec5SDimitry Andric       Type = CurGD.getCtorType();
6500b57cec5SDimitry Andric       Delegating = true;
6510b57cec5SDimitry Andric       break;
6520b57cec5SDimitry Andric 
6535f757f3fSDimitry Andric     case CXXConstructionKind::Complete:
6540b57cec5SDimitry Andric       Type = Ctor_Complete;
6550b57cec5SDimitry Andric       break;
6560b57cec5SDimitry Andric 
6575f757f3fSDimitry Andric     case CXXConstructionKind::VirtualBase:
6580b57cec5SDimitry Andric       ForVirtualBase = true;
659bdd1243dSDimitry Andric       [[fallthrough]];
6600b57cec5SDimitry Andric 
6615f757f3fSDimitry Andric     case CXXConstructionKind::NonVirtualBase:
6620b57cec5SDimitry Andric       Type = Ctor_Base;
6630b57cec5SDimitry Andric      }
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric      // Call the constructor.
6660b57cec5SDimitry Andric      EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E);
6670b57cec5SDimitry Andric   }
6680b57cec5SDimitry Andric }
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
6710b57cec5SDimitry Andric                                                  const Expr *Exp) {
6720b57cec5SDimitry Andric   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
6730b57cec5SDimitry Andric     Exp = E->getSubExpr();
6740b57cec5SDimitry Andric   assert(isa<CXXConstructExpr>(Exp) &&
6750b57cec5SDimitry Andric          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
6760b57cec5SDimitry Andric   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
6770b57cec5SDimitry Andric   const CXXConstructorDecl *CD = E->getConstructor();
6780b57cec5SDimitry Andric   RunCleanupsScope Scope(*this);
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric   // If we require zero initialization before (or instead of) calling the
6810b57cec5SDimitry Andric   // constructor, as can be the case with a non-user-provided default
6820b57cec5SDimitry Andric   // constructor, emit the zero initialization now.
6830b57cec5SDimitry Andric   // FIXME. Do I still need this for a copy ctor synthesis?
6840b57cec5SDimitry Andric   if (E->requiresZeroInitialization())
6850b57cec5SDimitry Andric     EmitNullInitialization(Dest, E->getType());
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric   assert(!getContext().getAsConstantArrayType(E->getType())
6880b57cec5SDimitry Andric          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
6890b57cec5SDimitry Andric   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
6900b57cec5SDimitry Andric }
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
6930b57cec5SDimitry Andric                                         const CXXNewExpr *E) {
6940b57cec5SDimitry Andric   if (!E->isArray())
6950b57cec5SDimitry Andric     return CharUnits::Zero();
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric   // No cookie is required if the operator new[] being used is the
6980b57cec5SDimitry Andric   // reserved placement operator new[].
6990b57cec5SDimitry Andric   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
7000b57cec5SDimitry Andric     return CharUnits::Zero();
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
7030b57cec5SDimitry Andric }
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
7060b57cec5SDimitry Andric                                         const CXXNewExpr *e,
7070b57cec5SDimitry Andric                                         unsigned minElements,
7080b57cec5SDimitry Andric                                         llvm::Value *&numElements,
7090b57cec5SDimitry Andric                                         llvm::Value *&sizeWithoutCookie) {
7100b57cec5SDimitry Andric   QualType type = e->getAllocatedType();
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric   if (!e->isArray()) {
7130b57cec5SDimitry Andric     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
7140b57cec5SDimitry Andric     sizeWithoutCookie
7150b57cec5SDimitry Andric       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
7160b57cec5SDimitry Andric     return sizeWithoutCookie;
7170b57cec5SDimitry Andric   }
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   // The width of size_t.
7200b57cec5SDimitry Andric   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
7210b57cec5SDimitry Andric 
7220b57cec5SDimitry Andric   // Figure out the cookie size.
7230b57cec5SDimitry Andric   llvm::APInt cookieSize(sizeWidth,
7240b57cec5SDimitry Andric                          CalculateCookiePadding(CGF, e).getQuantity());
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   // Emit the array size expression.
7270b57cec5SDimitry Andric   // We multiply the size of all dimensions for NumElements.
7280b57cec5SDimitry Andric   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
7290b57cec5SDimitry Andric   numElements =
7300b57cec5SDimitry Andric     ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType());
7310b57cec5SDimitry Andric   if (!numElements)
7320b57cec5SDimitry Andric     numElements = CGF.EmitScalarExpr(*e->getArraySize());
7330b57cec5SDimitry Andric   assert(isa<llvm::IntegerType>(numElements->getType()));
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric   // The number of elements can be have an arbitrary integer type;
7360b57cec5SDimitry Andric   // essentially, we need to multiply it by a constant factor, add a
7370b57cec5SDimitry Andric   // cookie size, and verify that the result is representable as a
7380b57cec5SDimitry Andric   // size_t.  That's just a gloss, though, and it's wrong in one
7390b57cec5SDimitry Andric   // important way: if the count is negative, it's an error even if
7400b57cec5SDimitry Andric   // the cookie size would bring the total size >= 0.
7410b57cec5SDimitry Andric   bool isSigned
7420b57cec5SDimitry Andric     = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
7430b57cec5SDimitry Andric   llvm::IntegerType *numElementsType
7440b57cec5SDimitry Andric     = cast<llvm::IntegerType>(numElements->getType());
7450b57cec5SDimitry Andric   unsigned numElementsWidth = numElementsType->getBitWidth();
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric   // Compute the constant factor.
7480b57cec5SDimitry Andric   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
7490b57cec5SDimitry Andric   while (const ConstantArrayType *CAT
7500b57cec5SDimitry Andric              = CGF.getContext().getAsConstantArrayType(type)) {
7510b57cec5SDimitry Andric     type = CAT->getElementType();
7520b57cec5SDimitry Andric     arraySizeMultiplier *= CAT->getSize();
7530b57cec5SDimitry Andric   }
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
7560b57cec5SDimitry Andric   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
7570b57cec5SDimitry Andric   typeSizeMultiplier *= arraySizeMultiplier;
7580b57cec5SDimitry Andric 
7590b57cec5SDimitry Andric   // This will be a size_t.
7600b57cec5SDimitry Andric   llvm::Value *size;
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
7630b57cec5SDimitry Andric   // Don't bloat the -O0 code.
7640b57cec5SDimitry Andric   if (llvm::ConstantInt *numElementsC =
7650b57cec5SDimitry Andric         dyn_cast<llvm::ConstantInt>(numElements)) {
7660b57cec5SDimitry Andric     const llvm::APInt &count = numElementsC->getValue();
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric     bool hasAnyOverflow = false;
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric     // If 'count' was a negative number, it's an overflow.
7710b57cec5SDimitry Andric     if (isSigned && count.isNegative())
7720b57cec5SDimitry Andric       hasAnyOverflow = true;
7730b57cec5SDimitry Andric 
7740b57cec5SDimitry Andric     // We want to do all this arithmetic in size_t.  If numElements is
7750b57cec5SDimitry Andric     // wider than that, check whether it's already too big, and if so,
7760b57cec5SDimitry Andric     // overflow.
7770b57cec5SDimitry Andric     else if (numElementsWidth > sizeWidth &&
77806c3fb27SDimitry Andric              numElementsWidth - sizeWidth > count.countl_zero())
7790b57cec5SDimitry Andric       hasAnyOverflow = true;
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric     // Okay, compute a count at the right width.
7820b57cec5SDimitry Andric     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric     // If there is a brace-initializer, we cannot allocate fewer elements than
7850b57cec5SDimitry Andric     // there are initializers. If we do, that's treated like an overflow.
7860b57cec5SDimitry Andric     if (adjustedCount.ult(minElements))
7870b57cec5SDimitry Andric       hasAnyOverflow = true;
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric     // Scale numElements by that.  This might overflow, but we don't
7900b57cec5SDimitry Andric     // care because it only overflows if allocationSize does, too, and
7910b57cec5SDimitry Andric     // if that overflows then we shouldn't use this.
7920b57cec5SDimitry Andric     numElements = llvm::ConstantInt::get(CGF.SizeTy,
7930b57cec5SDimitry Andric                                          adjustedCount * arraySizeMultiplier);
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric     // Compute the size before cookie, and track whether it overflowed.
7960b57cec5SDimitry Andric     bool overflow;
7970b57cec5SDimitry Andric     llvm::APInt allocationSize
7980b57cec5SDimitry Andric       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
7990b57cec5SDimitry Andric     hasAnyOverflow |= overflow;
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric     // Add in the cookie, and check whether it's overflowed.
8020b57cec5SDimitry Andric     if (cookieSize != 0) {
8030b57cec5SDimitry Andric       // Save the current size without a cookie.  This shouldn't be
8040b57cec5SDimitry Andric       // used if there was overflow.
8050b57cec5SDimitry Andric       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
8080b57cec5SDimitry Andric       hasAnyOverflow |= overflow;
8090b57cec5SDimitry Andric     }
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric     // On overflow, produce a -1 so operator new will fail.
8120b57cec5SDimitry Andric     if (hasAnyOverflow) {
8130b57cec5SDimitry Andric       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
8140b57cec5SDimitry Andric     } else {
8150b57cec5SDimitry Andric       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
8160b57cec5SDimitry Andric     }
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   // Otherwise, we might need to use the overflow intrinsics.
8190b57cec5SDimitry Andric   } else {
8200b57cec5SDimitry Andric     // There are up to five conditions we need to test for:
8210b57cec5SDimitry Andric     // 1) if isSigned, we need to check whether numElements is negative;
8220b57cec5SDimitry Andric     // 2) if numElementsWidth > sizeWidth, we need to check whether
8230b57cec5SDimitry Andric     //   numElements is larger than something representable in size_t;
8240b57cec5SDimitry Andric     // 3) if minElements > 0, we need to check whether numElements is smaller
8250b57cec5SDimitry Andric     //    than that.
8260b57cec5SDimitry Andric     // 4) we need to compute
8270b57cec5SDimitry Andric     //      sizeWithoutCookie := numElements * typeSizeMultiplier
8280b57cec5SDimitry Andric     //    and check whether it overflows; and
8290b57cec5SDimitry Andric     // 5) if we need a cookie, we need to compute
8300b57cec5SDimitry Andric     //      size := sizeWithoutCookie + cookieSize
8310b57cec5SDimitry Andric     //    and check whether it overflows.
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric     llvm::Value *hasOverflow = nullptr;
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric     // If numElementsWidth > sizeWidth, then one way or another, we're
8360b57cec5SDimitry Andric     // going to have to do a comparison for (2), and this happens to
8370b57cec5SDimitry Andric     // take care of (1), too.
8380b57cec5SDimitry Andric     if (numElementsWidth > sizeWidth) {
83906c3fb27SDimitry Andric       llvm::APInt threshold =
84006c3fb27SDimitry Andric           llvm::APInt::getOneBitSet(numElementsWidth, sizeWidth);
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric       llvm::Value *thresholdV
8430b57cec5SDimitry Andric         = llvm::ConstantInt::get(numElementsType, threshold);
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
8460b57cec5SDimitry Andric       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric     // Otherwise, if we're signed, we want to sext up to size_t.
8490b57cec5SDimitry Andric     } else if (isSigned) {
8500b57cec5SDimitry Andric       if (numElementsWidth < sizeWidth)
8510b57cec5SDimitry Andric         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric       // If there's a non-1 type size multiplier, then we can do the
8540b57cec5SDimitry Andric       // signedness check at the same time as we do the multiply
8550b57cec5SDimitry Andric       // because a negative number times anything will cause an
8560b57cec5SDimitry Andric       // unsigned overflow.  Otherwise, we have to do it here. But at least
8570b57cec5SDimitry Andric       // in this case, we can subsume the >= minElements check.
8580b57cec5SDimitry Andric       if (typeSizeMultiplier == 1)
8590b57cec5SDimitry Andric         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
8600b57cec5SDimitry Andric                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric     // Otherwise, zext up to size_t if necessary.
8630b57cec5SDimitry Andric     } else if (numElementsWidth < sizeWidth) {
8640b57cec5SDimitry Andric       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
8650b57cec5SDimitry Andric     }
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric     assert(numElements->getType() == CGF.SizeTy);
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric     if (minElements) {
8700b57cec5SDimitry Andric       // Don't allow allocation of fewer elements than we have initializers.
8710b57cec5SDimitry Andric       if (!hasOverflow) {
8720b57cec5SDimitry Andric         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
8730b57cec5SDimitry Andric                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
8740b57cec5SDimitry Andric       } else if (numElementsWidth > sizeWidth) {
8750b57cec5SDimitry Andric         // The other existing overflow subsumes this check.
8760b57cec5SDimitry Andric         // We do an unsigned comparison, since any signed value < -1 is
8770b57cec5SDimitry Andric         // taken care of either above or below.
8780b57cec5SDimitry Andric         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
8790b57cec5SDimitry Andric                           CGF.Builder.CreateICmpULT(numElements,
8800b57cec5SDimitry Andric                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
8810b57cec5SDimitry Andric       }
8820b57cec5SDimitry Andric     }
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric     size = numElements;
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric     // Multiply by the type size if necessary.  This multiplier
8870b57cec5SDimitry Andric     // includes all the factors for nested arrays.
8880b57cec5SDimitry Andric     //
8890b57cec5SDimitry Andric     // This step also causes numElements to be scaled up by the
8900b57cec5SDimitry Andric     // nested-array factor if necessary.  Overflow on this computation
8910b57cec5SDimitry Andric     // can be ignored because the result shouldn't be used if
8920b57cec5SDimitry Andric     // allocation fails.
8930b57cec5SDimitry Andric     if (typeSizeMultiplier != 1) {
8940b57cec5SDimitry Andric       llvm::Function *umul_with_overflow
8950b57cec5SDimitry Andric         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric       llvm::Value *tsmV =
8980b57cec5SDimitry Andric         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
8990b57cec5SDimitry Andric       llvm::Value *result =
9000b57cec5SDimitry Andric           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
9030b57cec5SDimitry Andric       if (hasOverflow)
9040b57cec5SDimitry Andric         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
9050b57cec5SDimitry Andric       else
9060b57cec5SDimitry Andric         hasOverflow = overflowed;
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric       size = CGF.Builder.CreateExtractValue(result, 0);
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric       // Also scale up numElements by the array size multiplier.
9110b57cec5SDimitry Andric       if (arraySizeMultiplier != 1) {
9120b57cec5SDimitry Andric         // If the base element type size is 1, then we can re-use the
9130b57cec5SDimitry Andric         // multiply we just did.
9140b57cec5SDimitry Andric         if (typeSize.isOne()) {
9150b57cec5SDimitry Andric           assert(arraySizeMultiplier == typeSizeMultiplier);
9160b57cec5SDimitry Andric           numElements = size;
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric         // Otherwise we need a separate multiply.
9190b57cec5SDimitry Andric         } else {
9200b57cec5SDimitry Andric           llvm::Value *asmV =
9210b57cec5SDimitry Andric             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
9220b57cec5SDimitry Andric           numElements = CGF.Builder.CreateMul(numElements, asmV);
9230b57cec5SDimitry Andric         }
9240b57cec5SDimitry Andric       }
9250b57cec5SDimitry Andric     } else {
9260b57cec5SDimitry Andric       // numElements doesn't need to be scaled.
9270b57cec5SDimitry Andric       assert(arraySizeMultiplier == 1);
9280b57cec5SDimitry Andric     }
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric     // Add in the cookie size if necessary.
9310b57cec5SDimitry Andric     if (cookieSize != 0) {
9320b57cec5SDimitry Andric       sizeWithoutCookie = size;
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric       llvm::Function *uadd_with_overflow
9350b57cec5SDimitry Andric         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
9380b57cec5SDimitry Andric       llvm::Value *result =
9390b57cec5SDimitry Andric           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
9420b57cec5SDimitry Andric       if (hasOverflow)
9430b57cec5SDimitry Andric         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
9440b57cec5SDimitry Andric       else
9450b57cec5SDimitry Andric         hasOverflow = overflowed;
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric       size = CGF.Builder.CreateExtractValue(result, 0);
9480b57cec5SDimitry Andric     }
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric     // If we had any possibility of dynamic overflow, make a select to
9510b57cec5SDimitry Andric     // overwrite 'size' with an all-ones value, which should cause
9520b57cec5SDimitry Andric     // operator new to throw.
9530b57cec5SDimitry Andric     if (hasOverflow)
9540b57cec5SDimitry Andric       size = CGF.Builder.CreateSelect(hasOverflow,
9550b57cec5SDimitry Andric                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
9560b57cec5SDimitry Andric                                       size);
9570b57cec5SDimitry Andric   }
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric   if (cookieSize == 0)
9600b57cec5SDimitry Andric     sizeWithoutCookie = size;
9610b57cec5SDimitry Andric   else
9620b57cec5SDimitry Andric     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric   return size;
9650b57cec5SDimitry Andric }
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
9680b57cec5SDimitry Andric                                     QualType AllocType, Address NewPtr,
9690b57cec5SDimitry Andric                                     AggValueSlot::Overlap_t MayOverlap) {
9700b57cec5SDimitry Andric   // FIXME: Refactor with EmitExprAsInit.
9710b57cec5SDimitry Andric   switch (CGF.getEvaluationKind(AllocType)) {
9720b57cec5SDimitry Andric   case TEK_Scalar:
9730b57cec5SDimitry Andric     CGF.EmitScalarInit(Init, nullptr,
9740b57cec5SDimitry Andric                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
9750b57cec5SDimitry Andric     return;
9760b57cec5SDimitry Andric   case TEK_Complex:
9770b57cec5SDimitry Andric     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
9780b57cec5SDimitry Andric                                   /*isInit*/ true);
9790b57cec5SDimitry Andric     return;
9800b57cec5SDimitry Andric   case TEK_Aggregate: {
9810b57cec5SDimitry Andric     AggValueSlot Slot
9820b57cec5SDimitry Andric       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
9830b57cec5SDimitry Andric                               AggValueSlot::IsDestructed,
9840b57cec5SDimitry Andric                               AggValueSlot::DoesNotNeedGCBarriers,
9850b57cec5SDimitry Andric                               AggValueSlot::IsNotAliased,
9860b57cec5SDimitry Andric                               MayOverlap, AggValueSlot::IsNotZeroed,
9870b57cec5SDimitry Andric                               AggValueSlot::IsSanitizerChecked);
9880b57cec5SDimitry Andric     CGF.EmitAggExpr(Init, Slot);
9890b57cec5SDimitry Andric     return;
9900b57cec5SDimitry Andric   }
9910b57cec5SDimitry Andric   }
9920b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
9930b57cec5SDimitry Andric }
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric void CodeGenFunction::EmitNewArrayInitializer(
9960b57cec5SDimitry Andric     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
9970b57cec5SDimitry Andric     Address BeginPtr, llvm::Value *NumElements,
9980b57cec5SDimitry Andric     llvm::Value *AllocSizeWithoutCookie) {
9990b57cec5SDimitry Andric   // If we have a type with trivial initialization and no initializer,
10000b57cec5SDimitry Andric   // there's nothing to do.
10010b57cec5SDimitry Andric   if (!E->hasInitializer())
10020b57cec5SDimitry Andric     return;
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   Address CurPtr = BeginPtr;
10050b57cec5SDimitry Andric 
10060b57cec5SDimitry Andric   unsigned InitListElements = 0;
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric   const Expr *Init = E->getInitializer();
10090b57cec5SDimitry Andric   Address EndOfInit = Address::invalid();
10100b57cec5SDimitry Andric   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
1011*0fca6ea1SDimitry Andric   CleanupDeactivationScope deactivation(*this);
1012*0fca6ea1SDimitry Andric   bool pushedCleanup = false;
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
10150b57cec5SDimitry Andric   CharUnits ElementAlign =
10160b57cec5SDimitry Andric     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric   // Attempt to perform zero-initialization using memset.
10190b57cec5SDimitry Andric   auto TryMemsetInitialization = [&]() -> bool {
10200b57cec5SDimitry Andric     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
10210b57cec5SDimitry Andric     // we can initialize with a memset to -1.
10220b57cec5SDimitry Andric     if (!CGM.getTypes().isZeroInitializable(ElementType))
10230b57cec5SDimitry Andric       return false;
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric     // Optimization: since zero initialization will just set the memory
10260b57cec5SDimitry Andric     // to all zeroes, generate a single memset to do it in one shot.
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric     // Subtract out the size of any elements we've already initialized.
10290b57cec5SDimitry Andric     auto *RemainingSize = AllocSizeWithoutCookie;
10300b57cec5SDimitry Andric     if (InitListElements) {
10310b57cec5SDimitry Andric       // We know this can't overflow; we check this when doing the allocation.
10320b57cec5SDimitry Andric       auto *InitializedSize = llvm::ConstantInt::get(
10330b57cec5SDimitry Andric           RemainingSize->getType(),
10340b57cec5SDimitry Andric           getContext().getTypeSizeInChars(ElementType).getQuantity() *
10350b57cec5SDimitry Andric               InitListElements);
10360b57cec5SDimitry Andric       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
10370b57cec5SDimitry Andric     }
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric     // Create the memset.
10400b57cec5SDimitry Andric     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
10410b57cec5SDimitry Andric     return true;
10420b57cec5SDimitry Andric   };
10430b57cec5SDimitry Andric 
10447a6dacacSDimitry Andric   const InitListExpr *ILE = dyn_cast<InitListExpr>(Init);
10457a6dacacSDimitry Andric   const CXXParenListInitExpr *CPLIE = nullptr;
10467a6dacacSDimitry Andric   const StringLiteral *SL = nullptr;
10477a6dacacSDimitry Andric   const ObjCEncodeExpr *OCEE = nullptr;
10487a6dacacSDimitry Andric   const Expr *IgnoreParen = nullptr;
10497a6dacacSDimitry Andric   if (!ILE) {
10507a6dacacSDimitry Andric     IgnoreParen = Init->IgnoreParenImpCasts();
10517a6dacacSDimitry Andric     CPLIE = dyn_cast<CXXParenListInitExpr>(IgnoreParen);
10527a6dacacSDimitry Andric     SL = dyn_cast<StringLiteral>(IgnoreParen);
10537a6dacacSDimitry Andric     OCEE = dyn_cast<ObjCEncodeExpr>(IgnoreParen);
10547a6dacacSDimitry Andric   }
10557a6dacacSDimitry Andric 
10560b57cec5SDimitry Andric   // If the initializer is an initializer list, first do the explicit elements.
10577a6dacacSDimitry Andric   if (ILE || CPLIE || SL || OCEE) {
10580b57cec5SDimitry Andric     // Initializing from a (braced) string literal is a special case; the init
10590b57cec5SDimitry Andric     // list element does not initialize a (single) array element.
10607a6dacacSDimitry Andric     if ((ILE && ILE->isStringLiteralInit()) || SL || OCEE) {
10617a6dacacSDimitry Andric       if (!ILE)
10627a6dacacSDimitry Andric         Init = IgnoreParen;
10630b57cec5SDimitry Andric       // Initialize the initial portion of length equal to that of the string
10640b57cec5SDimitry Andric       // literal. The allocation must be for at least this much; we emitted a
10650b57cec5SDimitry Andric       // check for that earlier.
10660b57cec5SDimitry Andric       AggValueSlot Slot =
10670b57cec5SDimitry Andric           AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
10680b57cec5SDimitry Andric                                 AggValueSlot::IsDestructed,
10690b57cec5SDimitry Andric                                 AggValueSlot::DoesNotNeedGCBarriers,
10700b57cec5SDimitry Andric                                 AggValueSlot::IsNotAliased,
10710b57cec5SDimitry Andric                                 AggValueSlot::DoesNotOverlap,
10720b57cec5SDimitry Andric                                 AggValueSlot::IsNotZeroed,
10730b57cec5SDimitry Andric                                 AggValueSlot::IsSanitizerChecked);
10747a6dacacSDimitry Andric       EmitAggExpr(ILE ? ILE->getInit(0) : Init, Slot);
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric       // Move past these elements.
10770b57cec5SDimitry Andric       InitListElements =
10787a6dacacSDimitry Andric           cast<ConstantArrayType>(Init->getType()->getAsArrayTypeUnsafe())
1079*0fca6ea1SDimitry Andric               ->getZExtSize();
10800eae32dcSDimitry Andric       CurPtr = Builder.CreateConstInBoundsGEP(
10810eae32dcSDimitry Andric           CurPtr, InitListElements, "string.init.end");
10820b57cec5SDimitry Andric 
10830b57cec5SDimitry Andric       // Zero out the rest, if any remain.
10840b57cec5SDimitry Andric       llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
10850b57cec5SDimitry Andric       if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
10860b57cec5SDimitry Andric         bool OK = TryMemsetInitialization();
10870b57cec5SDimitry Andric         (void)OK;
10880b57cec5SDimitry Andric         assert(OK && "couldn't memset character type?");
10890b57cec5SDimitry Andric       }
10900b57cec5SDimitry Andric       return;
10910b57cec5SDimitry Andric     }
10920b57cec5SDimitry Andric 
10937a6dacacSDimitry Andric     ArrayRef<const Expr *> InitExprs =
10947a6dacacSDimitry Andric         ILE ? ILE->inits() : CPLIE->getInitExprs();
10957a6dacacSDimitry Andric     InitListElements = InitExprs.size();
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric     // If this is a multi-dimensional array new, we will initialize multiple
10980b57cec5SDimitry Andric     // elements with each init list element.
10990b57cec5SDimitry Andric     QualType AllocType = E->getAllocatedType();
11000b57cec5SDimitry Andric     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
11010b57cec5SDimitry Andric             AllocType->getAsArrayTypeUnsafe())) {
11020b57cec5SDimitry Andric       ElementTy = ConvertTypeForMem(AllocType);
110306c3fb27SDimitry Andric       CurPtr = CurPtr.withElementType(ElementTy);
11040b57cec5SDimitry Andric       InitListElements *= getContext().getConstantArrayElementCount(CAT);
11050b57cec5SDimitry Andric     }
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric     // Enter a partial-destruction Cleanup if necessary.
1108*0fca6ea1SDimitry Andric     if (DtorKind) {
1109*0fca6ea1SDimitry Andric       AllocaTrackerRAII AllocaTracker(*this);
11100b57cec5SDimitry Andric       // In principle we could tell the Cleanup where we are more
11110b57cec5SDimitry Andric       // directly, but the control flow can get so varied here that it
11120b57cec5SDimitry Andric       // would actually be quite complex.  Therefore we go through an
11130b57cec5SDimitry Andric       // alloca.
1114*0fca6ea1SDimitry Andric       llvm::Instruction *DominatingIP =
1115*0fca6ea1SDimitry Andric           Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy));
11160b57cec5SDimitry Andric       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
11170b57cec5SDimitry Andric                                    "array.init.end");
1118*0fca6ea1SDimitry Andric       pushIrregularPartialArrayCleanup(BeginPtr.emitRawPointer(*this),
1119*0fca6ea1SDimitry Andric                                        EndOfInit, ElementType, ElementAlign,
11200b57cec5SDimitry Andric                                        getDestroyer(DtorKind));
1121*0fca6ea1SDimitry Andric       cast<EHCleanupScope>(*EHStack.find(EHStack.stable_begin()))
1122*0fca6ea1SDimitry Andric           .AddAuxAllocas(AllocaTracker.Take());
1123*0fca6ea1SDimitry Andric       DeferredDeactivationCleanupStack.push_back(
1124*0fca6ea1SDimitry Andric           {EHStack.stable_begin(), DominatingIP});
1125*0fca6ea1SDimitry Andric       pushedCleanup = true;
11260b57cec5SDimitry Andric     }
11270b57cec5SDimitry Andric 
11280b57cec5SDimitry Andric     CharUnits StartAlign = CurPtr.getAlignment();
11297a6dacacSDimitry Andric     unsigned i = 0;
11307a6dacacSDimitry Andric     for (const Expr *IE : InitExprs) {
11310b57cec5SDimitry Andric       // Tell the cleanup that it needs to destroy up to this
11320b57cec5SDimitry Andric       // element.  TODO: some of these stores can be trivially
11330b57cec5SDimitry Andric       // observed to be unnecessary.
11340b57cec5SDimitry Andric       if (EndOfInit.isValid()) {
1135*0fca6ea1SDimitry Andric         Builder.CreateStore(CurPtr.emitRawPointer(*this), EndOfInit);
11360b57cec5SDimitry Andric       }
11370b57cec5SDimitry Andric       // FIXME: If the last initializer is an incomplete initializer list for
11380b57cec5SDimitry Andric       // an array, and we have an array filler, we can fold together the two
11390b57cec5SDimitry Andric       // initialization loops.
11407a6dacacSDimitry Andric       StoreAnyExprIntoOneUnit(*this, IE, IE->getType(), CurPtr,
11410b57cec5SDimitry Andric                               AggValueSlot::DoesNotOverlap);
1142*0fca6ea1SDimitry Andric       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(),
1143*0fca6ea1SDimitry Andric                                                  CurPtr.emitRawPointer(*this),
1144*0fca6ea1SDimitry Andric                                                  Builder.getSize(1),
1145*0fca6ea1SDimitry Andric                                                  "array.exp.next"),
11461fd87a68SDimitry Andric                        CurPtr.getElementType(),
11477a6dacacSDimitry Andric                        StartAlign.alignmentAtOffset((++i) * ElementSize));
11480b57cec5SDimitry Andric     }
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric     // The remaining elements are filled with the array filler expression.
11517a6dacacSDimitry Andric     Init = ILE ? ILE->getArrayFiller() : CPLIE->getArrayFiller();
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric     // Extract the initializer for the individual array elements by pulling
11540b57cec5SDimitry Andric     // out the array filler from all the nested initializer lists. This avoids
11550b57cec5SDimitry Andric     // generating a nested loop for the initialization.
11560b57cec5SDimitry Andric     while (Init && Init->getType()->isConstantArrayType()) {
11570b57cec5SDimitry Andric       auto *SubILE = dyn_cast<InitListExpr>(Init);
11580b57cec5SDimitry Andric       if (!SubILE)
11590b57cec5SDimitry Andric         break;
11600b57cec5SDimitry Andric       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
11610b57cec5SDimitry Andric       Init = SubILE->getArrayFiller();
11620b57cec5SDimitry Andric     }
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric     // Switch back to initializing one base element at a time.
116506c3fb27SDimitry Andric     CurPtr = CurPtr.withElementType(BeginPtr.getElementType());
11660b57cec5SDimitry Andric   }
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric   // If all elements have already been initialized, skip any further
11690b57cec5SDimitry Andric   // initialization.
11700b57cec5SDimitry Andric   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
11710b57cec5SDimitry Andric   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
11720b57cec5SDimitry Andric     return;
11730b57cec5SDimitry Andric   }
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric   assert(Init && "have trailing elements to initialize but no initializer");
11760b57cec5SDimitry Andric 
11770b57cec5SDimitry Andric   // If this is a constructor call, try to optimize it out, and failing that
11780b57cec5SDimitry Andric   // emit a single loop to initialize all remaining elements.
11790b57cec5SDimitry Andric   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
11800b57cec5SDimitry Andric     CXXConstructorDecl *Ctor = CCE->getConstructor();
11810b57cec5SDimitry Andric     if (Ctor->isTrivial()) {
11820b57cec5SDimitry Andric       // If new expression did not specify value-initialization, then there
11830b57cec5SDimitry Andric       // is no initialization.
11840b57cec5SDimitry Andric       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
11850b57cec5SDimitry Andric         return;
11860b57cec5SDimitry Andric 
11870b57cec5SDimitry Andric       if (TryMemsetInitialization())
11880b57cec5SDimitry Andric         return;
11890b57cec5SDimitry Andric     }
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric     // Store the new Cleanup position for irregular Cleanups.
11920b57cec5SDimitry Andric     //
11930b57cec5SDimitry Andric     // FIXME: Share this cleanup with the constructor call emission rather than
11940b57cec5SDimitry Andric     // having it create a cleanup of its own.
11950b57cec5SDimitry Andric     if (EndOfInit.isValid())
1196*0fca6ea1SDimitry Andric       Builder.CreateStore(CurPtr.emitRawPointer(*this), EndOfInit);
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric     // Emit a constructor call loop to initialize the remaining elements.
11990b57cec5SDimitry Andric     if (InitListElements)
12000b57cec5SDimitry Andric       NumElements = Builder.CreateSub(
12010b57cec5SDimitry Andric           NumElements,
12020b57cec5SDimitry Andric           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
12030b57cec5SDimitry Andric     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
12040b57cec5SDimitry Andric                                /*NewPointerIsChecked*/true,
12050b57cec5SDimitry Andric                                CCE->requiresZeroInitialization());
12060b57cec5SDimitry Andric     return;
12070b57cec5SDimitry Andric   }
12080b57cec5SDimitry Andric 
12090b57cec5SDimitry Andric   // If this is value-initialization, we can usually use memset.
12100b57cec5SDimitry Andric   ImplicitValueInitExpr IVIE(ElementType);
12110b57cec5SDimitry Andric   if (isa<ImplicitValueInitExpr>(Init)) {
12120b57cec5SDimitry Andric     if (TryMemsetInitialization())
12130b57cec5SDimitry Andric       return;
12140b57cec5SDimitry Andric 
12150b57cec5SDimitry Andric     // Switch to an ImplicitValueInitExpr for the element type. This handles
12160b57cec5SDimitry Andric     // only one case: multidimensional array new of pointers to members. In
12170b57cec5SDimitry Andric     // all other cases, we already have an initializer for the array element.
12180b57cec5SDimitry Andric     Init = &IVIE;
12190b57cec5SDimitry Andric   }
12200b57cec5SDimitry Andric 
12210b57cec5SDimitry Andric   // At this point we should have found an initializer for the individual
12220b57cec5SDimitry Andric   // elements of the array.
12230b57cec5SDimitry Andric   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
12240b57cec5SDimitry Andric          "got wrong type of element to initialize");
12250b57cec5SDimitry Andric 
12260b57cec5SDimitry Andric   // If we have an empty initializer list, we can usually use memset.
12270b57cec5SDimitry Andric   if (auto *ILE = dyn_cast<InitListExpr>(Init))
12280b57cec5SDimitry Andric     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
12290b57cec5SDimitry Andric       return;
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric   // If we have a struct whose every field is value-initialized, we can
12320b57cec5SDimitry Andric   // usually use memset.
12330b57cec5SDimitry Andric   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12340b57cec5SDimitry Andric     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
12350b57cec5SDimitry Andric       if (RType->getDecl()->isStruct()) {
12360b57cec5SDimitry Andric         unsigned NumElements = 0;
12370b57cec5SDimitry Andric         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
12380b57cec5SDimitry Andric           NumElements = CXXRD->getNumBases();
12390b57cec5SDimitry Andric         for (auto *Field : RType->getDecl()->fields())
1240*0fca6ea1SDimitry Andric           if (!Field->isUnnamedBitField())
12410b57cec5SDimitry Andric             ++NumElements;
12420b57cec5SDimitry Andric         // FIXME: Recurse into nested InitListExprs.
12430b57cec5SDimitry Andric         if (ILE->getNumInits() == NumElements)
12440b57cec5SDimitry Andric           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
12450b57cec5SDimitry Andric             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
12460b57cec5SDimitry Andric               --NumElements;
12470b57cec5SDimitry Andric         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
12480b57cec5SDimitry Andric           return;
12490b57cec5SDimitry Andric       }
12500b57cec5SDimitry Andric     }
12510b57cec5SDimitry Andric   }
12520b57cec5SDimitry Andric 
12530b57cec5SDimitry Andric   // Create the loop blocks.
12540b57cec5SDimitry Andric   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
12550b57cec5SDimitry Andric   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
12560b57cec5SDimitry Andric   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric   // Find the end of the array, hoisted out of the loop.
1259*0fca6ea1SDimitry Andric   llvm::Value *EndPtr = Builder.CreateInBoundsGEP(
1260*0fca6ea1SDimitry Andric       BeginPtr.getElementType(), BeginPtr.emitRawPointer(*this), NumElements,
1261*0fca6ea1SDimitry Andric       "array.end");
12620b57cec5SDimitry Andric 
12630b57cec5SDimitry Andric   // If the number of elements isn't constant, we have to now check if there is
12640b57cec5SDimitry Andric   // anything left to initialize.
12650b57cec5SDimitry Andric   if (!ConstNum) {
1266*0fca6ea1SDimitry Andric     llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr.emitRawPointer(*this),
1267*0fca6ea1SDimitry Andric                                                 EndPtr, "array.isempty");
12680b57cec5SDimitry Andric     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
12690b57cec5SDimitry Andric   }
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric   // Enter the loop.
12720b57cec5SDimitry Andric   EmitBlock(LoopBB);
12730b57cec5SDimitry Andric 
12740b57cec5SDimitry Andric   // Set up the current-element phi.
12750b57cec5SDimitry Andric   llvm::PHINode *CurPtrPhi =
12760b57cec5SDimitry Andric       Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1277*0fca6ea1SDimitry Andric   CurPtrPhi->addIncoming(CurPtr.emitRawPointer(*this), EntryBB);
12780b57cec5SDimitry Andric 
127981ad6265SDimitry Andric   CurPtr = Address(CurPtrPhi, CurPtr.getElementType(), ElementAlign);
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric   // Store the new Cleanup position for irregular Cleanups.
12820b57cec5SDimitry Andric   if (EndOfInit.isValid())
1283*0fca6ea1SDimitry Andric     Builder.CreateStore(CurPtr.emitRawPointer(*this), EndOfInit);
12840b57cec5SDimitry Andric 
12850b57cec5SDimitry Andric   // Enter a partial-destruction Cleanup if necessary.
1286*0fca6ea1SDimitry Andric   if (!pushedCleanup && needsEHCleanup(DtorKind)) {
1287*0fca6ea1SDimitry Andric     llvm::Instruction *DominatingIP =
1288*0fca6ea1SDimitry Andric         Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy));
1289*0fca6ea1SDimitry Andric     pushRegularPartialArrayCleanup(BeginPtr.emitRawPointer(*this),
1290*0fca6ea1SDimitry Andric                                    CurPtr.emitRawPointer(*this), ElementType,
1291*0fca6ea1SDimitry Andric                                    ElementAlign, getDestroyer(DtorKind));
1292*0fca6ea1SDimitry Andric     DeferredDeactivationCleanupStack.push_back(
1293*0fca6ea1SDimitry Andric         {EHStack.stable_begin(), DominatingIP});
12940b57cec5SDimitry Andric   }
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric   // Emit the initializer into this element.
12970b57cec5SDimitry Andric   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
12980b57cec5SDimitry Andric                           AggValueSlot::DoesNotOverlap);
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric   // Leave the Cleanup if we entered one.
1301*0fca6ea1SDimitry Andric   deactivation.ForceDeactivate();
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric   // Advance to the next element by adjusting the pointer type as necessary.
1304*0fca6ea1SDimitry Andric   llvm::Value *NextPtr = Builder.CreateConstInBoundsGEP1_32(
1305*0fca6ea1SDimitry Andric       ElementTy, CurPtr.emitRawPointer(*this), 1, "array.next");
13060b57cec5SDimitry Andric 
13070b57cec5SDimitry Andric   // Check whether we've gotten to the end of the array and, if so,
13080b57cec5SDimitry Andric   // exit the loop.
13090b57cec5SDimitry Andric   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
13100b57cec5SDimitry Andric   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
13110b57cec5SDimitry Andric   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric   EmitBlock(ContBB);
13140b57cec5SDimitry Andric }
13150b57cec5SDimitry Andric 
13160b57cec5SDimitry Andric static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
13170b57cec5SDimitry Andric                                QualType ElementType, llvm::Type *ElementTy,
13180b57cec5SDimitry Andric                                Address NewPtr, llvm::Value *NumElements,
13190b57cec5SDimitry Andric                                llvm::Value *AllocSizeWithoutCookie) {
13200b57cec5SDimitry Andric   ApplyDebugLocation DL(CGF, E);
13210b57cec5SDimitry Andric   if (E->isArray())
13220b57cec5SDimitry Andric     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
13230b57cec5SDimitry Andric                                 AllocSizeWithoutCookie);
13240b57cec5SDimitry Andric   else if (const Expr *Init = E->getInitializer())
13250b57cec5SDimitry Andric     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,
13260b57cec5SDimitry Andric                             AggValueSlot::DoesNotOverlap);
13270b57cec5SDimitry Andric }
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric /// Emit a call to an operator new or operator delete function, as implicitly
13300b57cec5SDimitry Andric /// created by new-expressions and delete-expressions.
13310b57cec5SDimitry Andric static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
13320b57cec5SDimitry Andric                                 const FunctionDecl *CalleeDecl,
13330b57cec5SDimitry Andric                                 const FunctionProtoType *CalleeType,
13340b57cec5SDimitry Andric                                 const CallArgList &Args) {
13350b57cec5SDimitry Andric   llvm::CallBase *CallOrInvoke;
13360b57cec5SDimitry Andric   llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
13370b57cec5SDimitry Andric   CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));
13380b57cec5SDimitry Andric   RValue RV =
13390b57cec5SDimitry Andric       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
13400b57cec5SDimitry Andric                        Args, CalleeType, /*ChainCall=*/false),
13410b57cec5SDimitry Andric                    Callee, ReturnValueSlot(), Args, &CallOrInvoke);
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric   /// C++1y [expr.new]p10:
13440b57cec5SDimitry Andric   ///   [In a new-expression,] an implementation is allowed to omit a call
13450b57cec5SDimitry Andric   ///   to a replaceable global allocation function.
13460b57cec5SDimitry Andric   ///
13470b57cec5SDimitry Andric   /// We model such elidable calls with the 'builtin' attribute.
13480b57cec5SDimitry Andric   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
13490b57cec5SDimitry Andric   if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
13500b57cec5SDimitry Andric       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1351349cc55cSDimitry Andric     CallOrInvoke->addFnAttr(llvm::Attribute::Builtin);
13520b57cec5SDimitry Andric   }
13530b57cec5SDimitry Andric 
13540b57cec5SDimitry Andric   return RV;
13550b57cec5SDimitry Andric }
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
13580b57cec5SDimitry Andric                                                  const CallExpr *TheCall,
13590b57cec5SDimitry Andric                                                  bool IsDelete) {
13600b57cec5SDimitry Andric   CallArgList Args;
1361e8d8bef9SDimitry Andric   EmitCallArgs(Args, Type, TheCall->arguments());
13620b57cec5SDimitry Andric   // Find the allocation or deallocation function that we're calling.
13630b57cec5SDimitry Andric   ASTContext &Ctx = getContext();
13640b57cec5SDimitry Andric   DeclarationName Name = Ctx.DeclarationNames
13650b57cec5SDimitry Andric       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
13660b57cec5SDimitry Andric 
13670b57cec5SDimitry Andric   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
13680b57cec5SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
13690b57cec5SDimitry Andric       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
13700b57cec5SDimitry Andric         return EmitNewDeleteCall(*this, FD, Type, Args);
13710b57cec5SDimitry Andric   llvm_unreachable("predeclared global operator new/delete is missing");
13720b57cec5SDimitry Andric }
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric namespace {
13750b57cec5SDimitry Andric /// The parameters to pass to a usual operator delete.
13760b57cec5SDimitry Andric struct UsualDeleteParams {
13770b57cec5SDimitry Andric   bool DestroyingDelete = false;
13780b57cec5SDimitry Andric   bool Size = false;
13790b57cec5SDimitry Andric   bool Alignment = false;
13800b57cec5SDimitry Andric };
13810b57cec5SDimitry Andric }
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
13840b57cec5SDimitry Andric   UsualDeleteParams Params;
13850b57cec5SDimitry Andric 
13860b57cec5SDimitry Andric   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
13870b57cec5SDimitry Andric   auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric   // The first argument is always a void*.
13900b57cec5SDimitry Andric   ++AI;
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric   // The next parameter may be a std::destroying_delete_t.
13930b57cec5SDimitry Andric   if (FD->isDestroyingOperatorDelete()) {
13940b57cec5SDimitry Andric     Params.DestroyingDelete = true;
13950b57cec5SDimitry Andric     assert(AI != AE);
13960b57cec5SDimitry Andric     ++AI;
13970b57cec5SDimitry Andric   }
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric   // Figure out what other parameters we should be implicitly passing.
14000b57cec5SDimitry Andric   if (AI != AE && (*AI)->isIntegerType()) {
14010b57cec5SDimitry Andric     Params.Size = true;
14020b57cec5SDimitry Andric     ++AI;
14030b57cec5SDimitry Andric   }
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric   if (AI != AE && (*AI)->isAlignValT()) {
14060b57cec5SDimitry Andric     Params.Alignment = true;
14070b57cec5SDimitry Andric     ++AI;
14080b57cec5SDimitry Andric   }
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric   assert(AI == AE && "unexpected usual deallocation function parameter");
14110b57cec5SDimitry Andric   return Params;
14120b57cec5SDimitry Andric }
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric namespace {
14150b57cec5SDimitry Andric   /// A cleanup to call the given 'operator delete' function upon abnormal
14160b57cec5SDimitry Andric   /// exit from a new expression. Templated on a traits type that deals with
14170b57cec5SDimitry Andric   /// ensuring that the arguments dominate the cleanup if necessary.
14180b57cec5SDimitry Andric   template<typename Traits>
14190b57cec5SDimitry Andric   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
14200b57cec5SDimitry Andric     /// Type used to hold llvm::Value*s.
14210b57cec5SDimitry Andric     typedef typename Traits::ValueTy ValueTy;
14220b57cec5SDimitry Andric     /// Type used to hold RValues.
14230b57cec5SDimitry Andric     typedef typename Traits::RValueTy RValueTy;
14240b57cec5SDimitry Andric     struct PlacementArg {
14250b57cec5SDimitry Andric       RValueTy ArgValue;
14260b57cec5SDimitry Andric       QualType ArgType;
14270b57cec5SDimitry Andric     };
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric     unsigned NumPlacementArgs : 31;
1430*0fca6ea1SDimitry Andric     LLVM_PREFERRED_TYPE(bool)
14310b57cec5SDimitry Andric     unsigned PassAlignmentToPlacementDelete : 1;
14320b57cec5SDimitry Andric     const FunctionDecl *OperatorDelete;
14330b57cec5SDimitry Andric     ValueTy Ptr;
14340b57cec5SDimitry Andric     ValueTy AllocSize;
14350b57cec5SDimitry Andric     CharUnits AllocAlign;
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric     PlacementArg *getPlacementArgs() {
14380b57cec5SDimitry Andric       return reinterpret_cast<PlacementArg *>(this + 1);
14390b57cec5SDimitry Andric     }
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   public:
14420b57cec5SDimitry Andric     static size_t getExtraSize(size_t NumPlacementArgs) {
14430b57cec5SDimitry Andric       return NumPlacementArgs * sizeof(PlacementArg);
14440b57cec5SDimitry Andric     }
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric     CallDeleteDuringNew(size_t NumPlacementArgs,
14470b57cec5SDimitry Andric                         const FunctionDecl *OperatorDelete, ValueTy Ptr,
14480b57cec5SDimitry Andric                         ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
14490b57cec5SDimitry Andric                         CharUnits AllocAlign)
14500b57cec5SDimitry Andric       : NumPlacementArgs(NumPlacementArgs),
14510b57cec5SDimitry Andric         PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
14520b57cec5SDimitry Andric         OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
14530b57cec5SDimitry Andric         AllocAlign(AllocAlign) {}
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric     void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
14560b57cec5SDimitry Andric       assert(I < NumPlacementArgs && "index out of range");
14570b57cec5SDimitry Andric       getPlacementArgs()[I] = {Arg, Type};
14580b57cec5SDimitry Andric     }
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
1461480093f4SDimitry Andric       const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();
14620b57cec5SDimitry Andric       CallArgList DeleteArgs;
14630b57cec5SDimitry Andric 
14640b57cec5SDimitry Andric       // The first argument is always a void* (or C* for a destroying operator
14650b57cec5SDimitry Andric       // delete for class type C).
14660b57cec5SDimitry Andric       DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric       // Figure out what other parameters we should be implicitly passing.
14690b57cec5SDimitry Andric       UsualDeleteParams Params;
14700b57cec5SDimitry Andric       if (NumPlacementArgs) {
14710b57cec5SDimitry Andric         // A placement deallocation function is implicitly passed an alignment
14720b57cec5SDimitry Andric         // if the placement allocation function was, but is never passed a size.
14730b57cec5SDimitry Andric         Params.Alignment = PassAlignmentToPlacementDelete;
14740b57cec5SDimitry Andric       } else {
14750b57cec5SDimitry Andric         // For a non-placement new-expression, 'operator delete' can take a
14760b57cec5SDimitry Andric         // size and/or an alignment if it has the right parameters.
14770b57cec5SDimitry Andric         Params = getUsualDeleteParams(OperatorDelete);
14780b57cec5SDimitry Andric       }
14790b57cec5SDimitry Andric 
14800b57cec5SDimitry Andric       assert(!Params.DestroyingDelete &&
14810b57cec5SDimitry Andric              "should not call destroying delete in a new-expression");
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric       // The second argument can be a std::size_t (for non-placement delete).
14840b57cec5SDimitry Andric       if (Params.Size)
14850b57cec5SDimitry Andric         DeleteArgs.add(Traits::get(CGF, AllocSize),
14860b57cec5SDimitry Andric                        CGF.getContext().getSizeType());
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric       // The next (second or third) argument can be a std::align_val_t, which
14890b57cec5SDimitry Andric       // is an enum whose underlying type is std::size_t.
14900b57cec5SDimitry Andric       // FIXME: Use the right type as the parameter type. Note that in a call
14910b57cec5SDimitry Andric       // to operator delete(size_t, ...), we may not have it available.
14920b57cec5SDimitry Andric       if (Params.Alignment)
14930b57cec5SDimitry Andric         DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
14940b57cec5SDimitry Andric                            CGF.SizeTy, AllocAlign.getQuantity())),
14950b57cec5SDimitry Andric                        CGF.getContext().getSizeType());
14960b57cec5SDimitry Andric 
14970b57cec5SDimitry Andric       // Pass the rest of the arguments, which must match exactly.
14980b57cec5SDimitry Andric       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
14990b57cec5SDimitry Andric         auto Arg = getPlacementArgs()[I];
15000b57cec5SDimitry Andric         DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
15010b57cec5SDimitry Andric       }
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric       // Call 'operator delete'.
15040b57cec5SDimitry Andric       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
15050b57cec5SDimitry Andric     }
15060b57cec5SDimitry Andric   };
15070b57cec5SDimitry Andric }
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric /// Enter a cleanup to call 'operator delete' if the initializer in a
15100b57cec5SDimitry Andric /// new-expression throws.
15110b57cec5SDimitry Andric static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
15120b57cec5SDimitry Andric                                   const CXXNewExpr *E,
15130b57cec5SDimitry Andric                                   Address NewPtr,
15140b57cec5SDimitry Andric                                   llvm::Value *AllocSize,
15150b57cec5SDimitry Andric                                   CharUnits AllocAlign,
15160b57cec5SDimitry Andric                                   const CallArgList &NewArgs) {
15170b57cec5SDimitry Andric   unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
15180b57cec5SDimitry Andric 
15190b57cec5SDimitry Andric   // If we're not inside a conditional branch, then the cleanup will
15200b57cec5SDimitry Andric   // dominate and we can do the easier (and more efficient) thing.
15210b57cec5SDimitry Andric   if (!CGF.isInConditionalBranch()) {
15220b57cec5SDimitry Andric     struct DirectCleanupTraits {
15230b57cec5SDimitry Andric       typedef llvm::Value *ValueTy;
15240b57cec5SDimitry Andric       typedef RValue RValueTy;
15250b57cec5SDimitry Andric       static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
15260b57cec5SDimitry Andric       static RValue get(CodeGenFunction &, RValueTy V) { return V; }
15270b57cec5SDimitry Andric     };
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric     typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
15300b57cec5SDimitry Andric 
1531*0fca6ea1SDimitry Andric     DirectCleanup *Cleanup = CGF.EHStack.pushCleanupWithExtra<DirectCleanup>(
1532*0fca6ea1SDimitry Andric         EHCleanup, E->getNumPlacementArgs(), E->getOperatorDelete(),
1533*0fca6ea1SDimitry Andric         NewPtr.emitRawPointer(CGF), AllocSize, E->passAlignment(), AllocAlign);
15340b57cec5SDimitry Andric     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
15350b57cec5SDimitry Andric       auto &Arg = NewArgs[I + NumNonPlacementArgs];
15360b57cec5SDimitry Andric       Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);
15370b57cec5SDimitry Andric     }
15380b57cec5SDimitry Andric 
15390b57cec5SDimitry Andric     return;
15400b57cec5SDimitry Andric   }
15410b57cec5SDimitry Andric 
15420b57cec5SDimitry Andric   // Otherwise, we need to save all this stuff.
15430b57cec5SDimitry Andric   DominatingValue<RValue>::saved_type SavedNewPtr =
1544*0fca6ea1SDimitry Andric       DominatingValue<RValue>::save(CGF, RValue::get(NewPtr, CGF));
15450b57cec5SDimitry Andric   DominatingValue<RValue>::saved_type SavedAllocSize =
15460b57cec5SDimitry Andric     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
15470b57cec5SDimitry Andric 
15480b57cec5SDimitry Andric   struct ConditionalCleanupTraits {
15490b57cec5SDimitry Andric     typedef DominatingValue<RValue>::saved_type ValueTy;
15500b57cec5SDimitry Andric     typedef DominatingValue<RValue>::saved_type RValueTy;
15510b57cec5SDimitry Andric     static RValue get(CodeGenFunction &CGF, ValueTy V) {
15520b57cec5SDimitry Andric       return V.restore(CGF);
15530b57cec5SDimitry Andric     }
15540b57cec5SDimitry Andric   };
15550b57cec5SDimitry Andric   typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric   ConditionalCleanup *Cleanup = CGF.EHStack
15580b57cec5SDimitry Andric     .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
15590b57cec5SDimitry Andric                                               E->getNumPlacementArgs(),
15600b57cec5SDimitry Andric                                               E->getOperatorDelete(),
15610b57cec5SDimitry Andric                                               SavedNewPtr,
15620b57cec5SDimitry Andric                                               SavedAllocSize,
15630b57cec5SDimitry Andric                                               E->passAlignment(),
15640b57cec5SDimitry Andric                                               AllocAlign);
15650b57cec5SDimitry Andric   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
15660b57cec5SDimitry Andric     auto &Arg = NewArgs[I + NumNonPlacementArgs];
15670b57cec5SDimitry Andric     Cleanup->setPlacementArg(
15680b57cec5SDimitry Andric         I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);
15690b57cec5SDimitry Andric   }
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric   CGF.initFullExprCleanup();
15720b57cec5SDimitry Andric }
15730b57cec5SDimitry Andric 
15740b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
15750b57cec5SDimitry Andric   // The element type being allocated.
15760b57cec5SDimitry Andric   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric   // 1. Build a call to the allocation function.
15790b57cec5SDimitry Andric   FunctionDecl *allocator = E->getOperatorNew();
15800b57cec5SDimitry Andric 
15817a6dacacSDimitry Andric   // If there is a brace-initializer or C++20 parenthesized initializer, cannot
15827a6dacacSDimitry Andric   // allocate fewer elements than inits.
15830b57cec5SDimitry Andric   unsigned minElements = 0;
15840b57cec5SDimitry Andric   if (E->isArray() && E->hasInitializer()) {
15857a6dacacSDimitry Andric     const Expr *Init = E->getInitializer();
15867a6dacacSDimitry Andric     const InitListExpr *ILE = dyn_cast<InitListExpr>(Init);
15877a6dacacSDimitry Andric     const CXXParenListInitExpr *CPLIE = dyn_cast<CXXParenListInitExpr>(Init);
15887a6dacacSDimitry Andric     const Expr *IgnoreParen = Init->IgnoreParenImpCasts();
15897a6dacacSDimitry Andric     if ((ILE && ILE->isStringLiteralInit()) ||
15907a6dacacSDimitry Andric         isa<StringLiteral>(IgnoreParen) || isa<ObjCEncodeExpr>(IgnoreParen)) {
15910b57cec5SDimitry Andric       minElements =
15927a6dacacSDimitry Andric           cast<ConstantArrayType>(Init->getType()->getAsArrayTypeUnsafe())
1593*0fca6ea1SDimitry Andric               ->getZExtSize();
15947a6dacacSDimitry Andric     } else if (ILE || CPLIE) {
15957a6dacacSDimitry Andric       minElements = ILE ? ILE->getNumInits() : CPLIE->getInitExprs().size();
15967a6dacacSDimitry Andric     }
15970b57cec5SDimitry Andric   }
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric   llvm::Value *numElements = nullptr;
16000b57cec5SDimitry Andric   llvm::Value *allocSizeWithoutCookie = nullptr;
16010b57cec5SDimitry Andric   llvm::Value *allocSize =
16020b57cec5SDimitry Andric     EmitCXXNewAllocSize(*this, E, minElements, numElements,
16030b57cec5SDimitry Andric                         allocSizeWithoutCookie);
16042a66634dSDimitry Andric   CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
16050b57cec5SDimitry Andric 
16060b57cec5SDimitry Andric   // Emit the allocation call.  If the allocator is a global placement
16070b57cec5SDimitry Andric   // operator, just "inline" it directly.
16080b57cec5SDimitry Andric   Address allocation = Address::invalid();
16090b57cec5SDimitry Andric   CallArgList allocatorArgs;
16100b57cec5SDimitry Andric   if (allocator->isReservedGlobalPlacementOperator()) {
16110b57cec5SDimitry Andric     assert(E->getNumPlacementArgs() == 1);
16120b57cec5SDimitry Andric     const Expr *arg = *E->placement_arguments().begin();
16130b57cec5SDimitry Andric 
16140b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
16150b57cec5SDimitry Andric     allocation = EmitPointerWithAlignment(arg, &BaseInfo);
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric     // The pointer expression will, in many cases, be an opaque void*.
16180b57cec5SDimitry Andric     // In these cases, discard the computed alignment and use the
16190b57cec5SDimitry Andric     // formal alignment of the allocated type.
16200b57cec5SDimitry Andric     if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1621*0fca6ea1SDimitry Andric       allocation.setAlignment(allocAlign);
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric     // Set up allocatorArgs for the call to operator delete if it's not
16240b57cec5SDimitry Andric     // the reserved global operator.
16250b57cec5SDimitry Andric     if (E->getOperatorDelete() &&
16260b57cec5SDimitry Andric         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
16270b57cec5SDimitry Andric       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1628*0fca6ea1SDimitry Andric       allocatorArgs.add(RValue::get(allocation, *this), arg->getType());
16290b57cec5SDimitry Andric     }
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric   } else {
16320b57cec5SDimitry Andric     const FunctionProtoType *allocatorType =
16330b57cec5SDimitry Andric       allocator->getType()->castAs<FunctionProtoType>();
16340b57cec5SDimitry Andric     unsigned ParamsToSkip = 0;
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric     // The allocation size is the first argument.
16370b57cec5SDimitry Andric     QualType sizeType = getContext().getSizeType();
16380b57cec5SDimitry Andric     allocatorArgs.add(RValue::get(allocSize), sizeType);
16390b57cec5SDimitry Andric     ++ParamsToSkip;
16400b57cec5SDimitry Andric 
16410b57cec5SDimitry Andric     if (allocSize != allocSizeWithoutCookie) {
16420b57cec5SDimitry Andric       CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
16430b57cec5SDimitry Andric       allocAlign = std::max(allocAlign, cookieAlign);
16440b57cec5SDimitry Andric     }
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric     // The allocation alignment may be passed as the second argument.
16470b57cec5SDimitry Andric     if (E->passAlignment()) {
16480b57cec5SDimitry Andric       QualType AlignValT = sizeType;
16490b57cec5SDimitry Andric       if (allocatorType->getNumParams() > 1) {
16500b57cec5SDimitry Andric         AlignValT = allocatorType->getParamType(1);
16510b57cec5SDimitry Andric         assert(getContext().hasSameUnqualifiedType(
16520b57cec5SDimitry Andric                    AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
16530b57cec5SDimitry Andric                    sizeType) &&
16540b57cec5SDimitry Andric                "wrong type for alignment parameter");
16550b57cec5SDimitry Andric         ++ParamsToSkip;
16560b57cec5SDimitry Andric       } else {
16570b57cec5SDimitry Andric         // Corner case, passing alignment to 'operator new(size_t, ...)'.
16580b57cec5SDimitry Andric         assert(allocator->isVariadic() && "can't pass alignment to allocator");
16590b57cec5SDimitry Andric       }
16600b57cec5SDimitry Andric       allocatorArgs.add(
16610b57cec5SDimitry Andric           RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
16620b57cec5SDimitry Andric           AlignValT);
16630b57cec5SDimitry Andric     }
16640b57cec5SDimitry Andric 
16650b57cec5SDimitry Andric     // FIXME: Why do we not pass a CalleeDecl here?
16660b57cec5SDimitry Andric     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
16670b57cec5SDimitry Andric                  /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric     RValue RV =
16700b57cec5SDimitry Andric       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
16710b57cec5SDimitry Andric 
16725ffd83dbSDimitry Andric     // Set !heapallocsite metadata on the call to operator new.
16735ffd83dbSDimitry Andric     if (getDebugInfo())
16745ffd83dbSDimitry Andric       if (auto *newCall = dyn_cast<llvm::CallBase>(RV.getScalarVal()))
16755ffd83dbSDimitry Andric         getDebugInfo()->addHeapAllocSiteMetadata(newCall, allocType,
16765ffd83dbSDimitry Andric                                                  E->getExprLoc());
16775ffd83dbSDimitry Andric 
16780b57cec5SDimitry Andric     // If this was a call to a global replaceable allocation function that does
16790b57cec5SDimitry Andric     // not take an alignment argument, the allocator is known to produce
16800b57cec5SDimitry Andric     // storage that's suitably aligned for any object that fits, up to a known
16810b57cec5SDimitry Andric     // threshold. Otherwise assume it's suitably aligned for the allocated type.
16820b57cec5SDimitry Andric     CharUnits allocationAlign = allocAlign;
16830b57cec5SDimitry Andric     if (!E->passAlignment() &&
16840b57cec5SDimitry Andric         allocator->isReplaceableGlobalAllocationFunction()) {
168506c3fb27SDimitry Andric       unsigned AllocatorAlign = llvm::bit_floor(std::min<uint64_t>(
16860b57cec5SDimitry Andric           Target.getNewAlign(), getContext().getTypeSize(allocType)));
16870b57cec5SDimitry Andric       allocationAlign = std::max(
16880b57cec5SDimitry Andric           allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
16890b57cec5SDimitry Andric     }
16900b57cec5SDimitry Andric 
16910eae32dcSDimitry Andric     allocation = Address(RV.getScalarVal(), Int8Ty, allocationAlign);
16920b57cec5SDimitry Andric   }
16930b57cec5SDimitry Andric 
16940b57cec5SDimitry Andric   // Emit a null check on the allocation result if the allocation
16950b57cec5SDimitry Andric   // function is allowed to return null (because it has a non-throwing
16960b57cec5SDimitry Andric   // exception spec or is the reserved placement new) and we have an
16970b57cec5SDimitry Andric   // interesting initializer will be running sanitizers on the initialization.
16980b57cec5SDimitry Andric   bool nullCheck = E->shouldNullCheckAllocation() &&
16990b57cec5SDimitry Andric                    (!allocType.isPODType(getContext()) || E->hasInitializer() ||
17000b57cec5SDimitry Andric                     sanitizePerformTypeCheck());
17010b57cec5SDimitry Andric 
17020b57cec5SDimitry Andric   llvm::BasicBlock *nullCheckBB = nullptr;
17030b57cec5SDimitry Andric   llvm::BasicBlock *contBB = nullptr;
17040b57cec5SDimitry Andric 
17050b57cec5SDimitry Andric   // The null-check means that the initializer is conditionally
17060b57cec5SDimitry Andric   // evaluated.
17070b57cec5SDimitry Andric   ConditionalEvaluation conditional(*this);
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   if (nullCheck) {
17100b57cec5SDimitry Andric     conditional.begin(*this);
17110b57cec5SDimitry Andric 
17120b57cec5SDimitry Andric     nullCheckBB = Builder.GetInsertBlock();
17130b57cec5SDimitry Andric     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
17140b57cec5SDimitry Andric     contBB = createBasicBlock("new.cont");
17150b57cec5SDimitry Andric 
1716*0fca6ea1SDimitry Andric     llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
17170b57cec5SDimitry Andric     Builder.CreateCondBr(isNull, contBB, notNullBB);
17180b57cec5SDimitry Andric     EmitBlock(notNullBB);
17190b57cec5SDimitry Andric   }
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric   // If there's an operator delete, enter a cleanup to call it if an
17220b57cec5SDimitry Andric   // exception is thrown.
17230b57cec5SDimitry Andric   EHScopeStack::stable_iterator operatorDeleteCleanup;
17240b57cec5SDimitry Andric   llvm::Instruction *cleanupDominator = nullptr;
17250b57cec5SDimitry Andric   if (E->getOperatorDelete() &&
17260b57cec5SDimitry Andric       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
17270b57cec5SDimitry Andric     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
17280b57cec5SDimitry Andric                           allocatorArgs);
17290b57cec5SDimitry Andric     operatorDeleteCleanup = EHStack.stable_begin();
17300b57cec5SDimitry Andric     cleanupDominator = Builder.CreateUnreachable();
17310b57cec5SDimitry Andric   }
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric   assert((allocSize == allocSizeWithoutCookie) ==
17340b57cec5SDimitry Andric          CalculateCookiePadding(*this, E).isZero());
17350b57cec5SDimitry Andric   if (allocSize != allocSizeWithoutCookie) {
17360b57cec5SDimitry Andric     assert(E->isArray());
17370b57cec5SDimitry Andric     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
17380b57cec5SDimitry Andric                                                        numElements,
17390b57cec5SDimitry Andric                                                        E, allocType);
17400b57cec5SDimitry Andric   }
17410b57cec5SDimitry Andric 
17420b57cec5SDimitry Andric   llvm::Type *elementTy = ConvertTypeForMem(allocType);
174306c3fb27SDimitry Andric   Address result = allocation.withElementType(elementTy);
17440b57cec5SDimitry Andric 
17450b57cec5SDimitry Andric   // Passing pointer through launder.invariant.group to avoid propagation of
17460b57cec5SDimitry Andric   // vptrs information which may be included in previous type.
17470b57cec5SDimitry Andric   // To not break LTO with different optimizations levels, we do it regardless
17480b57cec5SDimitry Andric   // of optimization level.
17490b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().StrictVTablePointers &&
17500b57cec5SDimitry Andric       allocator->isReservedGlobalPlacementOperator())
17510eae32dcSDimitry Andric     result = Builder.CreateLaunderInvariantGroup(result);
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric   // Emit sanitizer checks for pointer value now, so that in the case of an
17540b57cec5SDimitry Andric   // array it was checked only once and not at each constructor call. We may
17550b57cec5SDimitry Andric   // have already checked that the pointer is non-null.
17560b57cec5SDimitry Andric   // FIXME: If we have an array cookie and a potentially-throwing allocator,
17570b57cec5SDimitry Andric   // we'll null check the wrong pointer here.
17580b57cec5SDimitry Andric   SanitizerSet SkippedChecks;
17590b57cec5SDimitry Andric   SkippedChecks.set(SanitizerKind::Null, nullCheck);
17600b57cec5SDimitry Andric   EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,
17610b57cec5SDimitry Andric                 E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1762*0fca6ea1SDimitry Andric                 result, allocType, result.getAlignment(), SkippedChecks,
1763*0fca6ea1SDimitry Andric                 numElements);
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
17660b57cec5SDimitry Andric                      allocSizeWithoutCookie);
1767*0fca6ea1SDimitry Andric   llvm::Value *resultPtr = result.emitRawPointer(*this);
17680b57cec5SDimitry Andric   if (E->isArray()) {
17690b57cec5SDimitry Andric     // NewPtr is a pointer to the base element type.  If we're
17700b57cec5SDimitry Andric     // allocating an array of arrays, we'll need to cast back to the
17710b57cec5SDimitry Andric     // array pointer type.
17720b57cec5SDimitry Andric     llvm::Type *resultType = ConvertTypeForMem(E->getType());
177381ad6265SDimitry Andric     if (resultPtr->getType() != resultType)
177481ad6265SDimitry Andric       resultPtr = Builder.CreateBitCast(resultPtr, resultType);
17750b57cec5SDimitry Andric   }
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric   // Deactivate the 'operator delete' cleanup if we finished
17780b57cec5SDimitry Andric   // initialization.
17790b57cec5SDimitry Andric   if (operatorDeleteCleanup.isValid()) {
17800b57cec5SDimitry Andric     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
17810b57cec5SDimitry Andric     cleanupDominator->eraseFromParent();
17820b57cec5SDimitry Andric   }
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric   if (nullCheck) {
17850b57cec5SDimitry Andric     conditional.end(*this);
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
17880b57cec5SDimitry Andric     EmitBlock(contBB);
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
17910b57cec5SDimitry Andric     PHI->addIncoming(resultPtr, notNullBB);
17920b57cec5SDimitry Andric     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
17930b57cec5SDimitry Andric                      nullCheckBB);
17940b57cec5SDimitry Andric 
17950b57cec5SDimitry Andric     resultPtr = PHI;
17960b57cec5SDimitry Andric   }
17970b57cec5SDimitry Andric 
17980b57cec5SDimitry Andric   return resultPtr;
17990b57cec5SDimitry Andric }
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
18020b57cec5SDimitry Andric                                      llvm::Value *Ptr, QualType DeleteTy,
18030b57cec5SDimitry Andric                                      llvm::Value *NumElements,
18040b57cec5SDimitry Andric                                      CharUnits CookieSize) {
18050b57cec5SDimitry Andric   assert((!NumElements && CookieSize.isZero()) ||
18060b57cec5SDimitry Andric          DeleteFD->getOverloadedOperator() == OO_Array_Delete);
18070b57cec5SDimitry Andric 
1808480093f4SDimitry Andric   const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>();
18090b57cec5SDimitry Andric   CallArgList DeleteArgs;
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric   auto Params = getUsualDeleteParams(DeleteFD);
18120b57cec5SDimitry Andric   auto ParamTypeIt = DeleteFTy->param_type_begin();
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   // Pass the pointer itself.
18150b57cec5SDimitry Andric   QualType ArgTy = *ParamTypeIt++;
18160b57cec5SDimitry Andric   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
18170b57cec5SDimitry Andric   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   // Pass the std::destroying_delete tag if present.
1820e8d8bef9SDimitry Andric   llvm::AllocaInst *DestroyingDeleteTag = nullptr;
18210b57cec5SDimitry Andric   if (Params.DestroyingDelete) {
18220b57cec5SDimitry Andric     QualType DDTag = *ParamTypeIt++;
1823e8d8bef9SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(DDTag);
1824e8d8bef9SDimitry Andric     CharUnits Align = CGM.getNaturalTypeAlignment(DDTag);
1825e8d8bef9SDimitry Andric     DestroyingDeleteTag = CreateTempAlloca(Ty, "destroying.delete.tag");
1826e8d8bef9SDimitry Andric     DestroyingDeleteTag->setAlignment(Align.getAsAlign());
182781ad6265SDimitry Andric     DeleteArgs.add(
182881ad6265SDimitry Andric         RValue::getAggregate(Address(DestroyingDeleteTag, Ty, Align)), DDTag);
18290b57cec5SDimitry Andric   }
18300b57cec5SDimitry Andric 
18310b57cec5SDimitry Andric   // Pass the size if the delete function has a size_t parameter.
18320b57cec5SDimitry Andric   if (Params.Size) {
18330b57cec5SDimitry Andric     QualType SizeType = *ParamTypeIt++;
18340b57cec5SDimitry Andric     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
18350b57cec5SDimitry Andric     llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
18360b57cec5SDimitry Andric                                                DeleteTypeSize.getQuantity());
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric     // For array new, multiply by the number of elements.
18390b57cec5SDimitry Andric     if (NumElements)
18400b57cec5SDimitry Andric       Size = Builder.CreateMul(Size, NumElements);
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric     // If there is a cookie, add the cookie size.
18430b57cec5SDimitry Andric     if (!CookieSize.isZero())
18440b57cec5SDimitry Andric       Size = Builder.CreateAdd(
18450b57cec5SDimitry Andric           Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
18460b57cec5SDimitry Andric 
18470b57cec5SDimitry Andric     DeleteArgs.add(RValue::get(Size), SizeType);
18480b57cec5SDimitry Andric   }
18490b57cec5SDimitry Andric 
18500b57cec5SDimitry Andric   // Pass the alignment if the delete function has an align_val_t parameter.
18510b57cec5SDimitry Andric   if (Params.Alignment) {
18520b57cec5SDimitry Andric     QualType AlignValType = *ParamTypeIt++;
1853e8d8bef9SDimitry Andric     CharUnits DeleteTypeAlign =
1854e8d8bef9SDimitry Andric         getContext().toCharUnitsFromBits(getContext().getTypeAlignIfKnown(
1855e8d8bef9SDimitry Andric             DeleteTy, true /* NeedsPreferredAlignment */));
18560b57cec5SDimitry Andric     llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
18570b57cec5SDimitry Andric                                                 DeleteTypeAlign.getQuantity());
18580b57cec5SDimitry Andric     DeleteArgs.add(RValue::get(Align), AlignValType);
18590b57cec5SDimitry Andric   }
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric   assert(ParamTypeIt == DeleteFTy->param_type_end() &&
18620b57cec5SDimitry Andric          "unknown parameter to usual delete function");
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric   // Emit the call to delete.
18650b57cec5SDimitry Andric   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1866e8d8bef9SDimitry Andric 
1867e8d8bef9SDimitry Andric   // If call argument lowering didn't use the destroying_delete_t alloca,
1868e8d8bef9SDimitry Andric   // remove it again.
1869e8d8bef9SDimitry Andric   if (DestroyingDeleteTag && DestroyingDeleteTag->use_empty())
1870e8d8bef9SDimitry Andric     DestroyingDeleteTag->eraseFromParent();
18710b57cec5SDimitry Andric }
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric namespace {
18740b57cec5SDimitry Andric   /// Calls the given 'operator delete' on a single object.
18750b57cec5SDimitry Andric   struct CallObjectDelete final : EHScopeStack::Cleanup {
18760b57cec5SDimitry Andric     llvm::Value *Ptr;
18770b57cec5SDimitry Andric     const FunctionDecl *OperatorDelete;
18780b57cec5SDimitry Andric     QualType ElementType;
18790b57cec5SDimitry Andric 
18800b57cec5SDimitry Andric     CallObjectDelete(llvm::Value *Ptr,
18810b57cec5SDimitry Andric                      const FunctionDecl *OperatorDelete,
18820b57cec5SDimitry Andric                      QualType ElementType)
18830b57cec5SDimitry Andric       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
18840b57cec5SDimitry Andric 
18850b57cec5SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
18860b57cec5SDimitry Andric       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
18870b57cec5SDimitry Andric     }
18880b57cec5SDimitry Andric   };
18890b57cec5SDimitry Andric }
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric void
18920b57cec5SDimitry Andric CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
18930b57cec5SDimitry Andric                                              llvm::Value *CompletePtr,
18940b57cec5SDimitry Andric                                              QualType ElementType) {
18950b57cec5SDimitry Andric   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
18960b57cec5SDimitry Andric                                         OperatorDelete, ElementType);
18970b57cec5SDimitry Andric }
18980b57cec5SDimitry Andric 
18990b57cec5SDimitry Andric /// Emit the code for deleting a single object with a destroying operator
19000b57cec5SDimitry Andric /// delete. If the element type has a non-virtual destructor, Ptr has already
19010b57cec5SDimitry Andric /// been converted to the type of the parameter of 'operator delete'. Otherwise
19020b57cec5SDimitry Andric /// Ptr points to an object of the static type.
19030b57cec5SDimitry Andric static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
19040b57cec5SDimitry Andric                                        const CXXDeleteExpr *DE, Address Ptr,
19050b57cec5SDimitry Andric                                        QualType ElementType) {
19060b57cec5SDimitry Andric   auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
19070b57cec5SDimitry Andric   if (Dtor && Dtor->isVirtual())
19080b57cec5SDimitry Andric     CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
19090b57cec5SDimitry Andric                                                 Dtor);
19100b57cec5SDimitry Andric   else
1911*0fca6ea1SDimitry Andric     CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.emitRawPointer(CGF),
1912*0fca6ea1SDimitry Andric                        ElementType);
19130b57cec5SDimitry Andric }
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric /// Emit the code for deleting a single object.
19165ffd83dbSDimitry Andric /// \return \c true if we started emitting UnconditionalDeleteBlock, \c false
19175ffd83dbSDimitry Andric /// if not.
19185ffd83dbSDimitry Andric static bool EmitObjectDelete(CodeGenFunction &CGF,
19190b57cec5SDimitry Andric                              const CXXDeleteExpr *DE,
19200b57cec5SDimitry Andric                              Address Ptr,
19215ffd83dbSDimitry Andric                              QualType ElementType,
19225ffd83dbSDimitry Andric                              llvm::BasicBlock *UnconditionalDeleteBlock) {
19230b57cec5SDimitry Andric   // C++11 [expr.delete]p3:
19240b57cec5SDimitry Andric   //   If the static type of the object to be deleted is different from its
19250b57cec5SDimitry Andric   //   dynamic type, the static type shall be a base class of the dynamic type
19260b57cec5SDimitry Andric   //   of the object to be deleted and the static type shall have a virtual
19270b57cec5SDimitry Andric   //   destructor or the behavior is undefined.
1928*0fca6ea1SDimitry Andric   CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall, DE->getExprLoc(), Ptr,
19290b57cec5SDimitry Andric                     ElementType);
19300b57cec5SDimitry Andric 
19310b57cec5SDimitry Andric   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
19320b57cec5SDimitry Andric   assert(!OperatorDelete->isDestroyingOperatorDelete());
19330b57cec5SDimitry Andric 
19340b57cec5SDimitry Andric   // Find the destructor for the type, if applicable.  If the
19350b57cec5SDimitry Andric   // destructor is virtual, we'll just emit the vcall and return.
19360b57cec5SDimitry Andric   const CXXDestructorDecl *Dtor = nullptr;
19370b57cec5SDimitry Andric   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
19380b57cec5SDimitry Andric     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
19390b57cec5SDimitry Andric     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
19400b57cec5SDimitry Andric       Dtor = RD->getDestructor();
19410b57cec5SDimitry Andric 
19420b57cec5SDimitry Andric       if (Dtor->isVirtual()) {
1943a7dea167SDimitry Andric         bool UseVirtualCall = true;
1944a7dea167SDimitry Andric         const Expr *Base = DE->getArgument();
1945a7dea167SDimitry Andric         if (auto *DevirtualizedDtor =
1946a7dea167SDimitry Andric                 dyn_cast_or_null<const CXXDestructorDecl>(
1947a7dea167SDimitry Andric                     Dtor->getDevirtualizedMethod(
1948a7dea167SDimitry Andric                         Base, CGF.CGM.getLangOpts().AppleKext))) {
1949a7dea167SDimitry Andric           UseVirtualCall = false;
1950a7dea167SDimitry Andric           const CXXRecordDecl *DevirtualizedClass =
1951a7dea167SDimitry Andric               DevirtualizedDtor->getParent();
1952a7dea167SDimitry Andric           if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) {
1953a7dea167SDimitry Andric             // Devirtualized to the class of the base type (the type of the
1954a7dea167SDimitry Andric             // whole expression).
1955a7dea167SDimitry Andric             Dtor = DevirtualizedDtor;
1956a7dea167SDimitry Andric           } else {
1957a7dea167SDimitry Andric             // Devirtualized to some other type. Would need to cast the this
1958a7dea167SDimitry Andric             // pointer to that type but we don't have support for that yet, so
1959a7dea167SDimitry Andric             // do a virtual call. FIXME: handle the case where it is
1960a7dea167SDimitry Andric             // devirtualized to the derived type (the type of the inner
1961a7dea167SDimitry Andric             // expression) as in EmitCXXMemberOrOperatorMemberCallExpr.
1962a7dea167SDimitry Andric             UseVirtualCall = true;
1963a7dea167SDimitry Andric           }
1964a7dea167SDimitry Andric         }
1965a7dea167SDimitry Andric         if (UseVirtualCall) {
19660b57cec5SDimitry Andric           CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
19670b57cec5SDimitry Andric                                                       Dtor);
19685ffd83dbSDimitry Andric           return false;
19690b57cec5SDimitry Andric         }
19700b57cec5SDimitry Andric       }
19710b57cec5SDimitry Andric     }
1972a7dea167SDimitry Andric   }
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric   // Make sure that we call delete even if the dtor throws.
19750b57cec5SDimitry Andric   // This doesn't have to a conditional cleanup because we're going
19760b57cec5SDimitry Andric   // to pop it off in a second.
1977*0fca6ea1SDimitry Andric   CGF.EHStack.pushCleanup<CallObjectDelete>(
1978*0fca6ea1SDimitry Andric       NormalAndEHCleanup, Ptr.emitRawPointer(CGF), OperatorDelete, ElementType);
19790b57cec5SDimitry Andric 
19800b57cec5SDimitry Andric   if (Dtor)
19810b57cec5SDimitry Andric     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
19820b57cec5SDimitry Andric                               /*ForVirtualBase=*/false,
19830b57cec5SDimitry Andric                               /*Delegating=*/false,
19840b57cec5SDimitry Andric                               Ptr, ElementType);
19850b57cec5SDimitry Andric   else if (auto Lifetime = ElementType.getObjCLifetime()) {
19860b57cec5SDimitry Andric     switch (Lifetime) {
19870b57cec5SDimitry Andric     case Qualifiers::OCL_None:
19880b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
19890b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
19900b57cec5SDimitry Andric       break;
19910b57cec5SDimitry Andric 
19920b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
19930b57cec5SDimitry Andric       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
19940b57cec5SDimitry Andric       break;
19950b57cec5SDimitry Andric 
19960b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
19970b57cec5SDimitry Andric       CGF.EmitARCDestroyWeak(Ptr);
19980b57cec5SDimitry Andric       break;
19990b57cec5SDimitry Andric     }
20000b57cec5SDimitry Andric   }
20010b57cec5SDimitry Andric 
20025ffd83dbSDimitry Andric   // When optimizing for size, call 'operator delete' unconditionally.
20035ffd83dbSDimitry Andric   if (CGF.CGM.getCodeGenOpts().OptimizeSize > 1) {
20045ffd83dbSDimitry Andric     CGF.EmitBlock(UnconditionalDeleteBlock);
20050b57cec5SDimitry Andric     CGF.PopCleanupBlock();
20065ffd83dbSDimitry Andric     return true;
20075ffd83dbSDimitry Andric   }
20085ffd83dbSDimitry Andric 
20095ffd83dbSDimitry Andric   CGF.PopCleanupBlock();
20105ffd83dbSDimitry Andric   return false;
20110b57cec5SDimitry Andric }
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric namespace {
20140b57cec5SDimitry Andric   /// Calls the given 'operator delete' on an array of objects.
20150b57cec5SDimitry Andric   struct CallArrayDelete final : EHScopeStack::Cleanup {
20160b57cec5SDimitry Andric     llvm::Value *Ptr;
20170b57cec5SDimitry Andric     const FunctionDecl *OperatorDelete;
20180b57cec5SDimitry Andric     llvm::Value *NumElements;
20190b57cec5SDimitry Andric     QualType ElementType;
20200b57cec5SDimitry Andric     CharUnits CookieSize;
20210b57cec5SDimitry Andric 
20220b57cec5SDimitry Andric     CallArrayDelete(llvm::Value *Ptr,
20230b57cec5SDimitry Andric                     const FunctionDecl *OperatorDelete,
20240b57cec5SDimitry Andric                     llvm::Value *NumElements,
20250b57cec5SDimitry Andric                     QualType ElementType,
20260b57cec5SDimitry Andric                     CharUnits CookieSize)
20270b57cec5SDimitry Andric       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
20280b57cec5SDimitry Andric         ElementType(ElementType), CookieSize(CookieSize) {}
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
20310b57cec5SDimitry Andric       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
20320b57cec5SDimitry Andric                          CookieSize);
20330b57cec5SDimitry Andric     }
20340b57cec5SDimitry Andric   };
20350b57cec5SDimitry Andric }
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric /// Emit the code for deleting an array of objects.
20380b57cec5SDimitry Andric static void EmitArrayDelete(CodeGenFunction &CGF,
20390b57cec5SDimitry Andric                             const CXXDeleteExpr *E,
20400b57cec5SDimitry Andric                             Address deletedPtr,
20410b57cec5SDimitry Andric                             QualType elementType) {
20420b57cec5SDimitry Andric   llvm::Value *numElements = nullptr;
20430b57cec5SDimitry Andric   llvm::Value *allocatedPtr = nullptr;
20440b57cec5SDimitry Andric   CharUnits cookieSize;
20450b57cec5SDimitry Andric   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
20460b57cec5SDimitry Andric                                       numElements, allocatedPtr, cookieSize);
20470b57cec5SDimitry Andric 
20480b57cec5SDimitry Andric   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
20490b57cec5SDimitry Andric 
20500b57cec5SDimitry Andric   // Make sure that we call delete even if one of the dtors throws.
20510b57cec5SDimitry Andric   const FunctionDecl *operatorDelete = E->getOperatorDelete();
20520b57cec5SDimitry Andric   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
20530b57cec5SDimitry Andric                                            allocatedPtr, operatorDelete,
20540b57cec5SDimitry Andric                                            numElements, elementType,
20550b57cec5SDimitry Andric                                            cookieSize);
20560b57cec5SDimitry Andric 
20570b57cec5SDimitry Andric   // Destroy the elements.
20580b57cec5SDimitry Andric   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
20590b57cec5SDimitry Andric     assert(numElements && "no element count for a type with a destructor!");
20600b57cec5SDimitry Andric 
20610b57cec5SDimitry Andric     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
20620b57cec5SDimitry Andric     CharUnits elementAlign =
20630b57cec5SDimitry Andric       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
20640b57cec5SDimitry Andric 
2065*0fca6ea1SDimitry Andric     llvm::Value *arrayBegin = deletedPtr.emitRawPointer(CGF);
2066fe6060f1SDimitry Andric     llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(
2067fe6060f1SDimitry Andric       deletedPtr.getElementType(), arrayBegin, numElements, "delete.end");
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric     // Note that it is legal to allocate a zero-length array, and we
20700b57cec5SDimitry Andric     // can never fold the check away because the length should always
20710b57cec5SDimitry Andric     // come from a cookie.
20720b57cec5SDimitry Andric     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
20730b57cec5SDimitry Andric                          CGF.getDestroyer(dtorKind),
20740b57cec5SDimitry Andric                          /*checkZeroLength*/ true,
20750b57cec5SDimitry Andric                          CGF.needsEHCleanup(dtorKind));
20760b57cec5SDimitry Andric   }
20770b57cec5SDimitry Andric 
20780b57cec5SDimitry Andric   // Pop the cleanup block.
20790b57cec5SDimitry Andric   CGF.PopCleanupBlock();
20800b57cec5SDimitry Andric }
20810b57cec5SDimitry Andric 
20820b57cec5SDimitry Andric void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
20830b57cec5SDimitry Andric   const Expr *Arg = E->getArgument();
20840b57cec5SDimitry Andric   Address Ptr = EmitPointerWithAlignment(Arg);
20850b57cec5SDimitry Andric 
20860b57cec5SDimitry Andric   // Null check the pointer.
20875ffd83dbSDimitry Andric   //
20885ffd83dbSDimitry Andric   // We could avoid this null check if we can determine that the object
20895ffd83dbSDimitry Andric   // destruction is trivial and doesn't require an array cookie; we can
20905ffd83dbSDimitry Andric   // unconditionally perform the operator delete call in that case. For now, we
20915ffd83dbSDimitry Andric   // assume that deleted pointers are null rarely enough that it's better to
20925ffd83dbSDimitry Andric   // keep the branch. This might be worth revisiting for a -O0 code size win.
20930b57cec5SDimitry Andric   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
20940b57cec5SDimitry Andric   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
20950b57cec5SDimitry Andric 
2096*0fca6ea1SDimitry Andric   llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
20970b57cec5SDimitry Andric 
20980b57cec5SDimitry Andric   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
20990b57cec5SDimitry Andric   EmitBlock(DeleteNotNull);
210006c3fb27SDimitry Andric   Ptr.setKnownNonNull();
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric   QualType DeleteTy = E->getDestroyedType();
21030b57cec5SDimitry Andric 
21040b57cec5SDimitry Andric   // A destroying operator delete overrides the entire operation of the
21050b57cec5SDimitry Andric   // delete expression.
21060b57cec5SDimitry Andric   if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
21070b57cec5SDimitry Andric     EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
21080b57cec5SDimitry Andric     EmitBlock(DeleteEnd);
21090b57cec5SDimitry Andric     return;
21100b57cec5SDimitry Andric   }
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric   // We might be deleting a pointer to array.  If so, GEP down to the
21130b57cec5SDimitry Andric   // first non-array element.
21140b57cec5SDimitry Andric   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
21150b57cec5SDimitry Andric   if (DeleteTy->isConstantArrayType()) {
21160b57cec5SDimitry Andric     llvm::Value *Zero = Builder.getInt32(0);
21170b57cec5SDimitry Andric     SmallVector<llvm::Value*,8> GEP;
21180b57cec5SDimitry Andric 
21190b57cec5SDimitry Andric     GEP.push_back(Zero); // point at the outermost array
21200b57cec5SDimitry Andric 
21210b57cec5SDimitry Andric     // For each layer of array type we're pointing at:
21220b57cec5SDimitry Andric     while (const ConstantArrayType *Arr
21230b57cec5SDimitry Andric              = getContext().getAsConstantArrayType(DeleteTy)) {
21240b57cec5SDimitry Andric       // 1. Unpeel the array type.
21250b57cec5SDimitry Andric       DeleteTy = Arr->getElementType();
21260b57cec5SDimitry Andric 
21270b57cec5SDimitry Andric       // 2. GEP to the first element of the array.
21280b57cec5SDimitry Andric       GEP.push_back(Zero);
21290b57cec5SDimitry Andric     }
21300b57cec5SDimitry Andric 
2131*0fca6ea1SDimitry Andric     Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, ConvertTypeForMem(DeleteTy),
2132*0fca6ea1SDimitry Andric                                     Ptr.getAlignment(), "del.first");
21330b57cec5SDimitry Andric   }
21340b57cec5SDimitry Andric 
21350b57cec5SDimitry Andric   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric   if (E->isArrayForm()) {
21380b57cec5SDimitry Andric     EmitArrayDelete(*this, E, Ptr, DeleteTy);
21390b57cec5SDimitry Andric     EmitBlock(DeleteEnd);
21405ffd83dbSDimitry Andric   } else {
21415ffd83dbSDimitry Andric     if (!EmitObjectDelete(*this, E, Ptr, DeleteTy, DeleteEnd))
21425ffd83dbSDimitry Andric       EmitBlock(DeleteEnd);
21435ffd83dbSDimitry Andric   }
21440b57cec5SDimitry Andric }
21450b57cec5SDimitry Andric 
21460b57cec5SDimitry Andric static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
2147*0fca6ea1SDimitry Andric                                          llvm::Type *StdTypeInfoPtrTy,
2148*0fca6ea1SDimitry Andric                                          bool HasNullCheck) {
21490b57cec5SDimitry Andric   // Get the vtable pointer.
2150*0fca6ea1SDimitry Andric   Address ThisPtr = CGF.EmitLValue(E).getAddress();
21510b57cec5SDimitry Andric 
21520b57cec5SDimitry Andric   QualType SrcRecordTy = E->getType();
21530b57cec5SDimitry Andric 
21540b57cec5SDimitry Andric   // C++ [class.cdtor]p4:
21550b57cec5SDimitry Andric   //   If the operand of typeid refers to the object under construction or
21560b57cec5SDimitry Andric   //   destruction and the static type of the operand is neither the constructor
21570b57cec5SDimitry Andric   //   or destructor’s class nor one of its bases, the behavior is undefined.
21580b57cec5SDimitry Andric   CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
2159*0fca6ea1SDimitry Andric                     ThisPtr, SrcRecordTy);
21600b57cec5SDimitry Andric 
2161*0fca6ea1SDimitry Andric   // Whether we need an explicit null pointer check. For example, with the
2162*0fca6ea1SDimitry Andric   // Microsoft ABI, if this is a call to __RTtypeid, the null pointer check and
2163*0fca6ea1SDimitry Andric   // exception throw is inside the __RTtypeid(nullptr) call
2164*0fca6ea1SDimitry Andric   if (HasNullCheck &&
2165*0fca6ea1SDimitry Andric       CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(SrcRecordTy)) {
21660b57cec5SDimitry Andric     llvm::BasicBlock *BadTypeidBlock =
21670b57cec5SDimitry Andric         CGF.createBasicBlock("typeid.bad_typeid");
21680b57cec5SDimitry Andric     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
21690b57cec5SDimitry Andric 
2170*0fca6ea1SDimitry Andric     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
21710b57cec5SDimitry Andric     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
21720b57cec5SDimitry Andric 
21730b57cec5SDimitry Andric     CGF.EmitBlock(BadTypeidBlock);
21740b57cec5SDimitry Andric     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
21750b57cec5SDimitry Andric     CGF.EmitBlock(EndBlock);
21760b57cec5SDimitry Andric   }
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
21790b57cec5SDimitry Andric                                         StdTypeInfoPtrTy);
21800b57cec5SDimitry Andric }
21810b57cec5SDimitry Andric 
21820b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2183*0fca6ea1SDimitry Andric   // Ideally, we would like to use GlobalsInt8PtrTy here, however, we cannot,
2184*0fca6ea1SDimitry Andric   // primarily because the result of applying typeid is a value of type
2185*0fca6ea1SDimitry Andric   // type_info, which is declared & defined by the standard library
2186*0fca6ea1SDimitry Andric   // implementation and expects to operate on the generic (default) AS.
2187*0fca6ea1SDimitry Andric   // https://reviews.llvm.org/D157452 has more context, and a possible solution.
2188*0fca6ea1SDimitry Andric   llvm::Type *PtrTy = Int8PtrTy;
21895f757f3fSDimitry Andric   LangAS GlobAS = CGM.GetGlobalVarAddressSpace(nullptr);
21905f757f3fSDimitry Andric 
21915f757f3fSDimitry Andric   auto MaybeASCast = [=](auto &&TypeInfo) {
21925f757f3fSDimitry Andric     if (GlobAS == LangAS::Default)
21935f757f3fSDimitry Andric       return TypeInfo;
21945f757f3fSDimitry Andric     return getTargetHooks().performAddrSpaceCast(CGM,TypeInfo, GlobAS,
21955f757f3fSDimitry Andric                                                  LangAS::Default, PtrTy);
21965f757f3fSDimitry Andric   };
21970b57cec5SDimitry Andric 
21980b57cec5SDimitry Andric   if (E->isTypeOperand()) {
21990b57cec5SDimitry Andric     llvm::Constant *TypeInfo =
22000b57cec5SDimitry Andric         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
22015f757f3fSDimitry Andric     return MaybeASCast(TypeInfo);
22020b57cec5SDimitry Andric   }
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric   // C++ [expr.typeid]p2:
22050b57cec5SDimitry Andric   //   When typeid is applied to a glvalue expression whose type is a
22060b57cec5SDimitry Andric   //   polymorphic class type, the result refers to a std::type_info object
22070b57cec5SDimitry Andric   //   representing the type of the most derived object (that is, the dynamic
22080b57cec5SDimitry Andric   //   type) to which the glvalue refers.
2209e8d8bef9SDimitry Andric   // If the operand is already most derived object, no need to look up vtable.
2210e8d8bef9SDimitry Andric   if (E->isPotentiallyEvaluated() && !E->isMostDerived(getContext()))
2211*0fca6ea1SDimitry Andric     return EmitTypeidFromVTable(*this, E->getExprOperand(), PtrTy,
2212*0fca6ea1SDimitry Andric                                 E->hasNullCheck());
22130b57cec5SDimitry Andric 
22140b57cec5SDimitry Andric   QualType OperandTy = E->getExprOperand()->getType();
22155f757f3fSDimitry Andric   return MaybeASCast(CGM.GetAddrOfRTTIDescriptor(OperandTy));
22160b57cec5SDimitry Andric }
22170b57cec5SDimitry Andric 
22180b57cec5SDimitry Andric static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
22190b57cec5SDimitry Andric                                           QualType DestTy) {
22200b57cec5SDimitry Andric   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
22210b57cec5SDimitry Andric   if (DestTy->isPointerType())
22220b57cec5SDimitry Andric     return llvm::Constant::getNullValue(DestLTy);
22230b57cec5SDimitry Andric 
22240b57cec5SDimitry Andric   /// C++ [expr.dynamic.cast]p9:
22250b57cec5SDimitry Andric   ///   A failed cast to reference type throws std::bad_cast
22260b57cec5SDimitry Andric   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
22270b57cec5SDimitry Andric     return nullptr;
22280b57cec5SDimitry Andric 
222906c3fb27SDimitry Andric   CGF.Builder.ClearInsertionPoint();
223006c3fb27SDimitry Andric   return llvm::PoisonValue::get(DestLTy);
22310b57cec5SDimitry Andric }
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
22340b57cec5SDimitry Andric                                               const CXXDynamicCastExpr *DCE) {
22350b57cec5SDimitry Andric   CGM.EmitExplicitCastExprType(DCE, this);
22360b57cec5SDimitry Andric   QualType DestTy = DCE->getTypeAsWritten();
22370b57cec5SDimitry Andric 
22380b57cec5SDimitry Andric   QualType SrcTy = DCE->getSubExpr()->getType();
22390b57cec5SDimitry Andric 
22400b57cec5SDimitry Andric   // C++ [expr.dynamic.cast]p7:
22410b57cec5SDimitry Andric   //   If T is "pointer to cv void," then the result is a pointer to the most
22420b57cec5SDimitry Andric   //   derived object pointed to by v.
224306c3fb27SDimitry Andric   bool IsDynamicCastToVoid = DestTy->isVoidPointerType();
22440b57cec5SDimitry Andric   QualType SrcRecordTy;
22450b57cec5SDimitry Andric   QualType DestRecordTy;
224606c3fb27SDimitry Andric   if (IsDynamicCastToVoid) {
224706c3fb27SDimitry Andric     SrcRecordTy = SrcTy->getPointeeType();
224806c3fb27SDimitry Andric     // No DestRecordTy.
224906c3fb27SDimitry Andric   } else if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
22500b57cec5SDimitry Andric     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
22510b57cec5SDimitry Andric     DestRecordTy = DestPTy->getPointeeType();
22520b57cec5SDimitry Andric   } else {
22530b57cec5SDimitry Andric     SrcRecordTy = SrcTy;
22540b57cec5SDimitry Andric     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
22550b57cec5SDimitry Andric   }
22560b57cec5SDimitry Andric 
22570b57cec5SDimitry Andric   // C++ [class.cdtor]p5:
22580b57cec5SDimitry Andric   //   If the operand of the dynamic_cast refers to the object under
22590b57cec5SDimitry Andric   //   construction or destruction and the static type of the operand is not a
22600b57cec5SDimitry Andric   //   pointer to or object of the constructor or destructor’s own class or one
22610b57cec5SDimitry Andric   //   of its bases, the dynamic_cast results in undefined behavior.
2262*0fca6ea1SDimitry Andric   EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr, SrcRecordTy);
22630b57cec5SDimitry Andric 
226406c3fb27SDimitry Andric   if (DCE->isAlwaysNull()) {
226506c3fb27SDimitry Andric     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy)) {
226606c3fb27SDimitry Andric       // Expression emission is expected to retain a valid insertion point.
226706c3fb27SDimitry Andric       if (!Builder.GetInsertBlock())
226806c3fb27SDimitry Andric         EmitBlock(createBasicBlock("dynamic_cast.unreachable"));
22690b57cec5SDimitry Andric       return T;
227006c3fb27SDimitry Andric     }
227106c3fb27SDimitry Andric   }
22720b57cec5SDimitry Andric 
22730b57cec5SDimitry Andric   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
22740b57cec5SDimitry Andric 
227506c3fb27SDimitry Andric   // If the destination is effectively final, the cast succeeds if and only
227606c3fb27SDimitry Andric   // if the dynamic type of the pointer is exactly the destination type.
227706c3fb27SDimitry Andric   bool IsExact = !IsDynamicCastToVoid &&
227806c3fb27SDimitry Andric                  CGM.getCodeGenOpts().OptimizationLevel > 0 &&
227906c3fb27SDimitry Andric                  DestRecordTy->getAsCXXRecordDecl()->isEffectivelyFinal() &&
228006c3fb27SDimitry Andric                  CGM.getCXXABI().shouldEmitExactDynamicCast(DestRecordTy);
228106c3fb27SDimitry Andric 
22820b57cec5SDimitry Andric   // C++ [expr.dynamic.cast]p4:
22830b57cec5SDimitry Andric   //   If the value of v is a null pointer value in the pointer case, the result
22840b57cec5SDimitry Andric   //   is the null pointer value of type T.
22850b57cec5SDimitry Andric   bool ShouldNullCheckSrcValue =
228606c3fb27SDimitry Andric       IsExact || CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(
228706c3fb27SDimitry Andric                      SrcTy->isPointerType(), SrcRecordTy);
22880b57cec5SDimitry Andric 
22890b57cec5SDimitry Andric   llvm::BasicBlock *CastNull = nullptr;
22900b57cec5SDimitry Andric   llvm::BasicBlock *CastNotNull = nullptr;
22910b57cec5SDimitry Andric   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric   if (ShouldNullCheckSrcValue) {
22940b57cec5SDimitry Andric     CastNull = createBasicBlock("dynamic_cast.null");
22950b57cec5SDimitry Andric     CastNotNull = createBasicBlock("dynamic_cast.notnull");
22960b57cec5SDimitry Andric 
2297*0fca6ea1SDimitry Andric     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr);
22980b57cec5SDimitry Andric     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
22990b57cec5SDimitry Andric     EmitBlock(CastNotNull);
23000b57cec5SDimitry Andric   }
23010b57cec5SDimitry Andric 
23020b57cec5SDimitry Andric   llvm::Value *Value;
230306c3fb27SDimitry Andric   if (IsDynamicCastToVoid) {
230406c3fb27SDimitry Andric     Value = CGM.getCXXABI().emitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy);
230506c3fb27SDimitry Andric   } else if (IsExact) {
230606c3fb27SDimitry Andric     // If the destination type is effectively final, this pointer points to the
230706c3fb27SDimitry Andric     // right type if and only if its vptr has the right value.
230806c3fb27SDimitry Andric     Value = CGM.getCXXABI().emitExactDynamicCast(
230906c3fb27SDimitry Andric         *this, ThisAddr, SrcRecordTy, DestTy, DestRecordTy, CastEnd, CastNull);
23100b57cec5SDimitry Andric   } else {
23110b57cec5SDimitry Andric     assert(DestRecordTy->isRecordType() &&
23120b57cec5SDimitry Andric            "destination type must be a record type!");
231306c3fb27SDimitry Andric     Value = CGM.getCXXABI().emitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
23140b57cec5SDimitry Andric                                                 DestTy, DestRecordTy, CastEnd);
23150b57cec5SDimitry Andric   }
231606c3fb27SDimitry Andric   CastNotNull = Builder.GetInsertBlock();
23170b57cec5SDimitry Andric 
231806c3fb27SDimitry Andric   llvm::Value *NullValue = nullptr;
23190b57cec5SDimitry Andric   if (ShouldNullCheckSrcValue) {
23200b57cec5SDimitry Andric     EmitBranch(CastEnd);
23210b57cec5SDimitry Andric 
23220b57cec5SDimitry Andric     EmitBlock(CastNull);
232306c3fb27SDimitry Andric     NullValue = EmitDynamicCastToNull(*this, DestTy);
232406c3fb27SDimitry Andric     CastNull = Builder.GetInsertBlock();
232506c3fb27SDimitry Andric 
23260b57cec5SDimitry Andric     EmitBranch(CastEnd);
23270b57cec5SDimitry Andric   }
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric   EmitBlock(CastEnd);
23300b57cec5SDimitry Andric 
233106c3fb27SDimitry Andric   if (CastNull) {
23320b57cec5SDimitry Andric     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
23330b57cec5SDimitry Andric     PHI->addIncoming(Value, CastNotNull);
233406c3fb27SDimitry Andric     PHI->addIncoming(NullValue, CastNull);
23350b57cec5SDimitry Andric 
23360b57cec5SDimitry Andric     Value = PHI;
23370b57cec5SDimitry Andric   }
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric   return Value;
23400b57cec5SDimitry Andric }
2341