clang API Documentation

CGExprCXX.cpp
Go to the documentation of this file.
00001 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code dealing with code generation of C++ expressions
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenFunction.h"
00015 #include "CGCUDARuntime.h"
00016 #include "CGCXXABI.h"
00017 #include "CGDebugInfo.h"
00018 #include "CGObjCRuntime.h"
00019 #include "clang/CodeGen/CGFunctionInfo.h"
00020 #include "clang/Frontend/CodeGenOptions.h"
00021 #include "llvm/IR/CallSite.h"
00022 #include "llvm/IR/Intrinsics.h"
00023 
00024 using namespace clang;
00025 using namespace CodeGen;
00026 
00027 static RequiredArgs commonEmitCXXMemberOrOperatorCall(
00028     CodeGenFunction &CGF, const CXXMethodDecl *MD, llvm::Value *Callee,
00029     ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam,
00030     QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args) {
00031   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
00032          isa<CXXOperatorCallExpr>(CE));
00033   assert(MD->isInstance() &&
00034          "Trying to emit a member or operator call expr on a static method!");
00035 
00036   // C++11 [class.mfct.non-static]p2:
00037   //   If a non-static member function of a class X is called for an object that
00038   //   is not of type X, or of a type derived from X, the behavior is undefined.
00039   SourceLocation CallLoc;
00040   if (CE)
00041     CallLoc = CE->getExprLoc();
00042   CGF.EmitTypeCheck(
00043       isa<CXXConstructorDecl>(MD) ? CodeGenFunction::TCK_ConstructorCall
00044                                   : CodeGenFunction::TCK_MemberCall,
00045       CallLoc, This, CGF.getContext().getRecordType(MD->getParent()));
00046 
00047   // Push the this ptr.
00048   Args.add(RValue::get(This), MD->getThisType(CGF.getContext()));
00049 
00050   // If there is an implicit parameter (e.g. VTT), emit it.
00051   if (ImplicitParam) {
00052     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
00053   }
00054 
00055   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
00056   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
00057 
00058   // And the rest of the call args.
00059   if (CE) {
00060     // Special case: skip first argument of CXXOperatorCall (it is "this").
00061     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
00062     CGF.EmitCallArgs(Args, FPT, CE->arg_begin() + ArgsToSkip, CE->arg_end(),
00063                      CE->getDirectCallee());
00064   } else {
00065     assert(
00066         FPT->getNumParams() == 0 &&
00067         "No CallExpr specified for function with non-zero number of arguments");
00068   }
00069   return required;
00070 }
00071 
00072 RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
00073     const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
00074     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
00075     const CallExpr *CE) {
00076   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
00077   CallArgList Args;
00078   RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
00079       *this, MD, Callee, ReturnValue, This, ImplicitParam, ImplicitParamTy, CE,
00080       Args);
00081   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
00082                   Callee, ReturnValue, Args, MD);
00083 }
00084 
00085 RValue CodeGenFunction::EmitCXXStructorCall(
00086     const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
00087     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
00088     const CallExpr *CE, StructorType Type) {
00089   CallArgList Args;
00090   commonEmitCXXMemberOrOperatorCall(*this, MD, Callee, ReturnValue, This,
00091                                     ImplicitParam, ImplicitParamTy, CE, Args);
00092   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(MD, Type),
00093                   Callee, ReturnValue, Args, MD);
00094 }
00095 
00096 static CXXRecordDecl *getCXXRecord(const Expr *E) {
00097   QualType T = E->getType();
00098   if (const PointerType *PTy = T->getAs<PointerType>())
00099     T = PTy->getPointeeType();
00100   const RecordType *Ty = T->castAs<RecordType>();
00101   return cast<CXXRecordDecl>(Ty->getDecl());
00102 }
00103 
00104 // Note: This function also emit constructor calls to support a MSVC
00105 // extensions allowing explicit constructor function call.
00106 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
00107                                               ReturnValueSlot ReturnValue) {
00108   const Expr *callee = CE->getCallee()->IgnoreParens();
00109 
00110   if (isa<BinaryOperator>(callee))
00111     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
00112 
00113   const MemberExpr *ME = cast<MemberExpr>(callee);
00114   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
00115 
00116   if (MD->isStatic()) {
00117     // The method is static, emit it as we would a regular call.
00118     llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
00119     return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
00120                     ReturnValue);
00121   }
00122 
00123   // Compute the object pointer.
00124   const Expr *Base = ME->getBase();
00125   bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
00126 
00127   const CXXMethodDecl *DevirtualizedMethod = nullptr;
00128   if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
00129     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
00130     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
00131     assert(DevirtualizedMethod);
00132     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
00133     const Expr *Inner = Base->ignoreParenBaseCasts();
00134     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
00135         MD->getReturnType().getCanonicalType())
00136       // If the return types are not the same, this might be a case where more
00137       // code needs to run to compensate for it. For example, the derived
00138       // method might return a type that inherits form from the return
00139       // type of MD and has a prefix.
00140       // For now we just avoid devirtualizing these covariant cases.
00141       DevirtualizedMethod = nullptr;
00142     else if (getCXXRecord(Inner) == DevirtualizedClass)
00143       // If the class of the Inner expression is where the dynamic method
00144       // is defined, build the this pointer from it.
00145       Base = Inner;
00146     else if (getCXXRecord(Base) != DevirtualizedClass) {
00147       // If the method is defined in a class that is not the best dynamic
00148       // one or the one of the full expression, we would have to build
00149       // a derived-to-base cast to compute the correct this pointer, but
00150       // we don't have support for that yet, so do a virtual call.
00151       DevirtualizedMethod = nullptr;
00152     }
00153   }
00154 
00155   llvm::Value *This;
00156   if (ME->isArrow())
00157     This = EmitScalarExpr(Base);
00158   else
00159     This = EmitLValue(Base).getAddress();
00160 
00161 
00162   if (MD->isTrivial()) {
00163     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
00164     if (isa<CXXConstructorDecl>(MD) && 
00165         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
00166       return RValue::get(nullptr);
00167 
00168     if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
00169       // We don't like to generate the trivial copy/move assignment operator
00170       // when it isn't necessary; just produce the proper effect here.
00171       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
00172       EmitAggregateAssign(This, RHS, CE->getType());
00173       return RValue::get(This);
00174     }
00175 
00176     if (isa<CXXConstructorDecl>(MD) &&
00177         cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
00178       // Trivial move and copy ctor are the same.
00179       assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
00180       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
00181       EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
00182       return RValue::get(This);
00183     }
00184     llvm_unreachable("unknown trivial member function");
00185   }
00186 
00187   // Compute the function type we're calling.
00188   const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
00189   const CGFunctionInfo *FInfo = nullptr;
00190   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
00191     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
00192         Dtor, StructorType::Complete);
00193   else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
00194     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
00195         Ctor, StructorType::Complete);
00196   else
00197     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
00198 
00199   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
00200 
00201   // C++ [class.virtual]p12:
00202   //   Explicit qualification with the scope operator (5.1) suppresses the
00203   //   virtual call mechanism.
00204   //
00205   // We also don't emit a virtual call if the base expression has a record type
00206   // because then we know what the type is.
00207   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
00208   llvm::Value *Callee;
00209 
00210   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
00211     assert(CE->arg_begin() == CE->arg_end() &&
00212            "Destructor shouldn't have explicit parameters");
00213     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
00214     if (UseVirtualCall) {
00215       CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
00216                                                 This, CE);
00217     } else {
00218       if (getLangOpts().AppleKext &&
00219           MD->isVirtual() &&
00220           ME->hasQualifier())
00221         Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
00222       else if (!DevirtualizedMethod)
00223         Callee =
00224             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
00225       else {
00226         const CXXDestructorDecl *DDtor =
00227           cast<CXXDestructorDecl>(DevirtualizedMethod);
00228         Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
00229       }
00230       EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
00231                                   /*ImplicitParam=*/nullptr, QualType(), CE);
00232     }
00233     return RValue::get(nullptr);
00234   }
00235   
00236   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
00237     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
00238   } else if (UseVirtualCall) {
00239     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
00240   } else {
00241     if (getLangOpts().AppleKext &&
00242         MD->isVirtual() &&
00243         ME->hasQualifier())
00244       Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
00245     else if (!DevirtualizedMethod)
00246       Callee = CGM.GetAddrOfFunction(MD, Ty);
00247     else {
00248       Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
00249     }
00250   }
00251 
00252   if (MD->isVirtual()) {
00253     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
00254         *this, MD, This, UseVirtualCall);
00255   }
00256 
00257   return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
00258                                      /*ImplicitParam=*/nullptr, QualType(), CE);
00259 }
00260 
00261 RValue
00262 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
00263                                               ReturnValueSlot ReturnValue) {
00264   const BinaryOperator *BO =
00265       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
00266   const Expr *BaseExpr = BO->getLHS();
00267   const Expr *MemFnExpr = BO->getRHS();
00268   
00269   const MemberPointerType *MPT = 
00270     MemFnExpr->getType()->castAs<MemberPointerType>();
00271 
00272   const FunctionProtoType *FPT = 
00273     MPT->getPointeeType()->castAs<FunctionProtoType>();
00274   const CXXRecordDecl *RD = 
00275     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
00276 
00277   // Get the member function pointer.
00278   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
00279 
00280   // Emit the 'this' pointer.
00281   llvm::Value *This;
00282   
00283   if (BO->getOpcode() == BO_PtrMemI)
00284     This = EmitScalarExpr(BaseExpr);
00285   else 
00286     This = EmitLValue(BaseExpr).getAddress();
00287 
00288   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
00289                 QualType(MPT->getClass(), 0));
00290 
00291   // Ask the ABI to load the callee.  Note that This is modified.
00292   llvm::Value *Callee =
00293     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
00294   
00295   CallArgList Args;
00296 
00297   QualType ThisType = 
00298     getContext().getPointerType(getContext().getTagDeclType(RD));
00299 
00300   // Push the this ptr.
00301   Args.add(RValue::get(This), ThisType);
00302 
00303   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
00304   
00305   // And the rest of the call args
00306   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
00307   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
00308                   Callee, ReturnValue, Args);
00309 }
00310 
00311 RValue
00312 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
00313                                                const CXXMethodDecl *MD,
00314                                                ReturnValueSlot ReturnValue) {
00315   assert(MD->isInstance() &&
00316          "Trying to emit a member call expr on a static method!");
00317   LValue LV = EmitLValue(E->getArg(0));
00318   llvm::Value *This = LV.getAddress();
00319 
00320   if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
00321       MD->isTrivial() && !MD->getParent()->mayInsertExtraPadding()) {
00322     llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
00323     QualType Ty = E->getType();
00324     EmitAggregateAssign(This, Src, Ty);
00325     return RValue::get(This);
00326   }
00327 
00328   llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
00329   return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
00330                                      /*ImplicitParam=*/nullptr, QualType(), E);
00331 }
00332 
00333 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
00334                                                ReturnValueSlot ReturnValue) {
00335   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
00336 }
00337 
00338 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
00339                                             llvm::Value *DestPtr,
00340                                             const CXXRecordDecl *Base) {
00341   if (Base->isEmpty())
00342     return;
00343 
00344   DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
00345 
00346   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
00347   CharUnits Size = Layout.getNonVirtualSize();
00348   CharUnits Align = Layout.getNonVirtualAlignment();
00349 
00350   llvm::Value *SizeVal = CGF.CGM.getSize(Size);
00351 
00352   // If the type contains a pointer to data member we can't memset it to zero.
00353   // Instead, create a null constant and copy it to the destination.
00354   // TODO: there are other patterns besides zero that we can usefully memset,
00355   // like -1, which happens to be the pattern used by member-pointers.
00356   // TODO: isZeroInitializable can be over-conservative in the case where a
00357   // virtual base contains a member pointer.
00358   if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
00359     llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
00360 
00361     llvm::GlobalVariable *NullVariable = 
00362       new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
00363                                /*isConstant=*/true, 
00364                                llvm::GlobalVariable::PrivateLinkage,
00365                                NullConstant, Twine());
00366     NullVariable->setAlignment(Align.getQuantity());
00367     llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
00368 
00369     // Get and call the appropriate llvm.memcpy overload.
00370     CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
00371     return;
00372   } 
00373   
00374   // Otherwise, just memset the whole thing to zero.  This is legal
00375   // because in LLVM, all default initializers (other than the ones we just
00376   // handled above) are guaranteed to have a bit pattern of all zeros.
00377   CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
00378                            Align.getQuantity());
00379 }
00380 
00381 void
00382 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
00383                                       AggValueSlot Dest) {
00384   assert(!Dest.isIgnored() && "Must have a destination!");
00385   const CXXConstructorDecl *CD = E->getConstructor();
00386   
00387   // If we require zero initialization before (or instead of) calling the
00388   // constructor, as can be the case with a non-user-provided default
00389   // constructor, emit the zero initialization now, unless destination is
00390   // already zeroed.
00391   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
00392     switch (E->getConstructionKind()) {
00393     case CXXConstructExpr::CK_Delegating:
00394     case CXXConstructExpr::CK_Complete:
00395       EmitNullInitialization(Dest.getAddr(), E->getType());
00396       break;
00397     case CXXConstructExpr::CK_VirtualBase:
00398     case CXXConstructExpr::CK_NonVirtualBase:
00399       EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
00400       break;
00401     }
00402   }
00403   
00404   // If this is a call to a trivial default constructor, do nothing.
00405   if (CD->isTrivial() && CD->isDefaultConstructor())
00406     return;
00407   
00408   // Elide the constructor if we're constructing from a temporary.
00409   // The temporary check is required because Sema sets this on NRVO
00410   // returns.
00411   if (getLangOpts().ElideConstructors && E->isElidable()) {
00412     assert(getContext().hasSameUnqualifiedType(E->getType(),
00413                                                E->getArg(0)->getType()));
00414     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
00415       EmitAggExpr(E->getArg(0), Dest);
00416       return;
00417     }
00418   }
00419   
00420   if (const ConstantArrayType *arrayType 
00421         = getContext().getAsConstantArrayType(E->getType())) {
00422     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
00423   } else {
00424     CXXCtorType Type = Ctor_Complete;
00425     bool ForVirtualBase = false;
00426     bool Delegating = false;
00427     
00428     switch (E->getConstructionKind()) {
00429      case CXXConstructExpr::CK_Delegating:
00430       // We should be emitting a constructor; GlobalDecl will assert this
00431       Type = CurGD.getCtorType();
00432       Delegating = true;
00433       break;
00434 
00435      case CXXConstructExpr::CK_Complete:
00436       Type = Ctor_Complete;
00437       break;
00438 
00439      case CXXConstructExpr::CK_VirtualBase:
00440       ForVirtualBase = true;
00441       // fall-through
00442 
00443      case CXXConstructExpr::CK_NonVirtualBase:
00444       Type = Ctor_Base;
00445     }
00446     
00447     // Call the constructor.
00448     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
00449                            E);
00450   }
00451 }
00452 
00453 void
00454 CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, 
00455                                             llvm::Value *Src,
00456                                             const Expr *Exp) {
00457   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
00458     Exp = E->getSubExpr();
00459   assert(isa<CXXConstructExpr>(Exp) && 
00460          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
00461   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
00462   const CXXConstructorDecl *CD = E->getConstructor();
00463   RunCleanupsScope Scope(*this);
00464   
00465   // If we require zero initialization before (or instead of) calling the
00466   // constructor, as can be the case with a non-user-provided default
00467   // constructor, emit the zero initialization now.
00468   // FIXME. Do I still need this for a copy ctor synthesis?
00469   if (E->requiresZeroInitialization())
00470     EmitNullInitialization(Dest, E->getType());
00471   
00472   assert(!getContext().getAsConstantArrayType(E->getType())
00473          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
00474   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
00475 }
00476 
00477 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
00478                                         const CXXNewExpr *E) {
00479   if (!E->isArray())
00480     return CharUnits::Zero();
00481 
00482   // No cookie is required if the operator new[] being used is the
00483   // reserved placement operator new[].
00484   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
00485     return CharUnits::Zero();
00486 
00487   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
00488 }
00489 
00490 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
00491                                         const CXXNewExpr *e,
00492                                         unsigned minElements,
00493                                         llvm::Value *&numElements,
00494                                         llvm::Value *&sizeWithoutCookie) {
00495   QualType type = e->getAllocatedType();
00496 
00497   if (!e->isArray()) {
00498     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
00499     sizeWithoutCookie
00500       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
00501     return sizeWithoutCookie;
00502   }
00503 
00504   // The width of size_t.
00505   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
00506 
00507   // Figure out the cookie size.
00508   llvm::APInt cookieSize(sizeWidth,
00509                          CalculateCookiePadding(CGF, e).getQuantity());
00510 
00511   // Emit the array size expression.
00512   // We multiply the size of all dimensions for NumElements.
00513   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
00514   numElements = CGF.EmitScalarExpr(e->getArraySize());
00515   assert(isa<llvm::IntegerType>(numElements->getType()));
00516 
00517   // The number of elements can be have an arbitrary integer type;
00518   // essentially, we need to multiply it by a constant factor, add a
00519   // cookie size, and verify that the result is representable as a
00520   // size_t.  That's just a gloss, though, and it's wrong in one
00521   // important way: if the count is negative, it's an error even if
00522   // the cookie size would bring the total size >= 0.
00523   bool isSigned 
00524     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
00525   llvm::IntegerType *numElementsType
00526     = cast<llvm::IntegerType>(numElements->getType());
00527   unsigned numElementsWidth = numElementsType->getBitWidth();
00528 
00529   // Compute the constant factor.
00530   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
00531   while (const ConstantArrayType *CAT
00532              = CGF.getContext().getAsConstantArrayType(type)) {
00533     type = CAT->getElementType();
00534     arraySizeMultiplier *= CAT->getSize();
00535   }
00536 
00537   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
00538   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
00539   typeSizeMultiplier *= arraySizeMultiplier;
00540 
00541   // This will be a size_t.
00542   llvm::Value *size;
00543   
00544   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
00545   // Don't bloat the -O0 code.
00546   if (llvm::ConstantInt *numElementsC =
00547         dyn_cast<llvm::ConstantInt>(numElements)) {
00548     const llvm::APInt &count = numElementsC->getValue();
00549 
00550     bool hasAnyOverflow = false;
00551 
00552     // If 'count' was a negative number, it's an overflow.
00553     if (isSigned && count.isNegative())
00554       hasAnyOverflow = true;
00555 
00556     // We want to do all this arithmetic in size_t.  If numElements is
00557     // wider than that, check whether it's already too big, and if so,
00558     // overflow.
00559     else if (numElementsWidth > sizeWidth &&
00560              numElementsWidth - sizeWidth > count.countLeadingZeros())
00561       hasAnyOverflow = true;
00562 
00563     // Okay, compute a count at the right width.
00564     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
00565 
00566     // If there is a brace-initializer, we cannot allocate fewer elements than
00567     // there are initializers. If we do, that's treated like an overflow.
00568     if (adjustedCount.ult(minElements))
00569       hasAnyOverflow = true;
00570 
00571     // Scale numElements by that.  This might overflow, but we don't
00572     // care because it only overflows if allocationSize does, too, and
00573     // if that overflows then we shouldn't use this.
00574     numElements = llvm::ConstantInt::get(CGF.SizeTy,
00575                                          adjustedCount * arraySizeMultiplier);
00576 
00577     // Compute the size before cookie, and track whether it overflowed.
00578     bool overflow;
00579     llvm::APInt allocationSize
00580       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
00581     hasAnyOverflow |= overflow;
00582 
00583     // Add in the cookie, and check whether it's overflowed.
00584     if (cookieSize != 0) {
00585       // Save the current size without a cookie.  This shouldn't be
00586       // used if there was overflow.
00587       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
00588 
00589       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
00590       hasAnyOverflow |= overflow;
00591     }
00592 
00593     // On overflow, produce a -1 so operator new will fail.
00594     if (hasAnyOverflow) {
00595       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
00596     } else {
00597       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
00598     }
00599 
00600   // Otherwise, we might need to use the overflow intrinsics.
00601   } else {
00602     // There are up to five conditions we need to test for:
00603     // 1) if isSigned, we need to check whether numElements is negative;
00604     // 2) if numElementsWidth > sizeWidth, we need to check whether
00605     //   numElements is larger than something representable in size_t;
00606     // 3) if minElements > 0, we need to check whether numElements is smaller
00607     //    than that.
00608     // 4) we need to compute
00609     //      sizeWithoutCookie := numElements * typeSizeMultiplier
00610     //    and check whether it overflows; and
00611     // 5) if we need a cookie, we need to compute
00612     //      size := sizeWithoutCookie + cookieSize
00613     //    and check whether it overflows.
00614 
00615     llvm::Value *hasOverflow = nullptr;
00616 
00617     // If numElementsWidth > sizeWidth, then one way or another, we're
00618     // going to have to do a comparison for (2), and this happens to
00619     // take care of (1), too.
00620     if (numElementsWidth > sizeWidth) {
00621       llvm::APInt threshold(numElementsWidth, 1);
00622       threshold <<= sizeWidth;
00623 
00624       llvm::Value *thresholdV
00625         = llvm::ConstantInt::get(numElementsType, threshold);
00626 
00627       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
00628       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
00629 
00630     // Otherwise, if we're signed, we want to sext up to size_t.
00631     } else if (isSigned) {
00632       if (numElementsWidth < sizeWidth)
00633         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
00634       
00635       // If there's a non-1 type size multiplier, then we can do the
00636       // signedness check at the same time as we do the multiply
00637       // because a negative number times anything will cause an
00638       // unsigned overflow.  Otherwise, we have to do it here. But at least
00639       // in this case, we can subsume the >= minElements check.
00640       if (typeSizeMultiplier == 1)
00641         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
00642                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
00643 
00644     // Otherwise, zext up to size_t if necessary.
00645     } else if (numElementsWidth < sizeWidth) {
00646       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
00647     }
00648 
00649     assert(numElements->getType() == CGF.SizeTy);
00650 
00651     if (minElements) {
00652       // Don't allow allocation of fewer elements than we have initializers.
00653       if (!hasOverflow) {
00654         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
00655                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
00656       } else if (numElementsWidth > sizeWidth) {
00657         // The other existing overflow subsumes this check.
00658         // We do an unsigned comparison, since any signed value < -1 is
00659         // taken care of either above or below.
00660         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
00661                           CGF.Builder.CreateICmpULT(numElements,
00662                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
00663       }
00664     }
00665 
00666     size = numElements;
00667 
00668     // Multiply by the type size if necessary.  This multiplier
00669     // includes all the factors for nested arrays.
00670     //
00671     // This step also causes numElements to be scaled up by the
00672     // nested-array factor if necessary.  Overflow on this computation
00673     // can be ignored because the result shouldn't be used if
00674     // allocation fails.
00675     if (typeSizeMultiplier != 1) {
00676       llvm::Value *umul_with_overflow
00677         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
00678 
00679       llvm::Value *tsmV =
00680         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
00681       llvm::Value *result =
00682         CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
00683 
00684       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
00685       if (hasOverflow)
00686         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
00687       else
00688         hasOverflow = overflowed;
00689 
00690       size = CGF.Builder.CreateExtractValue(result, 0);
00691 
00692       // Also scale up numElements by the array size multiplier.
00693       if (arraySizeMultiplier != 1) {
00694         // If the base element type size is 1, then we can re-use the
00695         // multiply we just did.
00696         if (typeSize.isOne()) {
00697           assert(arraySizeMultiplier == typeSizeMultiplier);
00698           numElements = size;
00699 
00700         // Otherwise we need a separate multiply.
00701         } else {
00702           llvm::Value *asmV =
00703             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
00704           numElements = CGF.Builder.CreateMul(numElements, asmV);
00705         }
00706       }
00707     } else {
00708       // numElements doesn't need to be scaled.
00709       assert(arraySizeMultiplier == 1);
00710     }
00711     
00712     // Add in the cookie size if necessary.
00713     if (cookieSize != 0) {
00714       sizeWithoutCookie = size;
00715 
00716       llvm::Value *uadd_with_overflow
00717         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
00718 
00719       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
00720       llvm::Value *result =
00721         CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
00722 
00723       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
00724       if (hasOverflow)
00725         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
00726       else
00727         hasOverflow = overflowed;
00728 
00729       size = CGF.Builder.CreateExtractValue(result, 0);
00730     }
00731 
00732     // If we had any possibility of dynamic overflow, make a select to
00733     // overwrite 'size' with an all-ones value, which should cause
00734     // operator new to throw.
00735     if (hasOverflow)
00736       size = CGF.Builder.CreateSelect(hasOverflow,
00737                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
00738                                       size);
00739   }
00740 
00741   if (cookieSize == 0)
00742     sizeWithoutCookie = size;
00743   else
00744     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
00745 
00746   return size;
00747 }
00748 
00749 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
00750                                     QualType AllocType, llvm::Value *NewPtr) {
00751   // FIXME: Refactor with EmitExprAsInit.
00752   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
00753   switch (CGF.getEvaluationKind(AllocType)) {
00754   case TEK_Scalar:
00755     CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
00756                                                          Alignment),
00757                        false);
00758     return;
00759   case TEK_Complex:
00760     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
00761                                                            Alignment),
00762                                   /*isInit*/ true);
00763     return;
00764   case TEK_Aggregate: {
00765     AggValueSlot Slot
00766       = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
00767                               AggValueSlot::IsDestructed,
00768                               AggValueSlot::DoesNotNeedGCBarriers,
00769                               AggValueSlot::IsNotAliased);
00770     CGF.EmitAggExpr(Init, Slot);
00771     return;
00772   }
00773   }
00774   llvm_unreachable("bad evaluation kind");
00775 }
00776 
00777 void
00778 CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
00779                                          QualType ElementType,
00780                                          llvm::Value *BeginPtr,
00781                                          llvm::Value *NumElements,
00782                                          llvm::Value *AllocSizeWithoutCookie) {
00783   // If we have a type with trivial initialization and no initializer,
00784   // there's nothing to do.
00785   if (!E->hasInitializer())
00786     return;
00787 
00788   llvm::Value *CurPtr = BeginPtr;
00789 
00790   unsigned InitListElements = 0;
00791 
00792   const Expr *Init = E->getInitializer();
00793   llvm::AllocaInst *EndOfInit = nullptr;
00794   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
00795   EHScopeStack::stable_iterator Cleanup;
00796   llvm::Instruction *CleanupDominator = nullptr;
00797 
00798   // If the initializer is an initializer list, first do the explicit elements.
00799   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
00800     InitListElements = ILE->getNumInits();
00801 
00802     // If this is a multi-dimensional array new, we will initialize multiple
00803     // elements with each init list element.
00804     QualType AllocType = E->getAllocatedType();
00805     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
00806             AllocType->getAsArrayTypeUnsafe())) {
00807       unsigned AS = CurPtr->getType()->getPointerAddressSpace();
00808       llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
00809       CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
00810       InitListElements *= getContext().getConstantArrayElementCount(CAT);
00811     }
00812 
00813     // Enter a partial-destruction Cleanup if necessary.
00814     if (needsEHCleanup(DtorKind)) {
00815       // In principle we could tell the Cleanup where we are more
00816       // directly, but the control flow can get so varied here that it
00817       // would actually be quite complex.  Therefore we go through an
00818       // alloca.
00819       EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
00820       CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
00821       pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
00822                                        getDestroyer(DtorKind));
00823       Cleanup = EHStack.stable_begin();
00824     }
00825 
00826     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
00827       // Tell the cleanup that it needs to destroy up to this
00828       // element.  TODO: some of these stores can be trivially
00829       // observed to be unnecessary.
00830       if (EndOfInit)
00831         Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
00832                             EndOfInit);
00833       // FIXME: If the last initializer is an incomplete initializer list for
00834       // an array, and we have an array filler, we can fold together the two
00835       // initialization loops.
00836       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
00837                               ILE->getInit(i)->getType(), CurPtr);
00838       CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
00839     }
00840 
00841     // The remaining elements are filled with the array filler expression.
00842     Init = ILE->getArrayFiller();
00843 
00844     // Extract the initializer for the individual array elements by pulling
00845     // out the array filler from all the nested initializer lists. This avoids
00846     // generating a nested loop for the initialization.
00847     while (Init && Init->getType()->isConstantArrayType()) {
00848       auto *SubILE = dyn_cast<InitListExpr>(Init);
00849       if (!SubILE)
00850         break;
00851       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
00852       Init = SubILE->getArrayFiller();
00853     }
00854 
00855     // Switch back to initializing one base element at a time.
00856     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
00857   }
00858 
00859   // Attempt to perform zero-initialization using memset.
00860   auto TryMemsetInitialization = [&]() -> bool {
00861     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
00862     // we can initialize with a memset to -1.
00863     if (!CGM.getTypes().isZeroInitializable(ElementType))
00864       return false;
00865 
00866     // Optimization: since zero initialization will just set the memory
00867     // to all zeroes, generate a single memset to do it in one shot.
00868 
00869     // Subtract out the size of any elements we've already initialized.
00870     auto *RemainingSize = AllocSizeWithoutCookie;
00871     if (InitListElements) {
00872       // We know this can't overflow; we check this when doing the allocation.
00873       auto *InitializedSize = llvm::ConstantInt::get(
00874           RemainingSize->getType(),
00875           getContext().getTypeSizeInChars(ElementType).getQuantity() *
00876               InitListElements);
00877       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
00878     }
00879 
00880     // Create the memset.
00881     CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
00882     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
00883                          Alignment.getQuantity(), false);
00884     return true;
00885   };
00886 
00887   // If all elements have already been initialized, skip any further
00888   // initialization.
00889   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
00890   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
00891     // If there was a Cleanup, deactivate it.
00892     if (CleanupDominator)
00893       DeactivateCleanupBlock(Cleanup, CleanupDominator);
00894     return;
00895   }
00896 
00897   assert(Init && "have trailing elements to initialize but no initializer");
00898 
00899   // If this is a constructor call, try to optimize it out, and failing that
00900   // emit a single loop to initialize all remaining elements.
00901   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
00902     CXXConstructorDecl *Ctor = CCE->getConstructor();
00903     if (Ctor->isTrivial()) {
00904       // If new expression did not specify value-initialization, then there
00905       // is no initialization.
00906       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
00907         return;
00908 
00909       if (TryMemsetInitialization())
00910         return;
00911     }
00912 
00913     // Store the new Cleanup position for irregular Cleanups.
00914     //
00915     // FIXME: Share this cleanup with the constructor call emission rather than
00916     // having it create a cleanup of its own.
00917     if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
00918 
00919     // Emit a constructor call loop to initialize the remaining elements.
00920     if (InitListElements)
00921       NumElements = Builder.CreateSub(
00922           NumElements,
00923           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
00924     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
00925                                CCE->requiresZeroInitialization());
00926     return;
00927   }
00928 
00929   // If this is value-initialization, we can usually use memset.
00930   ImplicitValueInitExpr IVIE(ElementType);
00931   if (isa<ImplicitValueInitExpr>(Init)) {
00932     if (TryMemsetInitialization())
00933       return;
00934 
00935     // Switch to an ImplicitValueInitExpr for the element type. This handles
00936     // only one case: multidimensional array new of pointers to members. In
00937     // all other cases, we already have an initializer for the array element.
00938     Init = &IVIE;
00939   }
00940 
00941   // At this point we should have found an initializer for the individual
00942   // elements of the array.
00943   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
00944          "got wrong type of element to initialize");
00945 
00946   // If we have an empty initializer list, we can usually use memset.
00947   if (auto *ILE = dyn_cast<InitListExpr>(Init))
00948     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
00949       return;
00950 
00951   // Create the loop blocks.
00952   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
00953   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
00954   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
00955 
00956   // Find the end of the array, hoisted out of the loop.
00957   llvm::Value *EndPtr =
00958     Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
00959 
00960   // If the number of elements isn't constant, we have to now check if there is
00961   // anything left to initialize.
00962   if (!ConstNum) {
00963     llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
00964                                                 "array.isempty");
00965     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
00966   }
00967 
00968   // Enter the loop.
00969   EmitBlock(LoopBB);
00970 
00971   // Set up the current-element phi.
00972   llvm::PHINode *CurPtrPhi =
00973     Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
00974   CurPtrPhi->addIncoming(CurPtr, EntryBB);
00975   CurPtr = CurPtrPhi;
00976 
00977   // Store the new Cleanup position for irregular Cleanups.
00978   if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
00979 
00980   // Enter a partial-destruction Cleanup if necessary.
00981   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
00982     pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
00983                                    getDestroyer(DtorKind));
00984     Cleanup = EHStack.stable_begin();
00985     CleanupDominator = Builder.CreateUnreachable();
00986   }
00987 
00988   // Emit the initializer into this element.
00989   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
00990 
00991   // Leave the Cleanup if we entered one.
00992   if (CleanupDominator) {
00993     DeactivateCleanupBlock(Cleanup, CleanupDominator);
00994     CleanupDominator->eraseFromParent();
00995   }
00996 
00997   // Advance to the next element by adjusting the pointer type as necessary.
00998   llvm::Value *NextPtr =
00999       Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
01000 
01001   // Check whether we've gotten to the end of the array and, if so,
01002   // exit the loop.
01003   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
01004   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
01005   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
01006 
01007   EmitBlock(ContBB);
01008 }
01009 
01010 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
01011                                QualType ElementType,
01012                                llvm::Value *NewPtr,
01013                                llvm::Value *NumElements,
01014                                llvm::Value *AllocSizeWithoutCookie) {
01015   if (E->isArray())
01016     CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
01017                                 AllocSizeWithoutCookie);
01018   else if (const Expr *Init = E->getInitializer())
01019     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
01020 }
01021 
01022 /// Emit a call to an operator new or operator delete function, as implicitly
01023 /// created by new-expressions and delete-expressions.
01024 static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
01025                                 const FunctionDecl *Callee,
01026                                 const FunctionProtoType *CalleeType,
01027                                 const CallArgList &Args) {
01028   llvm::Instruction *CallOrInvoke;
01029   llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
01030   RValue RV =
01031       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
01032                    CalleeAddr, ReturnValueSlot(), Args,
01033                    Callee, &CallOrInvoke);
01034 
01035   /// C++1y [expr.new]p10:
01036   ///   [In a new-expression,] an implementation is allowed to omit a call
01037   ///   to a replaceable global allocation function.
01038   ///
01039   /// We model such elidable calls with the 'builtin' attribute.
01040   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
01041   if (Callee->isReplaceableGlobalAllocationFunction() &&
01042       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
01043     // FIXME: Add addAttribute to CallSite.
01044     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
01045       CI->addAttribute(llvm::AttributeSet::FunctionIndex,
01046                        llvm::Attribute::Builtin);
01047     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
01048       II->addAttribute(llvm::AttributeSet::FunctionIndex,
01049                        llvm::Attribute::Builtin);
01050     else
01051       llvm_unreachable("unexpected kind of call instruction");
01052   }
01053 
01054   return RV;
01055 }
01056 
01057 RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
01058                                                  const Expr *Arg,
01059                                                  bool IsDelete) {
01060   CallArgList Args;
01061   const Stmt *ArgS = Arg;
01062   EmitCallArgs(Args, *Type->param_type_begin(),
01063                ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
01064   // Find the allocation or deallocation function that we're calling.
01065   ASTContext &Ctx = getContext();
01066   DeclarationName Name = Ctx.DeclarationNames
01067       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
01068   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
01069     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
01070       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
01071         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
01072   llvm_unreachable("predeclared global operator new/delete is missing");
01073 }
01074 
01075 namespace {
01076   /// A cleanup to call the given 'operator delete' function upon
01077   /// abnormal exit from a new expression.
01078   class CallDeleteDuringNew : public EHScopeStack::Cleanup {
01079     size_t NumPlacementArgs;
01080     const FunctionDecl *OperatorDelete;
01081     llvm::Value *Ptr;
01082     llvm::Value *AllocSize;
01083 
01084     RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
01085 
01086   public:
01087     static size_t getExtraSize(size_t NumPlacementArgs) {
01088       return NumPlacementArgs * sizeof(RValue);
01089     }
01090 
01091     CallDeleteDuringNew(size_t NumPlacementArgs,
01092                         const FunctionDecl *OperatorDelete,
01093                         llvm::Value *Ptr,
01094                         llvm::Value *AllocSize) 
01095       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
01096         Ptr(Ptr), AllocSize(AllocSize) {}
01097 
01098     void setPlacementArg(unsigned I, RValue Arg) {
01099       assert(I < NumPlacementArgs && "index out of range");
01100       getPlacementArgs()[I] = Arg;
01101     }
01102 
01103     void Emit(CodeGenFunction &CGF, Flags flags) override {
01104       const FunctionProtoType *FPT
01105         = OperatorDelete->getType()->getAs<FunctionProtoType>();
01106       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
01107              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
01108 
01109       CallArgList DeleteArgs;
01110 
01111       // The first argument is always a void*.
01112       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
01113       DeleteArgs.add(RValue::get(Ptr), *AI++);
01114 
01115       // A member 'operator delete' can take an extra 'size_t' argument.
01116       if (FPT->getNumParams() == NumPlacementArgs + 2)
01117         DeleteArgs.add(RValue::get(AllocSize), *AI++);
01118 
01119       // Pass the rest of the arguments, which must match exactly.
01120       for (unsigned I = 0; I != NumPlacementArgs; ++I)
01121         DeleteArgs.add(getPlacementArgs()[I], *AI++);
01122 
01123       // Call 'operator delete'.
01124       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
01125     }
01126   };
01127 
01128   /// A cleanup to call the given 'operator delete' function upon
01129   /// abnormal exit from a new expression when the new expression is
01130   /// conditional.
01131   class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
01132     size_t NumPlacementArgs;
01133     const FunctionDecl *OperatorDelete;
01134     DominatingValue<RValue>::saved_type Ptr;
01135     DominatingValue<RValue>::saved_type AllocSize;
01136 
01137     DominatingValue<RValue>::saved_type *getPlacementArgs() {
01138       return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
01139     }
01140 
01141   public:
01142     static size_t getExtraSize(size_t NumPlacementArgs) {
01143       return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
01144     }
01145 
01146     CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
01147                                    const FunctionDecl *OperatorDelete,
01148                                    DominatingValue<RValue>::saved_type Ptr,
01149                               DominatingValue<RValue>::saved_type AllocSize)
01150       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
01151         Ptr(Ptr), AllocSize(AllocSize) {}
01152 
01153     void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
01154       assert(I < NumPlacementArgs && "index out of range");
01155       getPlacementArgs()[I] = Arg;
01156     }
01157 
01158     void Emit(CodeGenFunction &CGF, Flags flags) override {
01159       const FunctionProtoType *FPT
01160         = OperatorDelete->getType()->getAs<FunctionProtoType>();
01161       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
01162              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
01163 
01164       CallArgList DeleteArgs;
01165 
01166       // The first argument is always a void*.
01167       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
01168       DeleteArgs.add(Ptr.restore(CGF), *AI++);
01169 
01170       // A member 'operator delete' can take an extra 'size_t' argument.
01171       if (FPT->getNumParams() == NumPlacementArgs + 2) {
01172         RValue RV = AllocSize.restore(CGF);
01173         DeleteArgs.add(RV, *AI++);
01174       }
01175 
01176       // Pass the rest of the arguments, which must match exactly.
01177       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
01178         RValue RV = getPlacementArgs()[I].restore(CGF);
01179         DeleteArgs.add(RV, *AI++);
01180       }
01181 
01182       // Call 'operator delete'.
01183       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
01184     }
01185   };
01186 }
01187 
01188 /// Enter a cleanup to call 'operator delete' if the initializer in a
01189 /// new-expression throws.
01190 static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
01191                                   const CXXNewExpr *E,
01192                                   llvm::Value *NewPtr,
01193                                   llvm::Value *AllocSize,
01194                                   const CallArgList &NewArgs) {
01195   // If we're not inside a conditional branch, then the cleanup will
01196   // dominate and we can do the easier (and more efficient) thing.
01197   if (!CGF.isInConditionalBranch()) {
01198     CallDeleteDuringNew *Cleanup = CGF.EHStack
01199       .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
01200                                                  E->getNumPlacementArgs(),
01201                                                  E->getOperatorDelete(),
01202                                                  NewPtr, AllocSize);
01203     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
01204       Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
01205 
01206     return;
01207   }
01208 
01209   // Otherwise, we need to save all this stuff.
01210   DominatingValue<RValue>::saved_type SavedNewPtr =
01211     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
01212   DominatingValue<RValue>::saved_type SavedAllocSize =
01213     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
01214 
01215   CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
01216     .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
01217                                                  E->getNumPlacementArgs(),
01218                                                  E->getOperatorDelete(),
01219                                                  SavedNewPtr,
01220                                                  SavedAllocSize);
01221   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
01222     Cleanup->setPlacementArg(I,
01223                      DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
01224 
01225   CGF.initFullExprCleanup();
01226 }
01227 
01228 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
01229   // The element type being allocated.
01230   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
01231 
01232   // 1. Build a call to the allocation function.
01233   FunctionDecl *allocator = E->getOperatorNew();
01234   const FunctionProtoType *allocatorType =
01235     allocator->getType()->castAs<FunctionProtoType>();
01236 
01237   CallArgList allocatorArgs;
01238 
01239   // The allocation size is the first argument.
01240   QualType sizeType = getContext().getSizeType();
01241 
01242   // If there is a brace-initializer, cannot allocate fewer elements than inits.
01243   unsigned minElements = 0;
01244   if (E->isArray() && E->hasInitializer()) {
01245     if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
01246       minElements = ILE->getNumInits();
01247   }
01248 
01249   llvm::Value *numElements = nullptr;
01250   llvm::Value *allocSizeWithoutCookie = nullptr;
01251   llvm::Value *allocSize =
01252     EmitCXXNewAllocSize(*this, E, minElements, numElements,
01253                         allocSizeWithoutCookie);
01254 
01255   allocatorArgs.add(RValue::get(allocSize), sizeType);
01256 
01257   // We start at 1 here because the first argument (the allocation size)
01258   // has already been emitted.
01259   EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
01260                E->placement_arg_end(), /* CalleeDecl */ nullptr,
01261                /*ParamsToSkip*/ 1);
01262 
01263   // Emit the allocation call.  If the allocator is a global placement
01264   // operator, just "inline" it directly.
01265   RValue RV;
01266   if (allocator->isReservedGlobalPlacementOperator()) {
01267     assert(allocatorArgs.size() == 2);
01268     RV = allocatorArgs[1].RV;
01269     // TODO: kill any unnecessary computations done for the size
01270     // argument.
01271   } else {
01272     RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
01273   }
01274 
01275   // Emit a null check on the allocation result if the allocation
01276   // function is allowed to return null (because it has a non-throwing
01277   // exception spec; for this part, we inline
01278   // CXXNewExpr::shouldNullCheckAllocation()) and we have an
01279   // interesting initializer.
01280   bool nullCheck = allocatorType->isNothrow(getContext()) &&
01281     (!allocType.isPODType(getContext()) || E->hasInitializer());
01282 
01283   llvm::BasicBlock *nullCheckBB = nullptr;
01284   llvm::BasicBlock *contBB = nullptr;
01285 
01286   llvm::Value *allocation = RV.getScalarVal();
01287   unsigned AS = allocation->getType()->getPointerAddressSpace();
01288 
01289   // The null-check means that the initializer is conditionally
01290   // evaluated.
01291   ConditionalEvaluation conditional(*this);
01292 
01293   if (nullCheck) {
01294     conditional.begin(*this);
01295 
01296     nullCheckBB = Builder.GetInsertBlock();
01297     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
01298     contBB = createBasicBlock("new.cont");
01299 
01300     llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
01301     Builder.CreateCondBr(isNull, contBB, notNullBB);
01302     EmitBlock(notNullBB);
01303   }
01304 
01305   // If there's an operator delete, enter a cleanup to call it if an
01306   // exception is thrown.
01307   EHScopeStack::stable_iterator operatorDeleteCleanup;
01308   llvm::Instruction *cleanupDominator = nullptr;
01309   if (E->getOperatorDelete() &&
01310       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
01311     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
01312     operatorDeleteCleanup = EHStack.stable_begin();
01313     cleanupDominator = Builder.CreateUnreachable();
01314   }
01315 
01316   assert((allocSize == allocSizeWithoutCookie) ==
01317          CalculateCookiePadding(*this, E).isZero());
01318   if (allocSize != allocSizeWithoutCookie) {
01319     assert(E->isArray());
01320     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
01321                                                        numElements,
01322                                                        E, allocType);
01323   }
01324 
01325   llvm::Type *elementPtrTy
01326     = ConvertTypeForMem(allocType)->getPointerTo(AS);
01327   llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
01328 
01329   EmitNewInitializer(*this, E, allocType, result, numElements,
01330                      allocSizeWithoutCookie);
01331   if (E->isArray()) {
01332     // NewPtr is a pointer to the base element type.  If we're
01333     // allocating an array of arrays, we'll need to cast back to the
01334     // array pointer type.
01335     llvm::Type *resultType = ConvertTypeForMem(E->getType());
01336     if (result->getType() != resultType)
01337       result = Builder.CreateBitCast(result, resultType);
01338   }
01339 
01340   // Deactivate the 'operator delete' cleanup if we finished
01341   // initialization.
01342   if (operatorDeleteCleanup.isValid()) {
01343     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
01344     cleanupDominator->eraseFromParent();
01345   }
01346 
01347   if (nullCheck) {
01348     conditional.end(*this);
01349 
01350     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
01351     EmitBlock(contBB);
01352 
01353     llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
01354     PHI->addIncoming(result, notNullBB);
01355     PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
01356                      nullCheckBB);
01357 
01358     result = PHI;
01359   }
01360   
01361   return result;
01362 }
01363 
01364 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
01365                                      llvm::Value *Ptr,
01366                                      QualType DeleteTy) {
01367   assert(DeleteFD->getOverloadedOperator() == OO_Delete);
01368 
01369   const FunctionProtoType *DeleteFTy =
01370     DeleteFD->getType()->getAs<FunctionProtoType>();
01371 
01372   CallArgList DeleteArgs;
01373 
01374   // Check if we need to pass the size to the delete operator.
01375   llvm::Value *Size = nullptr;
01376   QualType SizeTy;
01377   if (DeleteFTy->getNumParams() == 2) {
01378     SizeTy = DeleteFTy->getParamType(1);
01379     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
01380     Size = llvm::ConstantInt::get(ConvertType(SizeTy), 
01381                                   DeleteTypeSize.getQuantity());
01382   }
01383 
01384   QualType ArgTy = DeleteFTy->getParamType(0);
01385   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
01386   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
01387 
01388   if (Size)
01389     DeleteArgs.add(RValue::get(Size), SizeTy);
01390 
01391   // Emit the call to delete.
01392   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
01393 }
01394 
01395 namespace {
01396   /// Calls the given 'operator delete' on a single object.
01397   struct CallObjectDelete : EHScopeStack::Cleanup {
01398     llvm::Value *Ptr;
01399     const FunctionDecl *OperatorDelete;
01400     QualType ElementType;
01401 
01402     CallObjectDelete(llvm::Value *Ptr,
01403                      const FunctionDecl *OperatorDelete,
01404                      QualType ElementType)
01405       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
01406 
01407     void Emit(CodeGenFunction &CGF, Flags flags) override {
01408       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
01409     }
01410   };
01411 }
01412 
01413 void
01414 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
01415                                              llvm::Value *CompletePtr,
01416                                              QualType ElementType) {
01417   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
01418                                         OperatorDelete, ElementType);
01419 }
01420 
01421 /// Emit the code for deleting a single object.
01422 static void EmitObjectDelete(CodeGenFunction &CGF,
01423                              const CXXDeleteExpr *DE,
01424                              llvm::Value *Ptr,
01425                              QualType ElementType) {
01426   // Find the destructor for the type, if applicable.  If the
01427   // destructor is virtual, we'll just emit the vcall and return.
01428   const CXXDestructorDecl *Dtor = nullptr;
01429   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
01430     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
01431     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
01432       Dtor = RD->getDestructor();
01433 
01434       if (Dtor->isVirtual()) {
01435         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
01436                                                     Dtor);
01437         return;
01438       }
01439     }
01440   }
01441 
01442   // Make sure that we call delete even if the dtor throws.
01443   // This doesn't have to a conditional cleanup because we're going
01444   // to pop it off in a second.
01445   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
01446   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
01447                                             Ptr, OperatorDelete, ElementType);
01448 
01449   if (Dtor)
01450     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
01451                               /*ForVirtualBase=*/false,
01452                               /*Delegating=*/false,
01453                               Ptr);
01454   else if (CGF.getLangOpts().ObjCAutoRefCount &&
01455            ElementType->isObjCLifetimeType()) {
01456     switch (ElementType.getObjCLifetime()) {
01457     case Qualifiers::OCL_None:
01458     case Qualifiers::OCL_ExplicitNone:
01459     case Qualifiers::OCL_Autoreleasing:
01460       break;
01461 
01462     case Qualifiers::OCL_Strong: {
01463       // Load the pointer value.
01464       llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr, 
01465                                              ElementType.isVolatileQualified());
01466         
01467       CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
01468       break;
01469     }
01470         
01471     case Qualifiers::OCL_Weak:
01472       CGF.EmitARCDestroyWeak(Ptr);
01473       break;
01474     }
01475   }
01476            
01477   CGF.PopCleanupBlock();
01478 }
01479 
01480 namespace {
01481   /// Calls the given 'operator delete' on an array of objects.
01482   struct CallArrayDelete : EHScopeStack::Cleanup {
01483     llvm::Value *Ptr;
01484     const FunctionDecl *OperatorDelete;
01485     llvm::Value *NumElements;
01486     QualType ElementType;
01487     CharUnits CookieSize;
01488 
01489     CallArrayDelete(llvm::Value *Ptr,
01490                     const FunctionDecl *OperatorDelete,
01491                     llvm::Value *NumElements,
01492                     QualType ElementType,
01493                     CharUnits CookieSize)
01494       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
01495         ElementType(ElementType), CookieSize(CookieSize) {}
01496 
01497     void Emit(CodeGenFunction &CGF, Flags flags) override {
01498       const FunctionProtoType *DeleteFTy =
01499         OperatorDelete->getType()->getAs<FunctionProtoType>();
01500       assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
01501 
01502       CallArgList Args;
01503       
01504       // Pass the pointer as the first argument.
01505       QualType VoidPtrTy = DeleteFTy->getParamType(0);
01506       llvm::Value *DeletePtr
01507         = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
01508       Args.add(RValue::get(DeletePtr), VoidPtrTy);
01509 
01510       // Pass the original requested size as the second argument.
01511       if (DeleteFTy->getNumParams() == 2) {
01512         QualType size_t = DeleteFTy->getParamType(1);
01513         llvm::IntegerType *SizeTy
01514           = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
01515         
01516         CharUnits ElementTypeSize =
01517           CGF.CGM.getContext().getTypeSizeInChars(ElementType);
01518 
01519         // The size of an element, multiplied by the number of elements.
01520         llvm::Value *Size
01521           = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
01522         Size = CGF.Builder.CreateMul(Size, NumElements);
01523 
01524         // Plus the size of the cookie if applicable.
01525         if (!CookieSize.isZero()) {
01526           llvm::Value *CookieSizeV
01527             = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
01528           Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
01529         }
01530 
01531         Args.add(RValue::get(Size), size_t);
01532       }
01533 
01534       // Emit the call to delete.
01535       EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
01536     }
01537   };
01538 }
01539 
01540 /// Emit the code for deleting an array of objects.
01541 static void EmitArrayDelete(CodeGenFunction &CGF,
01542                             const CXXDeleteExpr *E,
01543                             llvm::Value *deletedPtr,
01544                             QualType elementType) {
01545   llvm::Value *numElements = nullptr;
01546   llvm::Value *allocatedPtr = nullptr;
01547   CharUnits cookieSize;
01548   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
01549                                       numElements, allocatedPtr, cookieSize);
01550 
01551   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
01552 
01553   // Make sure that we call delete even if one of the dtors throws.
01554   const FunctionDecl *operatorDelete = E->getOperatorDelete();
01555   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
01556                                            allocatedPtr, operatorDelete,
01557                                            numElements, elementType,
01558                                            cookieSize);
01559 
01560   // Destroy the elements.
01561   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
01562     assert(numElements && "no element count for a type with a destructor!");
01563 
01564     llvm::Value *arrayEnd =
01565       CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
01566 
01567     // Note that it is legal to allocate a zero-length array, and we
01568     // can never fold the check away because the length should always
01569     // come from a cookie.
01570     CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
01571                          CGF.getDestroyer(dtorKind),
01572                          /*checkZeroLength*/ true,
01573                          CGF.needsEHCleanup(dtorKind));
01574   }
01575 
01576   // Pop the cleanup block.
01577   CGF.PopCleanupBlock();
01578 }
01579 
01580 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
01581   const Expr *Arg = E->getArgument();
01582   llvm::Value *Ptr = EmitScalarExpr(Arg);
01583 
01584   // Null check the pointer.
01585   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
01586   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
01587 
01588   llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
01589 
01590   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
01591   EmitBlock(DeleteNotNull);
01592 
01593   // We might be deleting a pointer to array.  If so, GEP down to the
01594   // first non-array element.
01595   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
01596   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
01597   if (DeleteTy->isConstantArrayType()) {
01598     llvm::Value *Zero = Builder.getInt32(0);
01599     SmallVector<llvm::Value*,8> GEP;
01600 
01601     GEP.push_back(Zero); // point at the outermost array
01602 
01603     // For each layer of array type we're pointing at:
01604     while (const ConstantArrayType *Arr
01605              = getContext().getAsConstantArrayType(DeleteTy)) {
01606       // 1. Unpeel the array type.
01607       DeleteTy = Arr->getElementType();
01608 
01609       // 2. GEP to the first element of the array.
01610       GEP.push_back(Zero);
01611     }
01612 
01613     Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
01614   }
01615 
01616   assert(ConvertTypeForMem(DeleteTy) ==
01617          cast<llvm::PointerType>(Ptr->getType())->getElementType());
01618 
01619   if (E->isArrayForm()) {
01620     EmitArrayDelete(*this, E, Ptr, DeleteTy);
01621   } else {
01622     EmitObjectDelete(*this, E, Ptr, DeleteTy);
01623   }
01624 
01625   EmitBlock(DeleteEnd);
01626 }
01627 
01628 static bool isGLValueFromPointerDeref(const Expr *E) {
01629   E = E->IgnoreParens();
01630 
01631   if (const auto *CE = dyn_cast<CastExpr>(E)) {
01632     if (!CE->getSubExpr()->isGLValue())
01633       return false;
01634     return isGLValueFromPointerDeref(CE->getSubExpr());
01635   }
01636 
01637   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
01638     return isGLValueFromPointerDeref(OVE->getSourceExpr());
01639 
01640   if (const auto *BO = dyn_cast<BinaryOperator>(E))
01641     if (BO->getOpcode() == BO_Comma)
01642       return isGLValueFromPointerDeref(BO->getRHS());
01643 
01644   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
01645     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
01646            isGLValueFromPointerDeref(ACO->getFalseExpr());
01647 
01648   // C++11 [expr.sub]p1:
01649   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
01650   if (isa<ArraySubscriptExpr>(E))
01651     return true;
01652 
01653   if (const auto *UO = dyn_cast<UnaryOperator>(E))
01654     if (UO->getOpcode() == UO_Deref)
01655       return true;
01656 
01657   return false;
01658 }
01659 
01660 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
01661                                          llvm::Type *StdTypeInfoPtrTy) {
01662   // Get the vtable pointer.
01663   llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
01664 
01665   // C++ [expr.typeid]p2:
01666   //   If the glvalue expression is obtained by applying the unary * operator to
01667   //   a pointer and the pointer is a null pointer value, the typeid expression
01668   //   throws the std::bad_typeid exception.
01669   //
01670   // However, this paragraph's intent is not clear.  We choose a very generous
01671   // interpretation which implores us to consider comma operators, conditional
01672   // operators, parentheses and other such constructs.
01673   QualType SrcRecordTy = E->getType();
01674   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
01675           isGLValueFromPointerDeref(E), SrcRecordTy)) {
01676     llvm::BasicBlock *BadTypeidBlock =
01677         CGF.createBasicBlock("typeid.bad_typeid");
01678     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
01679 
01680     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
01681     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
01682 
01683     CGF.EmitBlock(BadTypeidBlock);
01684     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
01685     CGF.EmitBlock(EndBlock);
01686   }
01687 
01688   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
01689                                         StdTypeInfoPtrTy);
01690 }
01691 
01692 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
01693   llvm::Type *StdTypeInfoPtrTy = 
01694     ConvertType(E->getType())->getPointerTo();
01695   
01696   if (E->isTypeOperand()) {
01697     llvm::Constant *TypeInfo =
01698         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
01699     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
01700   }
01701 
01702   // C++ [expr.typeid]p2:
01703   //   When typeid is applied to a glvalue expression whose type is a
01704   //   polymorphic class type, the result refers to a std::type_info object
01705   //   representing the type of the most derived object (that is, the dynamic
01706   //   type) to which the glvalue refers.
01707   if (E->isPotentiallyEvaluated())
01708     return EmitTypeidFromVTable(*this, E->getExprOperand(), 
01709                                 StdTypeInfoPtrTy);
01710 
01711   QualType OperandTy = E->getExprOperand()->getType();
01712   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
01713                                StdTypeInfoPtrTy);
01714 }
01715 
01716 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
01717                                           QualType DestTy) {
01718   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
01719   if (DestTy->isPointerType())
01720     return llvm::Constant::getNullValue(DestLTy);
01721 
01722   /// C++ [expr.dynamic.cast]p9:
01723   ///   A failed cast to reference type throws std::bad_cast
01724   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
01725     return nullptr;
01726 
01727   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
01728   return llvm::UndefValue::get(DestLTy);
01729 }
01730 
01731 llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
01732                                               const CXXDynamicCastExpr *DCE) {
01733   QualType DestTy = DCE->getTypeAsWritten();
01734 
01735   if (DCE->isAlwaysNull())
01736     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
01737       return T;
01738 
01739   QualType SrcTy = DCE->getSubExpr()->getType();
01740 
01741   // C++ [expr.dynamic.cast]p7:
01742   //   If T is "pointer to cv void," then the result is a pointer to the most
01743   //   derived object pointed to by v.
01744   const PointerType *DestPTy = DestTy->getAs<PointerType>();
01745 
01746   bool isDynamicCastToVoid;
01747   QualType SrcRecordTy;
01748   QualType DestRecordTy;
01749   if (DestPTy) {
01750     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
01751     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
01752     DestRecordTy = DestPTy->getPointeeType();
01753   } else {
01754     isDynamicCastToVoid = false;
01755     SrcRecordTy = SrcTy;
01756     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
01757   }
01758 
01759   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
01760 
01761   // C++ [expr.dynamic.cast]p4: 
01762   //   If the value of v is a null pointer value in the pointer case, the result
01763   //   is the null pointer value of type T.
01764   bool ShouldNullCheckSrcValue =
01765       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
01766                                                          SrcRecordTy);
01767 
01768   llvm::BasicBlock *CastNull = nullptr;
01769   llvm::BasicBlock *CastNotNull = nullptr;
01770   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
01771   
01772   if (ShouldNullCheckSrcValue) {
01773     CastNull = createBasicBlock("dynamic_cast.null");
01774     CastNotNull = createBasicBlock("dynamic_cast.notnull");
01775 
01776     llvm::Value *IsNull = Builder.CreateIsNull(Value);
01777     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
01778     EmitBlock(CastNotNull);
01779   }
01780 
01781   if (isDynamicCastToVoid) {
01782     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
01783                                                   DestTy);
01784   } else {
01785     assert(DestRecordTy->isRecordType() &&
01786            "destination type must be a record type!");
01787     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
01788                                                 DestTy, DestRecordTy, CastEnd);
01789   }
01790 
01791   if (ShouldNullCheckSrcValue) {
01792     EmitBranch(CastEnd);
01793 
01794     EmitBlock(CastNull);
01795     EmitBranch(CastEnd);
01796   }
01797 
01798   EmitBlock(CastEnd);
01799 
01800   if (ShouldNullCheckSrcValue) {
01801     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
01802     PHI->addIncoming(Value, CastNotNull);
01803     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
01804 
01805     Value = PHI;
01806   }
01807 
01808   return Value;
01809 }
01810 
01811 void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
01812   RunCleanupsScope Scope(*this);
01813   LValue SlotLV =
01814       MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
01815 
01816   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
01817   for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
01818                                          e = E->capture_init_end();
01819        i != e; ++i, ++CurField) {
01820     // Emit initialization
01821     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
01822     if (CurField->hasCapturedVLAType()) {
01823       auto VAT = CurField->getCapturedVLAType();
01824       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
01825     } else {
01826       ArrayRef<VarDecl *> ArrayIndexes;
01827       if (CurField->getType()->isArrayType())
01828         ArrayIndexes = E->getCaptureInitIndexVars(i);
01829       EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
01830     }
01831   }
01832 }