Home | History | Annotate | Download | only in CodeGen
      1 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This contains code dealing with code generation of C++ expressions
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "CodeGenFunction.h"
     15 #include "CGCUDARuntime.h"
     16 #include "CGCXXABI.h"
     17 #include "CGDebugInfo.h"
     18 #include "CGObjCRuntime.h"
     19 #include "clang/CodeGen/CGFunctionInfo.h"
     20 #include "clang/Frontend/CodeGenOptions.h"
     21 #include "llvm/IR/CallSite.h"
     22 #include "llvm/IR/Intrinsics.h"
     23 
     24 using namespace clang;
     25 using namespace CodeGen;
     26 
     27 static RequiredArgs commonEmitCXXMemberOrOperatorCall(
     28     CodeGenFunction &CGF, const CXXMethodDecl *MD, llvm::Value *Callee,
     29     ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam,
     30     QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args) {
     31   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
     32          isa<CXXOperatorCallExpr>(CE));
     33   assert(MD->isInstance() &&
     34          "Trying to emit a member or operator call expr on a static method!");
     35 
     36   // C++11 [class.mfct.non-static]p2:
     37   //   If a non-static member function of a class X is called for an object that
     38   //   is not of type X, or of a type derived from X, the behavior is undefined.
     39   SourceLocation CallLoc;
     40   if (CE)
     41     CallLoc = CE->getExprLoc();
     42   CGF.EmitTypeCheck(
     43       isa<CXXConstructorDecl>(MD) ? CodeGenFunction::TCK_ConstructorCall
     44                                   : CodeGenFunction::TCK_MemberCall,
     45       CallLoc, This, CGF.getContext().getRecordType(MD->getParent()));
     46 
     47   // Push the this ptr.
     48   Args.add(RValue::get(This), MD->getThisType(CGF.getContext()));
     49 
     50   // If there is an implicit parameter (e.g. VTT), emit it.
     51   if (ImplicitParam) {
     52     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
     53   }
     54 
     55   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
     56   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
     57 
     58   // And the rest of the call args.
     59   if (CE) {
     60     // Special case: skip first argument of CXXOperatorCall (it is "this").
     61     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
     62     CGF.EmitCallArgs(Args, FPT, CE->arg_begin() + ArgsToSkip, CE->arg_end(),
     63                      CE->getDirectCallee());
     64   } else {
     65     assert(
     66         FPT->getNumParams() == 0 &&
     67         "No CallExpr specified for function with non-zero number of arguments");
     68   }
     69   return required;
     70 }
     71 
     72 RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
     73     const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
     74     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
     75     const CallExpr *CE) {
     76   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
     77   CallArgList Args;
     78   RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
     79       *this, MD, Callee, ReturnValue, This, ImplicitParam, ImplicitParamTy, CE,
     80       Args);
     81   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
     82                   Callee, ReturnValue, Args, MD);
     83 }
     84 
     85 RValue CodeGenFunction::EmitCXXStructorCall(
     86     const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
     87     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
     88     const CallExpr *CE, StructorType Type) {
     89   CallArgList Args;
     90   commonEmitCXXMemberOrOperatorCall(*this, MD, Callee, ReturnValue, This,
     91                                     ImplicitParam, ImplicitParamTy, CE, Args);
     92   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(MD, Type),
     93                   Callee, ReturnValue, Args, MD);
     94 }
     95 
     96 static CXXRecordDecl *getCXXRecord(const Expr *E) {
     97   QualType T = E->getType();
     98   if (const PointerType *PTy = T->getAs<PointerType>())
     99     T = PTy->getPointeeType();
    100   const RecordType *Ty = T->castAs<RecordType>();
    101   return cast<CXXRecordDecl>(Ty->getDecl());
    102 }
    103 
    104 // Note: This function also emit constructor calls to support a MSVC
    105 // extensions allowing explicit constructor function call.
    106 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
    107                                               ReturnValueSlot ReturnValue) {
    108   const Expr *callee = CE->getCallee()->IgnoreParens();
    109 
    110   if (isa<BinaryOperator>(callee))
    111     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
    112 
    113   const MemberExpr *ME = cast<MemberExpr>(callee);
    114   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
    115 
    116   if (MD->isStatic()) {
    117     // The method is static, emit it as we would a regular call.
    118     llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
    119     return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
    120                     ReturnValue);
    121   }
    122 
    123   bool HasQualifier = ME->hasQualifier();
    124   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
    125   bool IsArrow = ME->isArrow();
    126   const Expr *Base = ME->getBase();
    127 
    128   return EmitCXXMemberOrOperatorMemberCallExpr(
    129       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
    130 }
    131 
    132 RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
    133     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
    134     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
    135     const Expr *Base) {
    136   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
    137 
    138   // Compute the object pointer.
    139   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
    140 
    141   const CXXMethodDecl *DevirtualizedMethod = nullptr;
    142   if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
    143     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
    144     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
    145     assert(DevirtualizedMethod);
    146     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
    147     const Expr *Inner = Base->ignoreParenBaseCasts();
    148     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
    149         MD->getReturnType().getCanonicalType())
    150       // If the return types are not the same, this might be a case where more
    151       // code needs to run to compensate for it. For example, the derived
    152       // method might return a type that inherits form from the return
    153       // type of MD and has a prefix.
    154       // For now we just avoid devirtualizing these covariant cases.
    155       DevirtualizedMethod = nullptr;
    156     else if (getCXXRecord(Inner) == DevirtualizedClass)
    157       // If the class of the Inner expression is where the dynamic method
    158       // is defined, build the this pointer from it.
    159       Base = Inner;
    160     else if (getCXXRecord(Base) != DevirtualizedClass) {
    161       // If the method is defined in a class that is not the best dynamic
    162       // one or the one of the full expression, we would have to build
    163       // a derived-to-base cast to compute the correct this pointer, but
    164       // we don't have support for that yet, so do a virtual call.
    165       DevirtualizedMethod = nullptr;
    166     }
    167   }
    168 
    169   llvm::Value *This;
    170   if (IsArrow)
    171     This = EmitScalarExpr(Base);
    172   else
    173     This = EmitLValue(Base).getAddress();
    174 
    175 
    176   if (MD->isTrivial()) {
    177     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
    178     if (isa<CXXConstructorDecl>(MD) &&
    179         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
    180       return RValue::get(nullptr);
    181 
    182     if (!MD->getParent()->mayInsertExtraPadding()) {
    183       if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
    184         // We don't like to generate the trivial copy/move assignment operator
    185         // when it isn't necessary; just produce the proper effect here.
    186         // Special case: skip first argument of CXXOperatorCall (it is "this").
    187         unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
    188         llvm::Value *RHS =
    189             EmitLValue(*(CE->arg_begin() + ArgsToSkip)).getAddress();
    190         EmitAggregateAssign(This, RHS, CE->getType());
    191         return RValue::get(This);
    192       }
    193 
    194       if (isa<CXXConstructorDecl>(MD) &&
    195           cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
    196         // Trivial move and copy ctor are the same.
    197         assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
    198         llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
    199         EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
    200         return RValue::get(This);
    201       }
    202       llvm_unreachable("unknown trivial member function");
    203     }
    204   }
    205 
    206   // Compute the function type we're calling.
    207   const CXXMethodDecl *CalleeDecl =
    208       DevirtualizedMethod ? DevirtualizedMethod : MD;
    209   const CGFunctionInfo *FInfo = nullptr;
    210   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
    211     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
    212         Dtor, StructorType::Complete);
    213   else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
    214     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
    215         Ctor, StructorType::Complete);
    216   else
    217     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
    218 
    219   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
    220 
    221   // C++ [class.virtual]p12:
    222   //   Explicit qualification with the scope operator (5.1) suppresses the
    223   //   virtual call mechanism.
    224   //
    225   // We also don't emit a virtual call if the base expression has a record type
    226   // because then we know what the type is.
    227   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
    228   llvm::Value *Callee;
    229 
    230   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
    231     assert(CE->arg_begin() == CE->arg_end() &&
    232            "Destructor shouldn't have explicit parameters");
    233     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
    234     if (UseVirtualCall) {
    235       CGM.getCXXABI().EmitVirtualDestructorCall(
    236           *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
    237     } else {
    238       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
    239         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
    240       else if (!DevirtualizedMethod)
    241         Callee =
    242             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
    243       else {
    244         const CXXDestructorDecl *DDtor =
    245           cast<CXXDestructorDecl>(DevirtualizedMethod);
    246         Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
    247       }
    248       EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
    249                                   /*ImplicitParam=*/nullptr, QualType(), CE);
    250     }
    251     return RValue::get(nullptr);
    252   }
    253 
    254   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
    255     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
    256   } else if (UseVirtualCall) {
    257     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
    258   } else {
    259     if (SanOpts.has(SanitizerKind::CFINVCall) &&
    260         MD->getParent()->isDynamicClass()) {
    261       llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy);
    262       EmitVTablePtrCheckForCall(MD, VTable);
    263     }
    264 
    265     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
    266       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
    267     else if (!DevirtualizedMethod)
    268       Callee = CGM.GetAddrOfFunction(MD, Ty);
    269     else {
    270       Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
    271     }
    272   }
    273 
    274   if (MD->isVirtual()) {
    275     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
    276         *this, MD, This, UseVirtualCall);
    277   }
    278 
    279   return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
    280                                      /*ImplicitParam=*/nullptr, QualType(), CE);
    281 }
    282 
    283 RValue
    284 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
    285                                               ReturnValueSlot ReturnValue) {
    286   const BinaryOperator *BO =
    287       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
    288   const Expr *BaseExpr = BO->getLHS();
    289   const Expr *MemFnExpr = BO->getRHS();
    290 
    291   const MemberPointerType *MPT =
    292     MemFnExpr->getType()->castAs<MemberPointerType>();
    293 
    294   const FunctionProtoType *FPT =
    295     MPT->getPointeeType()->castAs<FunctionProtoType>();
    296   const CXXRecordDecl *RD =
    297     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
    298 
    299   // Get the member function pointer.
    300   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
    301 
    302   // Emit the 'this' pointer.
    303   llvm::Value *This;
    304 
    305   if (BO->getOpcode() == BO_PtrMemI)
    306     This = EmitScalarExpr(BaseExpr);
    307   else
    308     This = EmitLValue(BaseExpr).getAddress();
    309 
    310   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
    311                 QualType(MPT->getClass(), 0));
    312 
    313   // Ask the ABI to load the callee.  Note that This is modified.
    314   llvm::Value *Callee =
    315     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
    316 
    317   CallArgList Args;
    318 
    319   QualType ThisType =
    320     getContext().getPointerType(getContext().getTagDeclType(RD));
    321 
    322   // Push the this ptr.
    323   Args.add(RValue::get(This), ThisType);
    324 
    325   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
    326 
    327   // And the rest of the call args
    328   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
    329   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
    330                   Callee, ReturnValue, Args);
    331 }
    332 
    333 RValue
    334 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
    335                                                const CXXMethodDecl *MD,
    336                                                ReturnValueSlot ReturnValue) {
    337   assert(MD->isInstance() &&
    338          "Trying to emit a member call expr on a static method!");
    339   return EmitCXXMemberOrOperatorMemberCallExpr(
    340       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
    341       /*IsArrow=*/false, E->getArg(0));
    342 }
    343 
    344 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
    345                                                ReturnValueSlot ReturnValue) {
    346   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
    347 }
    348 
    349 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
    350                                             llvm::Value *DestPtr,
    351                                             const CXXRecordDecl *Base) {
    352   if (Base->isEmpty())
    353     return;
    354 
    355   DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
    356 
    357   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
    358   CharUnits Size = Layout.getNonVirtualSize();
    359   CharUnits Align = Layout.getNonVirtualAlignment();
    360 
    361   llvm::Value *SizeVal = CGF.CGM.getSize(Size);
    362 
    363   // If the type contains a pointer to data member we can't memset it to zero.
    364   // Instead, create a null constant and copy it to the destination.
    365   // TODO: there are other patterns besides zero that we can usefully memset,
    366   // like -1, which happens to be the pattern used by member-pointers.
    367   // TODO: isZeroInitializable can be over-conservative in the case where a
    368   // virtual base contains a member pointer.
    369   if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
    370     llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
    371 
    372     llvm::GlobalVariable *NullVariable =
    373       new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
    374                                /*isConstant=*/true,
    375                                llvm::GlobalVariable::PrivateLinkage,
    376                                NullConstant, Twine());
    377     NullVariable->setAlignment(Align.getQuantity());
    378     llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
    379 
    380     // Get and call the appropriate llvm.memcpy overload.
    381     CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
    382     return;
    383   }
    384 
    385   // Otherwise, just memset the whole thing to zero.  This is legal
    386   // because in LLVM, all default initializers (other than the ones we just
    387   // handled above) are guaranteed to have a bit pattern of all zeros.
    388   CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
    389                            Align.getQuantity());
    390 }
    391 
    392 void
    393 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
    394                                       AggValueSlot Dest) {
    395   assert(!Dest.isIgnored() && "Must have a destination!");
    396   const CXXConstructorDecl *CD = E->getConstructor();
    397 
    398   // If we require zero initialization before (or instead of) calling the
    399   // constructor, as can be the case with a non-user-provided default
    400   // constructor, emit the zero initialization now, unless destination is
    401   // already zeroed.
    402   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
    403     switch (E->getConstructionKind()) {
    404     case CXXConstructExpr::CK_Delegating:
    405     case CXXConstructExpr::CK_Complete:
    406       EmitNullInitialization(Dest.getAddr(), E->getType());
    407       break;
    408     case CXXConstructExpr::CK_VirtualBase:
    409     case CXXConstructExpr::CK_NonVirtualBase:
    410       EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
    411       break;
    412     }
    413   }
    414 
    415   // If this is a call to a trivial default constructor, do nothing.
    416   if (CD->isTrivial() && CD->isDefaultConstructor())
    417     return;
    418 
    419   // Elide the constructor if we're constructing from a temporary.
    420   // The temporary check is required because Sema sets this on NRVO
    421   // returns.
    422   if (getLangOpts().ElideConstructors && E->isElidable()) {
    423     assert(getContext().hasSameUnqualifiedType(E->getType(),
    424                                                E->getArg(0)->getType()));
    425     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
    426       EmitAggExpr(E->getArg(0), Dest);
    427       return;
    428     }
    429   }
    430 
    431   if (const ConstantArrayType *arrayType
    432         = getContext().getAsConstantArrayType(E->getType())) {
    433     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
    434   } else {
    435     CXXCtorType Type = Ctor_Complete;
    436     bool ForVirtualBase = false;
    437     bool Delegating = false;
    438 
    439     switch (E->getConstructionKind()) {
    440      case CXXConstructExpr::CK_Delegating:
    441       // We should be emitting a constructor; GlobalDecl will assert this
    442       Type = CurGD.getCtorType();
    443       Delegating = true;
    444       break;
    445 
    446      case CXXConstructExpr::CK_Complete:
    447       Type = Ctor_Complete;
    448       break;
    449 
    450      case CXXConstructExpr::CK_VirtualBase:
    451       ForVirtualBase = true;
    452       // fall-through
    453 
    454      case CXXConstructExpr::CK_NonVirtualBase:
    455       Type = Ctor_Base;
    456     }
    457 
    458     // Call the constructor.
    459     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
    460                            E);
    461   }
    462 }
    463 
    464 void
    465 CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
    466                                             llvm::Value *Src,
    467                                             const Expr *Exp) {
    468   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
    469     Exp = E->getSubExpr();
    470   assert(isa<CXXConstructExpr>(Exp) &&
    471          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
    472   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
    473   const CXXConstructorDecl *CD = E->getConstructor();
    474   RunCleanupsScope Scope(*this);
    475 
    476   // If we require zero initialization before (or instead of) calling the
    477   // constructor, as can be the case with a non-user-provided default
    478   // constructor, emit the zero initialization now.
    479   // FIXME. Do I still need this for a copy ctor synthesis?
    480   if (E->requiresZeroInitialization())
    481     EmitNullInitialization(Dest, E->getType());
    482 
    483   assert(!getContext().getAsConstantArrayType(E->getType())
    484          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
    485   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
    486 }
    487 
    488 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
    489                                         const CXXNewExpr *E) {
    490   if (!E->isArray())
    491     return CharUnits::Zero();
    492 
    493   // No cookie is required if the operator new[] being used is the
    494   // reserved placement operator new[].
    495   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
    496     return CharUnits::Zero();
    497 
    498   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
    499 }
    500 
    501 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
    502                                         const CXXNewExpr *e,
    503                                         unsigned minElements,
    504                                         llvm::Value *&numElements,
    505                                         llvm::Value *&sizeWithoutCookie) {
    506   QualType type = e->getAllocatedType();
    507 
    508   if (!e->isArray()) {
    509     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
    510     sizeWithoutCookie
    511       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
    512     return sizeWithoutCookie;
    513   }
    514 
    515   // The width of size_t.
    516   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
    517 
    518   // Figure out the cookie size.
    519   llvm::APInt cookieSize(sizeWidth,
    520                          CalculateCookiePadding(CGF, e).getQuantity());
    521 
    522   // Emit the array size expression.
    523   // We multiply the size of all dimensions for NumElements.
    524   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
    525   numElements = CGF.EmitScalarExpr(e->getArraySize());
    526   assert(isa<llvm::IntegerType>(numElements->getType()));
    527 
    528   // The number of elements can be have an arbitrary integer type;
    529   // essentially, we need to multiply it by a constant factor, add a
    530   // cookie size, and verify that the result is representable as a
    531   // size_t.  That's just a gloss, though, and it's wrong in one
    532   // important way: if the count is negative, it's an error even if
    533   // the cookie size would bring the total size >= 0.
    534   bool isSigned
    535     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
    536   llvm::IntegerType *numElementsType
    537     = cast<llvm::IntegerType>(numElements->getType());
    538   unsigned numElementsWidth = numElementsType->getBitWidth();
    539 
    540   // Compute the constant factor.
    541   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
    542   while (const ConstantArrayType *CAT
    543              = CGF.getContext().getAsConstantArrayType(type)) {
    544     type = CAT->getElementType();
    545     arraySizeMultiplier *= CAT->getSize();
    546   }
    547 
    548   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
    549   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
    550   typeSizeMultiplier *= arraySizeMultiplier;
    551 
    552   // This will be a size_t.
    553   llvm::Value *size;
    554 
    555   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
    556   // Don't bloat the -O0 code.
    557   if (llvm::ConstantInt *numElementsC =
    558         dyn_cast<llvm::ConstantInt>(numElements)) {
    559     const llvm::APInt &count = numElementsC->getValue();
    560 
    561     bool hasAnyOverflow = false;
    562 
    563     // If 'count' was a negative number, it's an overflow.
    564     if (isSigned && count.isNegative())
    565       hasAnyOverflow = true;
    566 
    567     // We want to do all this arithmetic in size_t.  If numElements is
    568     // wider than that, check whether it's already too big, and if so,
    569     // overflow.
    570     else if (numElementsWidth > sizeWidth &&
    571              numElementsWidth - sizeWidth > count.countLeadingZeros())
    572       hasAnyOverflow = true;
    573 
    574     // Okay, compute a count at the right width.
    575     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
    576 
    577     // If there is a brace-initializer, we cannot allocate fewer elements than
    578     // there are initializers. If we do, that's treated like an overflow.
    579     if (adjustedCount.ult(minElements))
    580       hasAnyOverflow = true;
    581 
    582     // Scale numElements by that.  This might overflow, but we don't
    583     // care because it only overflows if allocationSize does, too, and
    584     // if that overflows then we shouldn't use this.
    585     numElements = llvm::ConstantInt::get(CGF.SizeTy,
    586                                          adjustedCount * arraySizeMultiplier);
    587 
    588     // Compute the size before cookie, and track whether it overflowed.
    589     bool overflow;
    590     llvm::APInt allocationSize
    591       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
    592     hasAnyOverflow |= overflow;
    593 
    594     // Add in the cookie, and check whether it's overflowed.
    595     if (cookieSize != 0) {
    596       // Save the current size without a cookie.  This shouldn't be
    597       // used if there was overflow.
    598       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
    599 
    600       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
    601       hasAnyOverflow |= overflow;
    602     }
    603 
    604     // On overflow, produce a -1 so operator new will fail.
    605     if (hasAnyOverflow) {
    606       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
    607     } else {
    608       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
    609     }
    610 
    611   // Otherwise, we might need to use the overflow intrinsics.
    612   } else {
    613     // There are up to five conditions we need to test for:
    614     // 1) if isSigned, we need to check whether numElements is negative;
    615     // 2) if numElementsWidth > sizeWidth, we need to check whether
    616     //   numElements is larger than something representable in size_t;
    617     // 3) if minElements > 0, we need to check whether numElements is smaller
    618     //    than that.
    619     // 4) we need to compute
    620     //      sizeWithoutCookie := numElements * typeSizeMultiplier
    621     //    and check whether it overflows; and
    622     // 5) if we need a cookie, we need to compute
    623     //      size := sizeWithoutCookie + cookieSize
    624     //    and check whether it overflows.
    625 
    626     llvm::Value *hasOverflow = nullptr;
    627 
    628     // If numElementsWidth > sizeWidth, then one way or another, we're
    629     // going to have to do a comparison for (2), and this happens to
    630     // take care of (1), too.
    631     if (numElementsWidth > sizeWidth) {
    632       llvm::APInt threshold(numElementsWidth, 1);
    633       threshold <<= sizeWidth;
    634 
    635       llvm::Value *thresholdV
    636         = llvm::ConstantInt::get(numElementsType, threshold);
    637 
    638       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
    639       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
    640 
    641     // Otherwise, if we're signed, we want to sext up to size_t.
    642     } else if (isSigned) {
    643       if (numElementsWidth < sizeWidth)
    644         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
    645 
    646       // If there's a non-1 type size multiplier, then we can do the
    647       // signedness check at the same time as we do the multiply
    648       // because a negative number times anything will cause an
    649       // unsigned overflow.  Otherwise, we have to do it here. But at least
    650       // in this case, we can subsume the >= minElements check.
    651       if (typeSizeMultiplier == 1)
    652         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
    653                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
    654 
    655     // Otherwise, zext up to size_t if necessary.
    656     } else if (numElementsWidth < sizeWidth) {
    657       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
    658     }
    659 
    660     assert(numElements->getType() == CGF.SizeTy);
    661 
    662     if (minElements) {
    663       // Don't allow allocation of fewer elements than we have initializers.
    664       if (!hasOverflow) {
    665         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
    666                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
    667       } else if (numElementsWidth > sizeWidth) {
    668         // The other existing overflow subsumes this check.
    669         // We do an unsigned comparison, since any signed value < -1 is
    670         // taken care of either above or below.
    671         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
    672                           CGF.Builder.CreateICmpULT(numElements,
    673                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
    674       }
    675     }
    676 
    677     size = numElements;
    678 
    679     // Multiply by the type size if necessary.  This multiplier
    680     // includes all the factors for nested arrays.
    681     //
    682     // This step also causes numElements to be scaled up by the
    683     // nested-array factor if necessary.  Overflow on this computation
    684     // can be ignored because the result shouldn't be used if
    685     // allocation fails.
    686     if (typeSizeMultiplier != 1) {
    687       llvm::Value *umul_with_overflow
    688         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
    689 
    690       llvm::Value *tsmV =
    691         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
    692       llvm::Value *result =
    693         CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
    694 
    695       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
    696       if (hasOverflow)
    697         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
    698       else
    699         hasOverflow = overflowed;
    700 
    701       size = CGF.Builder.CreateExtractValue(result, 0);
    702 
    703       // Also scale up numElements by the array size multiplier.
    704       if (arraySizeMultiplier != 1) {
    705         // If the base element type size is 1, then we can re-use the
    706         // multiply we just did.
    707         if (typeSize.isOne()) {
    708           assert(arraySizeMultiplier == typeSizeMultiplier);
    709           numElements = size;
    710 
    711         // Otherwise we need a separate multiply.
    712         } else {
    713           llvm::Value *asmV =
    714             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
    715           numElements = CGF.Builder.CreateMul(numElements, asmV);
    716         }
    717       }
    718     } else {
    719       // numElements doesn't need to be scaled.
    720       assert(arraySizeMultiplier == 1);
    721     }
    722 
    723     // Add in the cookie size if necessary.
    724     if (cookieSize != 0) {
    725       sizeWithoutCookie = size;
    726 
    727       llvm::Value *uadd_with_overflow
    728         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
    729 
    730       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
    731       llvm::Value *result =
    732         CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
    733 
    734       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
    735       if (hasOverflow)
    736         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
    737       else
    738         hasOverflow = overflowed;
    739 
    740       size = CGF.Builder.CreateExtractValue(result, 0);
    741     }
    742 
    743     // If we had any possibility of dynamic overflow, make a select to
    744     // overwrite 'size' with an all-ones value, which should cause
    745     // operator new to throw.
    746     if (hasOverflow)
    747       size = CGF.Builder.CreateSelect(hasOverflow,
    748                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
    749                                       size);
    750   }
    751 
    752   if (cookieSize == 0)
    753     sizeWithoutCookie = size;
    754   else
    755     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
    756 
    757   return size;
    758 }
    759 
    760 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
    761                                     QualType AllocType, llvm::Value *NewPtr) {
    762   // FIXME: Refactor with EmitExprAsInit.
    763   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
    764   switch (CGF.getEvaluationKind(AllocType)) {
    765   case TEK_Scalar:
    766     CGF.EmitScalarInit(Init, nullptr,
    767                        CGF.MakeAddrLValue(NewPtr, AllocType, Alignment), false);
    768     return;
    769   case TEK_Complex:
    770     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
    771                                                            Alignment),
    772                                   /*isInit*/ true);
    773     return;
    774   case TEK_Aggregate: {
    775     AggValueSlot Slot
    776       = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
    777                               AggValueSlot::IsDestructed,
    778                               AggValueSlot::DoesNotNeedGCBarriers,
    779                               AggValueSlot::IsNotAliased);
    780     CGF.EmitAggExpr(Init, Slot);
    781     return;
    782   }
    783   }
    784   llvm_unreachable("bad evaluation kind");
    785 }
    786 
    787 void CodeGenFunction::EmitNewArrayInitializer(
    788     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
    789     llvm::Value *BeginPtr, llvm::Value *NumElements,
    790     llvm::Value *AllocSizeWithoutCookie) {
    791   // If we have a type with trivial initialization and no initializer,
    792   // there's nothing to do.
    793   if (!E->hasInitializer())
    794     return;
    795 
    796   llvm::Value *CurPtr = BeginPtr;
    797 
    798   unsigned InitListElements = 0;
    799 
    800   const Expr *Init = E->getInitializer();
    801   llvm::AllocaInst *EndOfInit = nullptr;
    802   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
    803   EHScopeStack::stable_iterator Cleanup;
    804   llvm::Instruction *CleanupDominator = nullptr;
    805 
    806   // If the initializer is an initializer list, first do the explicit elements.
    807   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
    808     InitListElements = ILE->getNumInits();
    809 
    810     // If this is a multi-dimensional array new, we will initialize multiple
    811     // elements with each init list element.
    812     QualType AllocType = E->getAllocatedType();
    813     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
    814             AllocType->getAsArrayTypeUnsafe())) {
    815       unsigned AS = CurPtr->getType()->getPointerAddressSpace();
    816       ElementTy = ConvertTypeForMem(AllocType);
    817       llvm::Type *AllocPtrTy = ElementTy->getPointerTo(AS);
    818       CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
    819       InitListElements *= getContext().getConstantArrayElementCount(CAT);
    820     }
    821 
    822     // Enter a partial-destruction Cleanup if necessary.
    823     if (needsEHCleanup(DtorKind)) {
    824       // In principle we could tell the Cleanup where we are more
    825       // directly, but the control flow can get so varied here that it
    826       // would actually be quite complex.  Therefore we go through an
    827       // alloca.
    828       EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
    829       CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
    830       pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
    831                                        getDestroyer(DtorKind));
    832       Cleanup = EHStack.stable_begin();
    833     }
    834 
    835     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
    836       // Tell the cleanup that it needs to destroy up to this
    837       // element.  TODO: some of these stores can be trivially
    838       // observed to be unnecessary.
    839       if (EndOfInit)
    840         Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
    841                             EndOfInit);
    842       // FIXME: If the last initializer is an incomplete initializer list for
    843       // an array, and we have an array filler, we can fold together the two
    844       // initialization loops.
    845       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
    846                               ILE->getInit(i)->getType(), CurPtr);
    847       CurPtr = Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr, 1,
    848                                                   "array.exp.next");
    849     }
    850 
    851     // The remaining elements are filled with the array filler expression.
    852     Init = ILE->getArrayFiller();
    853 
    854     // Extract the initializer for the individual array elements by pulling
    855     // out the array filler from all the nested initializer lists. This avoids
    856     // generating a nested loop for the initialization.
    857     while (Init && Init->getType()->isConstantArrayType()) {
    858       auto *SubILE = dyn_cast<InitListExpr>(Init);
    859       if (!SubILE)
    860         break;
    861       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
    862       Init = SubILE->getArrayFiller();
    863     }
    864 
    865     // Switch back to initializing one base element at a time.
    866     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
    867   }
    868 
    869   // Attempt to perform zero-initialization using memset.
    870   auto TryMemsetInitialization = [&]() -> bool {
    871     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
    872     // we can initialize with a memset to -1.
    873     if (!CGM.getTypes().isZeroInitializable(ElementType))
    874       return false;
    875 
    876     // Optimization: since zero initialization will just set the memory
    877     // to all zeroes, generate a single memset to do it in one shot.
    878 
    879     // Subtract out the size of any elements we've already initialized.
    880     auto *RemainingSize = AllocSizeWithoutCookie;
    881     if (InitListElements) {
    882       // We know this can't overflow; we check this when doing the allocation.
    883       auto *InitializedSize = llvm::ConstantInt::get(
    884           RemainingSize->getType(),
    885           getContext().getTypeSizeInChars(ElementType).getQuantity() *
    886               InitListElements);
    887       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
    888     }
    889 
    890     // Create the memset.
    891     CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
    892     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
    893                          Alignment.getQuantity(), false);
    894     return true;
    895   };
    896 
    897   // If all elements have already been initialized, skip any further
    898   // initialization.
    899   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
    900   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
    901     // If there was a Cleanup, deactivate it.
    902     if (CleanupDominator)
    903       DeactivateCleanupBlock(Cleanup, CleanupDominator);
    904     return;
    905   }
    906 
    907   assert(Init && "have trailing elements to initialize but no initializer");
    908 
    909   // If this is a constructor call, try to optimize it out, and failing that
    910   // emit a single loop to initialize all remaining elements.
    911   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
    912     CXXConstructorDecl *Ctor = CCE->getConstructor();
    913     if (Ctor->isTrivial()) {
    914       // If new expression did not specify value-initialization, then there
    915       // is no initialization.
    916       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
    917         return;
    918 
    919       if (TryMemsetInitialization())
    920         return;
    921     }
    922 
    923     // Store the new Cleanup position for irregular Cleanups.
    924     //
    925     // FIXME: Share this cleanup with the constructor call emission rather than
    926     // having it create a cleanup of its own.
    927     if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
    928 
    929     // Emit a constructor call loop to initialize the remaining elements.
    930     if (InitListElements)
    931       NumElements = Builder.CreateSub(
    932           NumElements,
    933           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
    934     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
    935                                CCE->requiresZeroInitialization());
    936     return;
    937   }
    938 
    939   // If this is value-initialization, we can usually use memset.
    940   ImplicitValueInitExpr IVIE(ElementType);
    941   if (isa<ImplicitValueInitExpr>(Init)) {
    942     if (TryMemsetInitialization())
    943       return;
    944 
    945     // Switch to an ImplicitValueInitExpr for the element type. This handles
    946     // only one case: multidimensional array new of pointers to members. In
    947     // all other cases, we already have an initializer for the array element.
    948     Init = &IVIE;
    949   }
    950 
    951   // At this point we should have found an initializer for the individual
    952   // elements of the array.
    953   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
    954          "got wrong type of element to initialize");
    955 
    956   // If we have an empty initializer list, we can usually use memset.
    957   if (auto *ILE = dyn_cast<InitListExpr>(Init))
    958     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
    959       return;
    960 
    961   // Create the loop blocks.
    962   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
    963   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
    964   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
    965 
    966   // Find the end of the array, hoisted out of the loop.
    967   llvm::Value *EndPtr =
    968     Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
    969 
    970   // If the number of elements isn't constant, we have to now check if there is
    971   // anything left to initialize.
    972   if (!ConstNum) {
    973     llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
    974                                                 "array.isempty");
    975     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
    976   }
    977 
    978   // Enter the loop.
    979   EmitBlock(LoopBB);
    980 
    981   // Set up the current-element phi.
    982   llvm::PHINode *CurPtrPhi =
    983     Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
    984   CurPtrPhi->addIncoming(CurPtr, EntryBB);
    985   CurPtr = CurPtrPhi;
    986 
    987   // Store the new Cleanup position for irregular Cleanups.
    988   if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
    989 
    990   // Enter a partial-destruction Cleanup if necessary.
    991   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
    992     pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
    993                                    getDestroyer(DtorKind));
    994     Cleanup = EHStack.stable_begin();
    995     CleanupDominator = Builder.CreateUnreachable();
    996   }
    997 
    998   // Emit the initializer into this element.
    999   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
   1000 
   1001   // Leave the Cleanup if we entered one.
   1002   if (CleanupDominator) {
   1003     DeactivateCleanupBlock(Cleanup, CleanupDominator);
   1004     CleanupDominator->eraseFromParent();
   1005   }
   1006 
   1007   // Advance to the next element by adjusting the pointer type as necessary.
   1008   llvm::Value *NextPtr =
   1009       Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr, 1, "array.next");
   1010 
   1011   // Check whether we've gotten to the end of the array and, if so,
   1012   // exit the loop.
   1013   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
   1014   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
   1015   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
   1016 
   1017   EmitBlock(ContBB);
   1018 }
   1019 
   1020 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
   1021                                QualType ElementType, llvm::Type *ElementTy,
   1022                                llvm::Value *NewPtr, llvm::Value *NumElements,
   1023                                llvm::Value *AllocSizeWithoutCookie) {
   1024   ApplyDebugLocation DL(CGF, E);
   1025   if (E->isArray())
   1026     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
   1027                                 AllocSizeWithoutCookie);
   1028   else if (const Expr *Init = E->getInitializer())
   1029     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
   1030 }
   1031 
   1032 /// Emit a call to an operator new or operator delete function, as implicitly
   1033 /// created by new-expressions and delete-expressions.
   1034 static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
   1035                                 const FunctionDecl *Callee,
   1036                                 const FunctionProtoType *CalleeType,
   1037                                 const CallArgList &Args) {
   1038   llvm::Instruction *CallOrInvoke;
   1039   llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
   1040   RValue RV =
   1041       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
   1042                        Args, CalleeType, /*chainCall=*/false),
   1043                    CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
   1044 
   1045   /// C++1y [expr.new]p10:
   1046   ///   [In a new-expression,] an implementation is allowed to omit a call
   1047   ///   to a replaceable global allocation function.
   1048   ///
   1049   /// We model such elidable calls with the 'builtin' attribute.
   1050   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
   1051   if (Callee->isReplaceableGlobalAllocationFunction() &&
   1052       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
   1053     // FIXME: Add addAttribute to CallSite.
   1054     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
   1055       CI->addAttribute(llvm::AttributeSet::FunctionIndex,
   1056                        llvm::Attribute::Builtin);
   1057     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
   1058       II->addAttribute(llvm::AttributeSet::FunctionIndex,
   1059                        llvm::Attribute::Builtin);
   1060     else
   1061       llvm_unreachable("unexpected kind of call instruction");
   1062   }
   1063 
   1064   return RV;
   1065 }
   1066 
   1067 RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
   1068                                                  const Expr *Arg,
   1069                                                  bool IsDelete) {
   1070   CallArgList Args;
   1071   const Stmt *ArgS = Arg;
   1072   EmitCallArgs(Args, *Type->param_type_begin(),
   1073                ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
   1074   // Find the allocation or deallocation function that we're calling.
   1075   ASTContext &Ctx = getContext();
   1076   DeclarationName Name = Ctx.DeclarationNames
   1077       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
   1078   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
   1079     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
   1080       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
   1081         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
   1082   llvm_unreachable("predeclared global operator new/delete is missing");
   1083 }
   1084 
   1085 namespace {
   1086   /// A cleanup to call the given 'operator delete' function upon
   1087   /// abnormal exit from a new expression.
   1088   class CallDeleteDuringNew : public EHScopeStack::Cleanup {
   1089     size_t NumPlacementArgs;
   1090     const FunctionDecl *OperatorDelete;
   1091     llvm::Value *Ptr;
   1092     llvm::Value *AllocSize;
   1093 
   1094     RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
   1095 
   1096   public:
   1097     static size_t getExtraSize(size_t NumPlacementArgs) {
   1098       return NumPlacementArgs * sizeof(RValue);
   1099     }
   1100 
   1101     CallDeleteDuringNew(size_t NumPlacementArgs,
   1102                         const FunctionDecl *OperatorDelete,
   1103                         llvm::Value *Ptr,
   1104                         llvm::Value *AllocSize)
   1105       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
   1106         Ptr(Ptr), AllocSize(AllocSize) {}
   1107 
   1108     void setPlacementArg(unsigned I, RValue Arg) {
   1109       assert(I < NumPlacementArgs && "index out of range");
   1110       getPlacementArgs()[I] = Arg;
   1111     }
   1112 
   1113     void Emit(CodeGenFunction &CGF, Flags flags) override {
   1114       const FunctionProtoType *FPT
   1115         = OperatorDelete->getType()->getAs<FunctionProtoType>();
   1116       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
   1117              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
   1118 
   1119       CallArgList DeleteArgs;
   1120 
   1121       // The first argument is always a void*.
   1122       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
   1123       DeleteArgs.add(RValue::get(Ptr), *AI++);
   1124 
   1125       // A member 'operator delete' can take an extra 'size_t' argument.
   1126       if (FPT->getNumParams() == NumPlacementArgs + 2)
   1127         DeleteArgs.add(RValue::get(AllocSize), *AI++);
   1128 
   1129       // Pass the rest of the arguments, which must match exactly.
   1130       for (unsigned I = 0; I != NumPlacementArgs; ++I)
   1131         DeleteArgs.add(getPlacementArgs()[I], *AI++);
   1132 
   1133       // Call 'operator delete'.
   1134       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
   1135     }
   1136   };
   1137 
   1138   /// A cleanup to call the given 'operator delete' function upon
   1139   /// abnormal exit from a new expression when the new expression is
   1140   /// conditional.
   1141   class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
   1142     size_t NumPlacementArgs;
   1143     const FunctionDecl *OperatorDelete;
   1144     DominatingValue<RValue>::saved_type Ptr;
   1145     DominatingValue<RValue>::saved_type AllocSize;
   1146 
   1147     DominatingValue<RValue>::saved_type *getPlacementArgs() {
   1148       return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
   1149     }
   1150 
   1151   public:
   1152     static size_t getExtraSize(size_t NumPlacementArgs) {
   1153       return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
   1154     }
   1155 
   1156     CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
   1157                                    const FunctionDecl *OperatorDelete,
   1158                                    DominatingValue<RValue>::saved_type Ptr,
   1159                               DominatingValue<RValue>::saved_type AllocSize)
   1160       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
   1161         Ptr(Ptr), AllocSize(AllocSize) {}
   1162 
   1163     void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
   1164       assert(I < NumPlacementArgs && "index out of range");
   1165       getPlacementArgs()[I] = Arg;
   1166     }
   1167 
   1168     void Emit(CodeGenFunction &CGF, Flags flags) override {
   1169       const FunctionProtoType *FPT
   1170         = OperatorDelete->getType()->getAs<FunctionProtoType>();
   1171       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
   1172              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
   1173 
   1174       CallArgList DeleteArgs;
   1175 
   1176       // The first argument is always a void*.
   1177       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
   1178       DeleteArgs.add(Ptr.restore(CGF), *AI++);
   1179 
   1180       // A member 'operator delete' can take an extra 'size_t' argument.
   1181       if (FPT->getNumParams() == NumPlacementArgs + 2) {
   1182         RValue RV = AllocSize.restore(CGF);
   1183         DeleteArgs.add(RV, *AI++);
   1184       }
   1185 
   1186       // Pass the rest of the arguments, which must match exactly.
   1187       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
   1188         RValue RV = getPlacementArgs()[I].restore(CGF);
   1189         DeleteArgs.add(RV, *AI++);
   1190       }
   1191 
   1192       // Call 'operator delete'.
   1193       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
   1194     }
   1195   };
   1196 }
   1197 
   1198 /// Enter a cleanup to call 'operator delete' if the initializer in a
   1199 /// new-expression throws.
   1200 static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
   1201                                   const CXXNewExpr *E,
   1202                                   llvm::Value *NewPtr,
   1203                                   llvm::Value *AllocSize,
   1204                                   const CallArgList &NewArgs) {
   1205   // If we're not inside a conditional branch, then the cleanup will
   1206   // dominate and we can do the easier (and more efficient) thing.
   1207   if (!CGF.isInConditionalBranch()) {
   1208     CallDeleteDuringNew *Cleanup = CGF.EHStack
   1209       .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
   1210                                                  E->getNumPlacementArgs(),
   1211                                                  E->getOperatorDelete(),
   1212                                                  NewPtr, AllocSize);
   1213     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
   1214       Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
   1215 
   1216     return;
   1217   }
   1218 
   1219   // Otherwise, we need to save all this stuff.
   1220   DominatingValue<RValue>::saved_type SavedNewPtr =
   1221     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
   1222   DominatingValue<RValue>::saved_type SavedAllocSize =
   1223     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
   1224 
   1225   CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
   1226     .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
   1227                                                  E->getNumPlacementArgs(),
   1228                                                  E->getOperatorDelete(),
   1229                                                  SavedNewPtr,
   1230                                                  SavedAllocSize);
   1231   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
   1232     Cleanup->setPlacementArg(I,
   1233                      DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
   1234 
   1235   CGF.initFullExprCleanup();
   1236 }
   1237 
   1238 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
   1239   // The element type being allocated.
   1240   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
   1241 
   1242   // 1. Build a call to the allocation function.
   1243   FunctionDecl *allocator = E->getOperatorNew();
   1244   const FunctionProtoType *allocatorType =
   1245     allocator->getType()->castAs<FunctionProtoType>();
   1246 
   1247   CallArgList allocatorArgs;
   1248 
   1249   // The allocation size is the first argument.
   1250   QualType sizeType = getContext().getSizeType();
   1251 
   1252   // If there is a brace-initializer, cannot allocate fewer elements than inits.
   1253   unsigned minElements = 0;
   1254   if (E->isArray() && E->hasInitializer()) {
   1255     if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
   1256       minElements = ILE->getNumInits();
   1257   }
   1258 
   1259   llvm::Value *numElements = nullptr;
   1260   llvm::Value *allocSizeWithoutCookie = nullptr;
   1261   llvm::Value *allocSize =
   1262     EmitCXXNewAllocSize(*this, E, minElements, numElements,
   1263                         allocSizeWithoutCookie);
   1264 
   1265   allocatorArgs.add(RValue::get(allocSize), sizeType);
   1266 
   1267   // We start at 1 here because the first argument (the allocation size)
   1268   // has already been emitted.
   1269   EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
   1270                E->placement_arg_end(), /* CalleeDecl */ nullptr,
   1271                /*ParamsToSkip*/ 1);
   1272 
   1273   // Emit the allocation call.  If the allocator is a global placement
   1274   // operator, just "inline" it directly.
   1275   RValue RV;
   1276   if (allocator->isReservedGlobalPlacementOperator()) {
   1277     assert(allocatorArgs.size() == 2);
   1278     RV = allocatorArgs[1].RV;
   1279     // TODO: kill any unnecessary computations done for the size
   1280     // argument.
   1281   } else {
   1282     RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
   1283   }
   1284 
   1285   // Emit a null check on the allocation result if the allocation
   1286   // function is allowed to return null (because it has a non-throwing
   1287   // exception spec or is the reserved placement new) and we have an
   1288   // interesting initializer.
   1289   bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
   1290     (!allocType.isPODType(getContext()) || E->hasInitializer());
   1291 
   1292   llvm::BasicBlock *nullCheckBB = nullptr;
   1293   llvm::BasicBlock *contBB = nullptr;
   1294 
   1295   llvm::Value *allocation = RV.getScalarVal();
   1296   unsigned AS = allocation->getType()->getPointerAddressSpace();
   1297 
   1298   // The null-check means that the initializer is conditionally
   1299   // evaluated.
   1300   ConditionalEvaluation conditional(*this);
   1301 
   1302   if (nullCheck) {
   1303     conditional.begin(*this);
   1304 
   1305     nullCheckBB = Builder.GetInsertBlock();
   1306     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
   1307     contBB = createBasicBlock("new.cont");
   1308 
   1309     llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
   1310     Builder.CreateCondBr(isNull, contBB, notNullBB);
   1311     EmitBlock(notNullBB);
   1312   }
   1313 
   1314   // If there's an operator delete, enter a cleanup to call it if an
   1315   // exception is thrown.
   1316   EHScopeStack::stable_iterator operatorDeleteCleanup;
   1317   llvm::Instruction *cleanupDominator = nullptr;
   1318   if (E->getOperatorDelete() &&
   1319       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
   1320     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
   1321     operatorDeleteCleanup = EHStack.stable_begin();
   1322     cleanupDominator = Builder.CreateUnreachable();
   1323   }
   1324 
   1325   assert((allocSize == allocSizeWithoutCookie) ==
   1326          CalculateCookiePadding(*this, E).isZero());
   1327   if (allocSize != allocSizeWithoutCookie) {
   1328     assert(E->isArray());
   1329     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
   1330                                                        numElements,
   1331                                                        E, allocType);
   1332   }
   1333 
   1334   llvm::Type *elementTy = ConvertTypeForMem(allocType);
   1335   llvm::Type *elementPtrTy = elementTy->getPointerTo(AS);
   1336   llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
   1337 
   1338   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
   1339                      allocSizeWithoutCookie);
   1340   if (E->isArray()) {
   1341     // NewPtr is a pointer to the base element type.  If we're
   1342     // allocating an array of arrays, we'll need to cast back to the
   1343     // array pointer type.
   1344     llvm::Type *resultType = ConvertTypeForMem(E->getType());
   1345     if (result->getType() != resultType)
   1346       result = Builder.CreateBitCast(result, resultType);
   1347   }
   1348 
   1349   // Deactivate the 'operator delete' cleanup if we finished
   1350   // initialization.
   1351   if (operatorDeleteCleanup.isValid()) {
   1352     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
   1353     cleanupDominator->eraseFromParent();
   1354   }
   1355 
   1356   if (nullCheck) {
   1357     conditional.end(*this);
   1358 
   1359     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
   1360     EmitBlock(contBB);
   1361 
   1362     llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
   1363     PHI->addIncoming(result, notNullBB);
   1364     PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
   1365                      nullCheckBB);
   1366 
   1367     result = PHI;
   1368   }
   1369 
   1370   return result;
   1371 }
   1372 
   1373 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
   1374                                      llvm::Value *Ptr,
   1375                                      QualType DeleteTy) {
   1376   assert(DeleteFD->getOverloadedOperator() == OO_Delete);
   1377 
   1378   const FunctionProtoType *DeleteFTy =
   1379     DeleteFD->getType()->getAs<FunctionProtoType>();
   1380 
   1381   CallArgList DeleteArgs;
   1382 
   1383   // Check if we need to pass the size to the delete operator.
   1384   llvm::Value *Size = nullptr;
   1385   QualType SizeTy;
   1386   if (DeleteFTy->getNumParams() == 2) {
   1387     SizeTy = DeleteFTy->getParamType(1);
   1388     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
   1389     Size = llvm::ConstantInt::get(ConvertType(SizeTy),
   1390                                   DeleteTypeSize.getQuantity());
   1391   }
   1392 
   1393   QualType ArgTy = DeleteFTy->getParamType(0);
   1394   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
   1395   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
   1396 
   1397   if (Size)
   1398     DeleteArgs.add(RValue::get(Size), SizeTy);
   1399 
   1400   // Emit the call to delete.
   1401   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
   1402 }
   1403 
   1404 namespace {
   1405   /// Calls the given 'operator delete' on a single object.
   1406   struct CallObjectDelete : EHScopeStack::Cleanup {
   1407     llvm::Value *Ptr;
   1408     const FunctionDecl *OperatorDelete;
   1409     QualType ElementType;
   1410 
   1411     CallObjectDelete(llvm::Value *Ptr,
   1412                      const FunctionDecl *OperatorDelete,
   1413                      QualType ElementType)
   1414       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
   1415 
   1416     void Emit(CodeGenFunction &CGF, Flags flags) override {
   1417       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
   1418     }
   1419   };
   1420 }
   1421 
   1422 void
   1423 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
   1424                                              llvm::Value *CompletePtr,
   1425                                              QualType ElementType) {
   1426   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
   1427                                         OperatorDelete, ElementType);
   1428 }
   1429 
   1430 /// Emit the code for deleting a single object.
   1431 static void EmitObjectDelete(CodeGenFunction &CGF,
   1432                              const CXXDeleteExpr *DE,
   1433                              llvm::Value *Ptr,
   1434                              QualType ElementType) {
   1435   // Find the destructor for the type, if applicable.  If the
   1436   // destructor is virtual, we'll just emit the vcall and return.
   1437   const CXXDestructorDecl *Dtor = nullptr;
   1438   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
   1439     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
   1440     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
   1441       Dtor = RD->getDestructor();
   1442 
   1443       if (Dtor->isVirtual()) {
   1444         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
   1445                                                     Dtor);
   1446         return;
   1447       }
   1448     }
   1449   }
   1450 
   1451   // Make sure that we call delete even if the dtor throws.
   1452   // This doesn't have to a conditional cleanup because we're going
   1453   // to pop it off in a second.
   1454   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
   1455   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
   1456                                             Ptr, OperatorDelete, ElementType);
   1457 
   1458   if (Dtor)
   1459     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
   1460                               /*ForVirtualBase=*/false,
   1461                               /*Delegating=*/false,
   1462                               Ptr);
   1463   else if (CGF.getLangOpts().ObjCAutoRefCount &&
   1464            ElementType->isObjCLifetimeType()) {
   1465     switch (ElementType.getObjCLifetime()) {
   1466     case Qualifiers::OCL_None:
   1467     case Qualifiers::OCL_ExplicitNone:
   1468     case Qualifiers::OCL_Autoreleasing:
   1469       break;
   1470 
   1471     case Qualifiers::OCL_Strong: {
   1472       // Load the pointer value.
   1473       llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
   1474                                              ElementType.isVolatileQualified());
   1475 
   1476       CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
   1477       break;
   1478     }
   1479 
   1480     case Qualifiers::OCL_Weak:
   1481       CGF.EmitARCDestroyWeak(Ptr);
   1482       break;
   1483     }
   1484   }
   1485 
   1486   CGF.PopCleanupBlock();
   1487 }
   1488 
   1489 namespace {
   1490   /// Calls the given 'operator delete' on an array of objects.
   1491   struct CallArrayDelete : EHScopeStack::Cleanup {
   1492     llvm::Value *Ptr;
   1493     const FunctionDecl *OperatorDelete;
   1494     llvm::Value *NumElements;
   1495     QualType ElementType;
   1496     CharUnits CookieSize;
   1497 
   1498     CallArrayDelete(llvm::Value *Ptr,
   1499                     const FunctionDecl *OperatorDelete,
   1500                     llvm::Value *NumElements,
   1501                     QualType ElementType,
   1502                     CharUnits CookieSize)
   1503       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
   1504         ElementType(ElementType), CookieSize(CookieSize) {}
   1505 
   1506     void Emit(CodeGenFunction &CGF, Flags flags) override {
   1507       const FunctionProtoType *DeleteFTy =
   1508         OperatorDelete->getType()->getAs<FunctionProtoType>();
   1509       assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
   1510 
   1511       CallArgList Args;
   1512 
   1513       // Pass the pointer as the first argument.
   1514       QualType VoidPtrTy = DeleteFTy->getParamType(0);
   1515       llvm::Value *DeletePtr
   1516         = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
   1517       Args.add(RValue::get(DeletePtr), VoidPtrTy);
   1518 
   1519       // Pass the original requested size as the second argument.
   1520       if (DeleteFTy->getNumParams() == 2) {
   1521         QualType size_t = DeleteFTy->getParamType(1);
   1522         llvm::IntegerType *SizeTy
   1523           = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
   1524 
   1525         CharUnits ElementTypeSize =
   1526           CGF.CGM.getContext().getTypeSizeInChars(ElementType);
   1527 
   1528         // The size of an element, multiplied by the number of elements.
   1529         llvm::Value *Size
   1530           = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
   1531         Size = CGF.Builder.CreateMul(Size, NumElements);
   1532 
   1533         // Plus the size of the cookie if applicable.
   1534         if (!CookieSize.isZero()) {
   1535           llvm::Value *CookieSizeV
   1536             = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
   1537           Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
   1538         }
   1539 
   1540         Args.add(RValue::get(Size), size_t);
   1541       }
   1542 
   1543       // Emit the call to delete.
   1544       EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
   1545     }
   1546   };
   1547 }
   1548 
   1549 /// Emit the code for deleting an array of objects.
   1550 static void EmitArrayDelete(CodeGenFunction &CGF,
   1551                             const CXXDeleteExpr *E,
   1552                             llvm::Value *deletedPtr,
   1553                             QualType elementType) {
   1554   llvm::Value *numElements = nullptr;
   1555   llvm::Value *allocatedPtr = nullptr;
   1556   CharUnits cookieSize;
   1557   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
   1558                                       numElements, allocatedPtr, cookieSize);
   1559 
   1560   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
   1561 
   1562   // Make sure that we call delete even if one of the dtors throws.
   1563   const FunctionDecl *operatorDelete = E->getOperatorDelete();
   1564   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
   1565                                            allocatedPtr, operatorDelete,
   1566                                            numElements, elementType,
   1567                                            cookieSize);
   1568 
   1569   // Destroy the elements.
   1570   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
   1571     assert(numElements && "no element count for a type with a destructor!");
   1572 
   1573     llvm::Value *arrayEnd =
   1574       CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
   1575 
   1576     // Note that it is legal to allocate a zero-length array, and we
   1577     // can never fold the check away because the length should always
   1578     // come from a cookie.
   1579     CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
   1580                          CGF.getDestroyer(dtorKind),
   1581                          /*checkZeroLength*/ true,
   1582                          CGF.needsEHCleanup(dtorKind));
   1583   }
   1584 
   1585   // Pop the cleanup block.
   1586   CGF.PopCleanupBlock();
   1587 }
   1588 
   1589 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
   1590   const Expr *Arg = E->getArgument();
   1591   llvm::Value *Ptr = EmitScalarExpr(Arg);
   1592 
   1593   // Null check the pointer.
   1594   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
   1595   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
   1596 
   1597   llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
   1598 
   1599   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
   1600   EmitBlock(DeleteNotNull);
   1601 
   1602   // We might be deleting a pointer to array.  If so, GEP down to the
   1603   // first non-array element.
   1604   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
   1605   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
   1606   if (DeleteTy->isConstantArrayType()) {
   1607     llvm::Value *Zero = Builder.getInt32(0);
   1608     SmallVector<llvm::Value*,8> GEP;
   1609 
   1610     GEP.push_back(Zero); // point at the outermost array
   1611 
   1612     // For each layer of array type we're pointing at:
   1613     while (const ConstantArrayType *Arr
   1614              = getContext().getAsConstantArrayType(DeleteTy)) {
   1615       // 1. Unpeel the array type.
   1616       DeleteTy = Arr->getElementType();
   1617 
   1618       // 2. GEP to the first element of the array.
   1619       GEP.push_back(Zero);
   1620     }
   1621 
   1622     Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
   1623   }
   1624 
   1625   assert(ConvertTypeForMem(DeleteTy) ==
   1626          cast<llvm::PointerType>(Ptr->getType())->getElementType());
   1627 
   1628   if (E->isArrayForm()) {
   1629     EmitArrayDelete(*this, E, Ptr, DeleteTy);
   1630   } else {
   1631     EmitObjectDelete(*this, E, Ptr, DeleteTy);
   1632   }
   1633 
   1634   EmitBlock(DeleteEnd);
   1635 }
   1636 
   1637 static bool isGLValueFromPointerDeref(const Expr *E) {
   1638   E = E->IgnoreParens();
   1639 
   1640   if (const auto *CE = dyn_cast<CastExpr>(E)) {
   1641     if (!CE->getSubExpr()->isGLValue())
   1642       return false;
   1643     return isGLValueFromPointerDeref(CE->getSubExpr());
   1644   }
   1645 
   1646   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
   1647     return isGLValueFromPointerDeref(OVE->getSourceExpr());
   1648 
   1649   if (const auto *BO = dyn_cast<BinaryOperator>(E))
   1650     if (BO->getOpcode() == BO_Comma)
   1651       return isGLValueFromPointerDeref(BO->getRHS());
   1652 
   1653   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
   1654     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
   1655            isGLValueFromPointerDeref(ACO->getFalseExpr());
   1656 
   1657   // C++11 [expr.sub]p1:
   1658   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
   1659   if (isa<ArraySubscriptExpr>(E))
   1660     return true;
   1661 
   1662   if (const auto *UO = dyn_cast<UnaryOperator>(E))
   1663     if (UO->getOpcode() == UO_Deref)
   1664       return true;
   1665 
   1666   return false;
   1667 }
   1668 
   1669 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
   1670                                          llvm::Type *StdTypeInfoPtrTy) {
   1671   // Get the vtable pointer.
   1672   llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
   1673 
   1674   // C++ [expr.typeid]p2:
   1675   //   If the glvalue expression is obtained by applying the unary * operator to
   1676   //   a pointer and the pointer is a null pointer value, the typeid expression
   1677   //   throws the std::bad_typeid exception.
   1678   //
   1679   // However, this paragraph's intent is not clear.  We choose a very generous
   1680   // interpretation which implores us to consider comma operators, conditional
   1681   // operators, parentheses and other such constructs.
   1682   QualType SrcRecordTy = E->getType();
   1683   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
   1684           isGLValueFromPointerDeref(E), SrcRecordTy)) {
   1685     llvm::BasicBlock *BadTypeidBlock =
   1686         CGF.createBasicBlock("typeid.bad_typeid");
   1687     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
   1688 
   1689     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
   1690     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
   1691 
   1692     CGF.EmitBlock(BadTypeidBlock);
   1693     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
   1694     CGF.EmitBlock(EndBlock);
   1695   }
   1696 
   1697   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
   1698                                         StdTypeInfoPtrTy);
   1699 }
   1700 
   1701 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
   1702   llvm::Type *StdTypeInfoPtrTy =
   1703     ConvertType(E->getType())->getPointerTo();
   1704 
   1705   if (E->isTypeOperand()) {
   1706     llvm::Constant *TypeInfo =
   1707         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
   1708     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
   1709   }
   1710 
   1711   // C++ [expr.typeid]p2:
   1712   //   When typeid is applied to a glvalue expression whose type is a
   1713   //   polymorphic class type, the result refers to a std::type_info object
   1714   //   representing the type of the most derived object (that is, the dynamic
   1715   //   type) to which the glvalue refers.
   1716   if (E->isPotentiallyEvaluated())
   1717     return EmitTypeidFromVTable(*this, E->getExprOperand(),
   1718                                 StdTypeInfoPtrTy);
   1719 
   1720   QualType OperandTy = E->getExprOperand()->getType();
   1721   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
   1722                                StdTypeInfoPtrTy);
   1723 }
   1724 
   1725 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
   1726                                           QualType DestTy) {
   1727   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
   1728   if (DestTy->isPointerType())
   1729     return llvm::Constant::getNullValue(DestLTy);
   1730 
   1731   /// C++ [expr.dynamic.cast]p9:
   1732   ///   A failed cast to reference type throws std::bad_cast
   1733   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
   1734     return nullptr;
   1735 
   1736   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
   1737   return llvm::UndefValue::get(DestLTy);
   1738 }
   1739 
   1740 llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
   1741                                               const CXXDynamicCastExpr *DCE) {
   1742   QualType DestTy = DCE->getTypeAsWritten();
   1743 
   1744   if (DCE->isAlwaysNull())
   1745     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
   1746       return T;
   1747 
   1748   QualType SrcTy = DCE->getSubExpr()->getType();
   1749 
   1750   // C++ [expr.dynamic.cast]p7:
   1751   //   If T is "pointer to cv void," then the result is a pointer to the most
   1752   //   derived object pointed to by v.
   1753   const PointerType *DestPTy = DestTy->getAs<PointerType>();
   1754 
   1755   bool isDynamicCastToVoid;
   1756   QualType SrcRecordTy;
   1757   QualType DestRecordTy;
   1758   if (DestPTy) {
   1759     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
   1760     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
   1761     DestRecordTy = DestPTy->getPointeeType();
   1762   } else {
   1763     isDynamicCastToVoid = false;
   1764     SrcRecordTy = SrcTy;
   1765     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
   1766   }
   1767 
   1768   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
   1769 
   1770   // C++ [expr.dynamic.cast]p4:
   1771   //   If the value of v is a null pointer value in the pointer case, the result
   1772   //   is the null pointer value of type T.
   1773   bool ShouldNullCheckSrcValue =
   1774       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
   1775                                                          SrcRecordTy);
   1776 
   1777   llvm::BasicBlock *CastNull = nullptr;
   1778   llvm::BasicBlock *CastNotNull = nullptr;
   1779   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
   1780 
   1781   if (ShouldNullCheckSrcValue) {
   1782     CastNull = createBasicBlock("dynamic_cast.null");
   1783     CastNotNull = createBasicBlock("dynamic_cast.notnull");
   1784 
   1785     llvm::Value *IsNull = Builder.CreateIsNull(Value);
   1786     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
   1787     EmitBlock(CastNotNull);
   1788   }
   1789 
   1790   if (isDynamicCastToVoid) {
   1791     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
   1792                                                   DestTy);
   1793   } else {
   1794     assert(DestRecordTy->isRecordType() &&
   1795            "destination type must be a record type!");
   1796     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
   1797                                                 DestTy, DestRecordTy, CastEnd);
   1798   }
   1799 
   1800   if (ShouldNullCheckSrcValue) {
   1801     EmitBranch(CastEnd);
   1802 
   1803     EmitBlock(CastNull);
   1804     EmitBranch(CastEnd);
   1805   }
   1806 
   1807   EmitBlock(CastEnd);
   1808 
   1809   if (ShouldNullCheckSrcValue) {
   1810     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
   1811     PHI->addIncoming(Value, CastNotNull);
   1812     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
   1813 
   1814     Value = PHI;
   1815   }
   1816 
   1817   return Value;
   1818 }
   1819 
   1820 void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
   1821   RunCleanupsScope Scope(*this);
   1822   LValue SlotLV =
   1823       MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
   1824 
   1825   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
   1826   for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
   1827                                          e = E->capture_init_end();
   1828        i != e; ++i, ++CurField) {
   1829     // Emit initialization
   1830     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
   1831     if (CurField->hasCapturedVLAType()) {
   1832       auto VAT = CurField->getCapturedVLAType();
   1833       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
   1834     } else {
   1835       ArrayRef<VarDecl *> ArrayIndexes;
   1836       if (CurField->getType()->isArrayType())
   1837         ArrayIndexes = E->getCaptureInitIndexVars(i);
   1838       EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
   1839     }
   1840   }
   1841 }
   1842