159486a2dSAnders Carlsson //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===// 259486a2dSAnders Carlsson // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 659486a2dSAnders Carlsson // 759486a2dSAnders Carlsson //===----------------------------------------------------------------------===// 859486a2dSAnders Carlsson // 959486a2dSAnders Carlsson // This contains code dealing with code generation of C++ expressions 1059486a2dSAnders Carlsson // 1159486a2dSAnders Carlsson //===----------------------------------------------------------------------===// 1259486a2dSAnders Carlsson 13fe883422SPeter Collingbourne #include "CGCUDARuntime.h" 145d865c32SJohn McCall #include "CGCXXABI.h" 1591bbb554SDevang Patel #include "CGDebugInfo.h" 163a02247dSChandler Carruth #include "CGObjCRuntime.h" 1788559637SMarco Antognini #include "CodeGenFunction.h" 18de0fe07eSJohn McCall #include "ConstantEmitter.h" 1988559637SMarco Antognini #include "TargetInfo.h" 206368818fSRichard Trieu #include "clang/Basic/CodeGenOptions.h" 21a8e7df36SMark Lacey #include "clang/CodeGen/CGFunctionInfo.h" 22ffd5551bSChandler Carruth #include "llvm/IR/Intrinsics.h" 23bbe277c4SAnders Carlsson 2459486a2dSAnders Carlsson using namespace clang; 2559486a2dSAnders Carlsson using namespace CodeGen; 2659486a2dSAnders Carlsson 27d0a9e807SGeorge Burgess IV namespace { 28d0a9e807SGeorge Burgess IV struct MemberCallInfo { 29d0a9e807SGeorge Burgess IV RequiredArgs ReqArgs; 30d0a9e807SGeorge Burgess IV // Number of prefix arguments for the call. Ignores the `this` pointer. 31d0a9e807SGeorge Burgess IV unsigned PrefixSize; 32d0a9e807SGeorge Burgess IV }; 33d0a9e807SGeorge Burgess IV } 34d0a9e807SGeorge Burgess IV 35d0a9e807SGeorge Burgess IV static MemberCallInfo 36efa956ceSAlexey Samsonov commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD, 37efa956ceSAlexey Samsonov llvm::Value *This, llvm::Value *ImplicitParam, 38efa956ceSAlexey Samsonov QualType ImplicitParamTy, const CallExpr *CE, 39762672a7SRichard Smith CallArgList &Args, CallArgList *RtlArgs) { 40a5bf76bdSAlexey Samsonov assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) || 41a5bf76bdSAlexey Samsonov isa<CXXOperatorCallExpr>(CE)); 4227da15baSAnders Carlsson assert(MD->isInstance() && 43a5bf76bdSAlexey Samsonov "Trying to emit a member or operator call expr on a static method!"); 4427da15baSAnders Carlsson 4527da15baSAnders Carlsson // Push the this ptr. 46034e7270SReid Kleckner const CXXRecordDecl *RD = 47034e7270SReid Kleckner CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD); 48b92d290eSJames Y Knight Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD)); 4927da15baSAnders Carlsson 50ee6bc533STimur Iskhodzhanov // If there is an implicit parameter (e.g. VTT), emit it. 51ee6bc533STimur Iskhodzhanov if (ImplicitParam) { 52ee6bc533STimur Iskhodzhanov Args.add(RValue::get(ImplicitParam), ImplicitParamTy); 53e36a6b3eSAnders Carlsson } 54e36a6b3eSAnders Carlsson 55a729c62bSJohn McCall const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 56916db651SJames Y Knight RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size()); 57d0a9e807SGeorge Burgess IV unsigned PrefixSize = Args.size() - 1; 58a729c62bSJohn McCall 59a729c62bSJohn McCall // And the rest of the call args. 60762672a7SRichard Smith if (RtlArgs) { 61762672a7SRichard Smith // Special case: if the caller emitted the arguments right-to-left already 62762672a7SRichard Smith // (prior to emitting the *this argument), we're done. This happens for 63762672a7SRichard Smith // assignment operators. 64762672a7SRichard Smith Args.addFrom(*RtlArgs); 65762672a7SRichard Smith } else if (CE) { 66a5bf76bdSAlexey Samsonov // Special case: skip first argument of CXXOperatorCall (it is "this"). 678e1162c7SAlexey Samsonov unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0; 68f05779e2SDavid Blaikie CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip), 698e1162c7SAlexey Samsonov CE->getDirectCallee()); 70a5bf76bdSAlexey Samsonov } else { 718e1162c7SAlexey Samsonov assert( 728e1162c7SAlexey Samsonov FPT->getNumParams() == 0 && 738e1162c7SAlexey Samsonov "No CallExpr specified for function with non-zero number of arguments"); 74a5bf76bdSAlexey Samsonov } 75d0a9e807SGeorge Burgess IV return {required, PrefixSize}; 760c0b6d9aSDavid Majnemer } 7727da15baSAnders Carlsson 780c0b6d9aSDavid Majnemer RValue CodeGenFunction::EmitCXXMemberOrOperatorCall( 79b92ab1afSJohn McCall const CXXMethodDecl *MD, const CGCallee &Callee, 80b92ab1afSJohn McCall ReturnValueSlot ReturnValue, 810c0b6d9aSDavid Majnemer llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, 82762672a7SRichard Smith const CallExpr *CE, CallArgList *RtlArgs) { 830c0b6d9aSDavid Majnemer const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 840c0b6d9aSDavid Majnemer CallArgList Args; 85d0a9e807SGeorge Burgess IV MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall( 86762672a7SRichard Smith *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs); 87d0a9e807SGeorge Burgess IV auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall( 88d0a9e807SGeorge Burgess IV Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize); 8909b5bfddSVedant Kumar return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr, 9083446759SJoshua Haberman CE && CE == MustTailCall, 9109b5bfddSVedant Kumar CE ? CE->getExprLoc() : SourceLocation()); 9227da15baSAnders Carlsson } 9327da15baSAnders Carlsson 94ae81bbb4SAlexey Samsonov RValue CodeGenFunction::EmitCXXDestructorCall( 9588559637SMarco Antognini GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy, 96d1c5b28cSPeter Collingbourne llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) { 9788559637SMarco Antognini const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl()); 9888559637SMarco Antognini 9988559637SMarco Antognini assert(!ThisTy.isNull()); 10088559637SMarco Antognini assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() && 10188559637SMarco Antognini "Pointer/Object mixup"); 10288559637SMarco Antognini 10388559637SMarco Antognini LangAS SrcAS = ThisTy.getAddressSpace(); 10488559637SMarco Antognini LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace(); 10588559637SMarco Antognini if (SrcAS != DstAS) { 10688559637SMarco Antognini QualType DstTy = DtorDecl->getThisType(); 10788559637SMarco Antognini llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy); 10888559637SMarco Antognini This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS, 10988559637SMarco Antognini NewType); 11088559637SMarco Antognini } 11188559637SMarco Antognini 1120c0b6d9aSDavid Majnemer CallArgList Args; 11388559637SMarco Antognini commonEmitCXXMemberOrOperatorCall(*this, DtorDecl, This, ImplicitParam, 11488559637SMarco Antognini ImplicitParamTy, CE, Args, nullptr); 115d1c5b28cSPeter Collingbourne return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee, 11683446759SJoshua Haberman ReturnValueSlot(), Args, nullptr, CE && CE == MustTailCall, 11730588a73SErich Keane CE ? CE->getExprLoc() : SourceLocation{}); 118b92ab1afSJohn McCall } 119b92ab1afSJohn McCall 120b92ab1afSJohn McCall RValue CodeGenFunction::EmitCXXPseudoDestructorExpr( 121b92ab1afSJohn McCall const CXXPseudoDestructorExpr *E) { 122b92ab1afSJohn McCall QualType DestroyedType = E->getDestroyedType(); 123b92ab1afSJohn McCall if (DestroyedType.hasStrongOrWeakObjCLifetime()) { 124b92ab1afSJohn McCall // Automatic Reference Counting: 125b92ab1afSJohn McCall // If the pseudo-expression names a retainable object with weak or 126b92ab1afSJohn McCall // strong lifetime, the object shall be released. 127b92ab1afSJohn McCall Expr *BaseExpr = E->getBase(); 128b92ab1afSJohn McCall Address BaseValue = Address::invalid(); 129b92ab1afSJohn McCall Qualifiers BaseQuals; 130b92ab1afSJohn McCall 131b92ab1afSJohn McCall // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 132b92ab1afSJohn McCall if (E->isArrow()) { 133b92ab1afSJohn McCall BaseValue = EmitPointerWithAlignment(BaseExpr); 13416c53ffcSSimon Pilgrim const auto *PTy = BaseExpr->getType()->castAs<PointerType>(); 135b92ab1afSJohn McCall BaseQuals = PTy->getPointeeType().getQualifiers(); 136b92ab1afSJohn McCall } else { 137b92ab1afSJohn McCall LValue BaseLV = EmitLValue(BaseExpr); 138f139ae3dSAkira Hatanaka BaseValue = BaseLV.getAddress(*this); 139b92ab1afSJohn McCall QualType BaseTy = BaseExpr->getType(); 140b92ab1afSJohn McCall BaseQuals = BaseTy.getQualifiers(); 141b92ab1afSJohn McCall } 142b92ab1afSJohn McCall 143b92ab1afSJohn McCall switch (DestroyedType.getObjCLifetime()) { 144b92ab1afSJohn McCall case Qualifiers::OCL_None: 145b92ab1afSJohn McCall case Qualifiers::OCL_ExplicitNone: 146b92ab1afSJohn McCall case Qualifiers::OCL_Autoreleasing: 147b92ab1afSJohn McCall break; 148b92ab1afSJohn McCall 149b92ab1afSJohn McCall case Qualifiers::OCL_Strong: 150b92ab1afSJohn McCall EmitARCRelease(Builder.CreateLoad(BaseValue, 151b92ab1afSJohn McCall DestroyedType.isVolatileQualified()), 152b92ab1afSJohn McCall ARCPreciseLifetime); 153b92ab1afSJohn McCall break; 154b92ab1afSJohn McCall 155b92ab1afSJohn McCall case Qualifiers::OCL_Weak: 156b92ab1afSJohn McCall EmitARCDestroyWeak(BaseValue); 157b92ab1afSJohn McCall break; 158b92ab1afSJohn McCall } 159b92ab1afSJohn McCall } else { 160b92ab1afSJohn McCall // C++ [expr.pseudo]p1: 161b92ab1afSJohn McCall // The result shall only be used as the operand for the function call 162b92ab1afSJohn McCall // operator (), and the result of such a call has type void. The only 163b92ab1afSJohn McCall // effect is the evaluation of the postfix-expression before the dot or 164b92ab1afSJohn McCall // arrow. 165b92ab1afSJohn McCall EmitIgnoredExpr(E->getBase()); 166b92ab1afSJohn McCall } 167b92ab1afSJohn McCall 168b92ab1afSJohn McCall return RValue::get(nullptr); 1690c0b6d9aSDavid Majnemer } 1700c0b6d9aSDavid Majnemer 1713b33c4ecSRafael Espindola static CXXRecordDecl *getCXXRecord(const Expr *E) { 1723b33c4ecSRafael Espindola QualType T = E->getType(); 1733b33c4ecSRafael Espindola if (const PointerType *PTy = T->getAs<PointerType>()) 1743b33c4ecSRafael Espindola T = PTy->getPointeeType(); 1753b33c4ecSRafael Espindola const RecordType *Ty = T->castAs<RecordType>(); 1763b33c4ecSRafael Espindola return cast<CXXRecordDecl>(Ty->getDecl()); 1773b33c4ecSRafael Espindola } 1783b33c4ecSRafael Espindola 17964225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC 18064225794SFrancois Pichet // extensions allowing explicit constructor function call. 18127da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE, 18227da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 1832d2e8707SJohn McCall const Expr *callee = CE->getCallee()->IgnoreParens(); 1842d2e8707SJohn McCall 1852d2e8707SJohn McCall if (isa<BinaryOperator>(callee)) 18627da15baSAnders Carlsson return EmitCXXMemberPointerCallExpr(CE, ReturnValue); 18727da15baSAnders Carlsson 1882d2e8707SJohn McCall const MemberExpr *ME = cast<MemberExpr>(callee); 18927da15baSAnders Carlsson const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); 19027da15baSAnders Carlsson 19127da15baSAnders Carlsson if (MD->isStatic()) { 19227da15baSAnders Carlsson // The method is static, emit it as we would a regular call. 193de6480a3SErich Keane CGCallee callee = 194de6480a3SErich Keane CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD)); 195b92ab1afSJohn McCall return EmitCall(getContext().getPointerType(MD->getType()), callee, CE, 19670b9c01bSAlexey Samsonov ReturnValue); 19727da15baSAnders Carlsson } 19827da15baSAnders Carlsson 199aad4af6dSNico Weber bool HasQualifier = ME->hasQualifier(); 200aad4af6dSNico Weber NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr; 201aad4af6dSNico Weber bool IsArrow = ME->isArrow(); 202ecbe2e97SRafael Espindola const Expr *Base = ME->getBase(); 203aad4af6dSNico Weber 204aad4af6dSNico Weber return EmitCXXMemberOrOperatorMemberCallExpr( 205aad4af6dSNico Weber CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base); 206aad4af6dSNico Weber } 207aad4af6dSNico Weber 208aad4af6dSNico Weber RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( 209aad4af6dSNico Weber const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, 210aad4af6dSNico Weber bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow, 211aad4af6dSNico Weber const Expr *Base) { 212aad4af6dSNico Weber assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE)); 213aad4af6dSNico Weber 214aad4af6dSNico Weber // Compute the object pointer. 215aad4af6dSNico Weber bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier; 216ecbe2e97SRafael Espindola 2178a13c418SCraig Topper const CXXMethodDecl *DevirtualizedMethod = nullptr; 21822461673SAkira Hatanaka if (CanUseVirtualCall && 21922461673SAkira Hatanaka MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) { 2203b33c4ecSRafael Espindola const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 2213b33c4ecSRafael Espindola DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl); 2223b33c4ecSRafael Espindola assert(DevirtualizedMethod); 2233b33c4ecSRafael Espindola const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent(); 2241a7a2cd7SEduardo Caldas const Expr *Inner = Base->IgnoreParenBaseCasts(); 2255bd68794SAlexey Bataev if (DevirtualizedMethod->getReturnType().getCanonicalType() != 2265bd68794SAlexey Bataev MD->getReturnType().getCanonicalType()) 2275bd68794SAlexey Bataev // If the return types are not the same, this might be a case where more 2285bd68794SAlexey Bataev // code needs to run to compensate for it. For example, the derived 2295bd68794SAlexey Bataev // method might return a type that inherits form from the return 2305bd68794SAlexey Bataev // type of MD and has a prefix. 2315bd68794SAlexey Bataev // For now we just avoid devirtualizing these covariant cases. 2325bd68794SAlexey Bataev DevirtualizedMethod = nullptr; 2335bd68794SAlexey Bataev else if (getCXXRecord(Inner) == DevirtualizedClass) 2343b33c4ecSRafael Espindola // If the class of the Inner expression is where the dynamic method 2353b33c4ecSRafael Espindola // is defined, build the this pointer from it. 2363b33c4ecSRafael Espindola Base = Inner; 2373b33c4ecSRafael Espindola else if (getCXXRecord(Base) != DevirtualizedClass) { 2383b33c4ecSRafael Espindola // If the method is defined in a class that is not the best dynamic 2393b33c4ecSRafael Espindola // one or the one of the full expression, we would have to build 2403b33c4ecSRafael Espindola // a derived-to-base cast to compute the correct this pointer, but 2413b33c4ecSRafael Espindola // we don't have support for that yet, so do a virtual call. 2428a13c418SCraig Topper DevirtualizedMethod = nullptr; 2433b33c4ecSRafael Espindola } 2443b33c4ecSRafael Espindola } 245ecbe2e97SRafael Espindola 2463ced2397SRichard Smith bool TrivialForCodegen = 2473ced2397SRichard Smith MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion()); 2483ced2397SRichard Smith bool TrivialAssignment = 2493ced2397SRichard Smith TrivialForCodegen && 2503ced2397SRichard Smith (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) && 2513ced2397SRichard Smith !MD->getParent()->mayInsertExtraPadding(); 2523ced2397SRichard Smith 253762672a7SRichard Smith // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment 254762672a7SRichard Smith // operator before the LHS. 255762672a7SRichard Smith CallArgList RtlArgStorage; 256762672a7SRichard Smith CallArgList *RtlArgs = nullptr; 2573ced2397SRichard Smith LValue TrivialAssignmentRHS; 258762672a7SRichard Smith if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 259762672a7SRichard Smith if (OCE->isAssignmentOp()) { 2603ced2397SRichard Smith if (TrivialAssignment) { 2613ced2397SRichard Smith TrivialAssignmentRHS = EmitLValue(CE->getArg(1)); 2623ced2397SRichard Smith } else { 263762672a7SRichard Smith RtlArgs = &RtlArgStorage; 264762672a7SRichard Smith EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(), 265762672a7SRichard Smith drop_begin(CE->arguments(), 1), CE->getDirectCallee(), 266a560ccf2SRichard Smith /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft); 267762672a7SRichard Smith } 268762672a7SRichard Smith } 2693ced2397SRichard Smith } 270762672a7SRichard Smith 2711860b520SIvan A. Kosarev LValue This; 2721860b520SIvan A. Kosarev if (IsArrow) { 2731860b520SIvan A. Kosarev LValueBaseInfo BaseInfo; 2741860b520SIvan A. Kosarev TBAAAccessInfo TBAAInfo; 2751860b520SIvan A. Kosarev Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo); 2761860b520SIvan A. Kosarev This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo); 2771860b520SIvan A. Kosarev } else { 2781860b520SIvan A. Kosarev This = EmitLValue(Base); 2791860b520SIvan A. Kosarev } 280ecbe2e97SRafael Espindola 281ab4f7f14SJames Y Knight if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 282ab4f7f14SJames Y Knight // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's 283ab4f7f14SJames Y Knight // constructing a new complete object of type Ctor. 284ab4f7f14SJames Y Knight assert(!RtlArgs); 285ab4f7f14SJames Y Knight assert(ReturnValue.isNull() && "Constructor shouldn't have return value"); 286ab4f7f14SJames Y Knight CallArgList Args; 287ab4f7f14SJames Y Knight commonEmitCXXMemberOrOperatorCall( 288f139ae3dSAkira Hatanaka *this, Ctor, This.getPointer(*this), /*ImplicitParam=*/nullptr, 289ab4f7f14SJames Y Knight /*ImplicitParamTy=*/QualType(), CE, Args, nullptr); 290ab4f7f14SJames Y Knight 291ab4f7f14SJames Y Knight EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false, 292f139ae3dSAkira Hatanaka /*Delegating=*/false, This.getAddress(*this), Args, 293ab4f7f14SJames Y Knight AggValueSlot::DoesNotOverlap, CE->getExprLoc(), 294ab4f7f14SJames Y Knight /*NewPointerIsChecked=*/false); 295ab4f7f14SJames Y Knight return RValue::get(nullptr); 296ab4f7f14SJames Y Knight } 29727da15baSAnders Carlsson 2983ced2397SRichard Smith if (TrivialForCodegen) { 2993ced2397SRichard Smith if (isa<CXXDestructorDecl>(MD)) 3003ced2397SRichard Smith return RValue::get(nullptr); 3013ced2397SRichard Smith 3023ced2397SRichard Smith if (TrivialAssignment) { 30322653bacSSebastian Redl // We don't like to generate the trivial copy/move assignment operator 30422653bacSSebastian Redl // when it isn't necessary; just produce the proper effect here. 3053ced2397SRichard Smith // It's important that we use the result of EmitLValue here rather than 3063ced2397SRichard Smith // emitting call arguments, in order to preserve TBAA information from 3073ced2397SRichard Smith // the RHS. 308762672a7SRichard Smith LValue RHS = isa<CXXOperatorCallExpr>(CE) 3093ced2397SRichard Smith ? TrivialAssignmentRHS 310762672a7SRichard Smith : EmitLValue(*CE->arg_begin()); 3111860b520SIvan A. Kosarev EmitAggregateAssign(This, RHS, CE->getType()); 312f139ae3dSAkira Hatanaka return RValue::get(This.getPointer(*this)); 31327da15baSAnders Carlsson } 3143ced2397SRichard Smith 3153ced2397SRichard Smith assert(MD->getParent()->mayInsertExtraPadding() && 3163ced2397SRichard Smith "unknown trivial member function"); 317aad4af6dSNico Weber } 31864225794SFrancois Pichet 3190d635f53SJohn McCall // Compute the function type we're calling. 3203abfe958SNico Weber const CXXMethodDecl *CalleeDecl = 3213abfe958SNico Weber DevirtualizedMethod ? DevirtualizedMethod : MD; 3228a13c418SCraig Topper const CGFunctionInfo *FInfo = nullptr; 3233abfe958SNico Weber if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) 3248d2a19b4SRafael Espindola FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 325d1c5b28cSPeter Collingbourne GlobalDecl(Dtor, Dtor_Complete)); 32664225794SFrancois Pichet else 327ade60977SEli Friedman FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl); 3280d635f53SJohn McCall 329e7de47efSReid Kleckner llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo); 3300d635f53SJohn McCall 331d98f5d78SIvan Krasin // C++11 [class.mfct.non-static]p2: 332d98f5d78SIvan Krasin // If a non-static member function of a class X is called for an object that 333d98f5d78SIvan Krasin // is not of type X, or of a type derived from X, the behavior is undefined. 334d98f5d78SIvan Krasin SourceLocation CallLoc; 335d98f5d78SIvan Krasin ASTContext &C = getContext(); 336d98f5d78SIvan Krasin if (CE) 337d98f5d78SIvan Krasin CallLoc = CE->getExprLoc(); 338d98f5d78SIvan Krasin 33934b1fd6aSVedant Kumar SanitizerSet SkippedChecks; 340ffd7c887SVedant Kumar if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) { 341ffd7c887SVedant Kumar auto *IOA = CMCE->getImplicitObjectArgument(); 342ffd7c887SVedant Kumar bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA); 343ffd7c887SVedant Kumar if (IsImplicitObjectCXXThis) 344ffd7c887SVedant Kumar SkippedChecks.set(SanitizerKind::Alignment, true); 345ffd7c887SVedant Kumar if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA)) 34634b1fd6aSVedant Kumar SkippedChecks.set(SanitizerKind::Null, true); 347ffd7c887SVedant Kumar } 348f139ae3dSAkira Hatanaka EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc, 349f139ae3dSAkira Hatanaka This.getPointer(*this), 350ab4f7f14SJames Y Knight C.getRecordType(CalleeDecl->getParent()), 35134b1fd6aSVedant Kumar /*Alignment=*/CharUnits::Zero(), SkippedChecks); 352d98f5d78SIvan Krasin 35327da15baSAnders Carlsson // C++ [class.virtual]p12: 35427da15baSAnders Carlsson // Explicit qualification with the scope operator (5.1) suppresses the 35527da15baSAnders Carlsson // virtual call mechanism. 35627da15baSAnders Carlsson // 35727da15baSAnders Carlsson // We also don't emit a virtual call if the base expression has a record type 35827da15baSAnders Carlsson // because then we know what the type is. 3593b33c4ecSRafael Espindola bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod; 3609dc6eef7SStephen Lin 361b92d290eSJames Y Knight if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) { 36219cee187SStephen Lin assert(CE->arg_begin() == CE->arg_end() && 3639dc6eef7SStephen Lin "Destructor shouldn't have explicit parameters"); 3649dc6eef7SStephen Lin assert(ReturnValue.isNull() && "Destructor shouldn't have return value"); 3659dc6eef7SStephen Lin if (UseVirtualCall) { 366f139ae3dSAkira Hatanaka CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete, 367f139ae3dSAkira Hatanaka This.getAddress(*this), 3681860b520SIvan A. Kosarev cast<CXXMemberCallExpr>(CE)); 36927da15baSAnders Carlsson } else { 370d1c5b28cSPeter Collingbourne GlobalDecl GD(Dtor, Dtor_Complete); 371b92ab1afSJohn McCall CGCallee Callee; 372b92d290eSJames Y Knight if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier) 373b92d290eSJames Y Knight Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty); 3743b33c4ecSRafael Espindola else if (!DevirtualizedMethod) 375d1c5b28cSPeter Collingbourne Callee = 376d1c5b28cSPeter Collingbourne CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD); 37749e860b2SRafael Espindola else { 378d1c5b28cSPeter Collingbourne Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD); 37949e860b2SRafael Espindola } 380b92d290eSJames Y Knight 38188559637SMarco Antognini QualType ThisTy = 38288559637SMarco Antognini IsArrow ? Base->getType()->getPointeeType() : Base->getType(); 383f139ae3dSAkira Hatanaka EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy, 384b92d290eSJames Y Knight /*ImplicitParam=*/nullptr, 38530588a73SErich Keane /*ImplicitParamTy=*/QualType(), CE); 38627da15baSAnders Carlsson } 3878a13c418SCraig Topper return RValue::get(nullptr); 3889dc6eef7SStephen Lin } 3899dc6eef7SStephen Lin 390b92d290eSJames Y Knight // FIXME: Uses of 'MD' past this point need to be audited. We may need to use 391b92d290eSJames Y Knight // 'CalleeDecl' instead. 392b92d290eSJames Y Knight 393b92ab1afSJohn McCall CGCallee Callee; 394ab4f7f14SJames Y Knight if (UseVirtualCall) { 395f139ae3dSAkira Hatanaka Callee = CGCallee::forVirtual(CE, MD, This.getAddress(*this), Ty); 39627da15baSAnders Carlsson } else { 3971a7488afSPeter Collingbourne if (SanOpts.has(SanitizerKind::CFINVCall) && 3981a7488afSPeter Collingbourne MD->getParent()->isDynamicClass()) { 3996010880bSPeter Collingbourne llvm::Value *VTable; 4006010880bSPeter Collingbourne const CXXRecordDecl *RD; 401f139ae3dSAkira Hatanaka std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr( 402f139ae3dSAkira Hatanaka *this, This.getAddress(*this), CalleeDecl->getParent()); 403f2ceec48SStephen Kelly EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc()); 4041a7488afSPeter Collingbourne } 4051a7488afSPeter Collingbourne 406aad4af6dSNico Weber if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier) 407aad4af6dSNico Weber Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty); 4083b33c4ecSRafael Espindola else if (!DevirtualizedMethod) 409de6480a3SErich Keane Callee = 410de6480a3SErich Keane CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD)); 41149e860b2SRafael Espindola else { 412de6480a3SErich Keane Callee = 413de6480a3SErich Keane CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty), 414de6480a3SErich Keane GlobalDecl(DevirtualizedMethod)); 41549e860b2SRafael Espindola } 41627da15baSAnders Carlsson } 41727da15baSAnders Carlsson 418f1749427STimur Iskhodzhanov if (MD->isVirtual()) { 4191860b520SIvan A. Kosarev Address NewThisAddr = 4201860b520SIvan A. Kosarev CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall( 421f139ae3dSAkira Hatanaka *this, CalleeDecl, This.getAddress(*this), UseVirtualCall); 4221860b520SIvan A. Kosarev This.setAddress(NewThisAddr); 423f1749427STimur Iskhodzhanov } 42488fd439aSTimur Iskhodzhanov 425018f266bSVedant Kumar return EmitCXXMemberOrOperatorCall( 426f139ae3dSAkira Hatanaka CalleeDecl, Callee, ReturnValue, This.getPointer(*this), 427018f266bSVedant Kumar /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs); 42827da15baSAnders Carlsson } 42927da15baSAnders Carlsson 43027da15baSAnders Carlsson RValue 43127da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 43227da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 43327da15baSAnders Carlsson const BinaryOperator *BO = 43427da15baSAnders Carlsson cast<BinaryOperator>(E->getCallee()->IgnoreParens()); 43527da15baSAnders Carlsson const Expr *BaseExpr = BO->getLHS(); 43627da15baSAnders Carlsson const Expr *MemFnExpr = BO->getRHS(); 43727da15baSAnders Carlsson 4381cd399c9SSimon Pilgrim const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>(); 4391cd399c9SSimon Pilgrim const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>(); 4401cd399c9SSimon Pilgrim const auto *RD = 4411cd399c9SSimon Pilgrim cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl()); 44227da15baSAnders Carlsson 44327da15baSAnders Carlsson // Emit the 'this' pointer. 4447f416cc4SJohn McCall Address This = Address::invalid(); 445e302792bSJohn McCall if (BO->getOpcode() == BO_PtrMemI) 4467f416cc4SJohn McCall This = EmitPointerWithAlignment(BaseExpr); 44727da15baSAnders Carlsson else 448f139ae3dSAkira Hatanaka This = EmitLValue(BaseExpr).getAddress(*this); 44927da15baSAnders Carlsson 4507f416cc4SJohn McCall EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(), 451e30752c9SRichard Smith QualType(MPT->getClass(), 0)); 45269d0d262SRichard Smith 453bde62d78SRichard Smith // Get the member function pointer. 454bde62d78SRichard Smith llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr); 455bde62d78SRichard Smith 456475999dcSJohn McCall // Ask the ABI to load the callee. Note that This is modified. 4577f416cc4SJohn McCall llvm::Value *ThisPtrForCall = nullptr; 458b92ab1afSJohn McCall CGCallee Callee = 4597f416cc4SJohn McCall CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, 4607f416cc4SJohn McCall ThisPtrForCall, MemFnPtr, MPT); 46127da15baSAnders Carlsson 46227da15baSAnders Carlsson CallArgList Args; 46327da15baSAnders Carlsson 46427da15baSAnders Carlsson QualType ThisType = 46527da15baSAnders Carlsson getContext().getPointerType(getContext().getTagDeclType(RD)); 46627da15baSAnders Carlsson 46727da15baSAnders Carlsson // Push the this ptr. 4687f416cc4SJohn McCall Args.add(RValue::get(ThisPtrForCall), ThisType); 46927da15baSAnders Carlsson 470916db651SJames Y Knight RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1); 4718dda7b27SJohn McCall 47227da15baSAnders Carlsson // And the rest of the call args 473419996ccSGeorge Burgess IV EmitCallArgs(Args, FPT, E->arguments()); 474d0a9e807SGeorge Burgess IV return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required, 475d0a9e807SGeorge Burgess IV /*PrefixSize=*/0), 47683446759SJoshua Haberman Callee, ReturnValue, Args, nullptr, E == MustTailCall, 47783446759SJoshua Haberman E->getExprLoc()); 47827da15baSAnders Carlsson } 47927da15baSAnders Carlsson 48027da15baSAnders Carlsson RValue 48127da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 48227da15baSAnders Carlsson const CXXMethodDecl *MD, 48327da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 48427da15baSAnders Carlsson assert(MD->isInstance() && 48527da15baSAnders Carlsson "Trying to emit a member call expr on a static method!"); 486aad4af6dSNico Weber return EmitCXXMemberOrOperatorMemberCallExpr( 487aad4af6dSNico Weber E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr, 488aad4af6dSNico Weber /*IsArrow=*/false, E->getArg(0)); 48927da15baSAnders Carlsson } 49027da15baSAnders Carlsson 491fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 492fe883422SPeter Collingbourne ReturnValueSlot ReturnValue) { 493fe883422SPeter Collingbourne return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue); 494fe883422SPeter Collingbourne } 495fe883422SPeter Collingbourne 496fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF, 4977f416cc4SJohn McCall Address DestPtr, 498fde961dbSEli Friedman const CXXRecordDecl *Base) { 499fde961dbSEli Friedman if (Base->isEmpty()) 500fde961dbSEli Friedman return; 501fde961dbSEli Friedman 5027f416cc4SJohn McCall DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty); 503fde961dbSEli Friedman 504fde961dbSEli Friedman const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base); 5058671c6e0SDavid Majnemer CharUnits NVSize = Layout.getNonVirtualSize(); 5068671c6e0SDavid Majnemer 5078671c6e0SDavid Majnemer // We cannot simply zero-initialize the entire base sub-object if vbptrs are 5088671c6e0SDavid Majnemer // present, they are initialized by the most derived class before calling the 5098671c6e0SDavid Majnemer // constructor. 5108671c6e0SDavid Majnemer SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores; 5118671c6e0SDavid Majnemer Stores.emplace_back(CharUnits::Zero(), NVSize); 5128671c6e0SDavid Majnemer 5138671c6e0SDavid Majnemer // Each store is split by the existence of a vbptr. 5148671c6e0SDavid Majnemer CharUnits VBPtrWidth = CGF.getPointerSize(); 5158671c6e0SDavid Majnemer std::vector<CharUnits> VBPtrOffsets = 5168671c6e0SDavid Majnemer CGF.CGM.getCXXABI().getVBPtrOffsets(Base); 5178671c6e0SDavid Majnemer for (CharUnits VBPtrOffset : VBPtrOffsets) { 5187f980d84SDavid Majnemer // Stop before we hit any virtual base pointers located in virtual bases. 5197f980d84SDavid Majnemer if (VBPtrOffset >= NVSize) 5207f980d84SDavid Majnemer break; 5218671c6e0SDavid Majnemer std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val(); 5228671c6e0SDavid Majnemer CharUnits LastStoreOffset = LastStore.first; 5238671c6e0SDavid Majnemer CharUnits LastStoreSize = LastStore.second; 5248671c6e0SDavid Majnemer 5258671c6e0SDavid Majnemer CharUnits SplitBeforeOffset = LastStoreOffset; 5268671c6e0SDavid Majnemer CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset; 5278671c6e0SDavid Majnemer assert(!SplitBeforeSize.isNegative() && "negative store size!"); 5288671c6e0SDavid Majnemer if (!SplitBeforeSize.isZero()) 5298671c6e0SDavid Majnemer Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize); 5308671c6e0SDavid Majnemer 5318671c6e0SDavid Majnemer CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth; 5328671c6e0SDavid Majnemer CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset; 5338671c6e0SDavid Majnemer assert(!SplitAfterSize.isNegative() && "negative store size!"); 5348671c6e0SDavid Majnemer if (!SplitAfterSize.isZero()) 5358671c6e0SDavid Majnemer Stores.emplace_back(SplitAfterOffset, SplitAfterSize); 5368671c6e0SDavid Majnemer } 537fde961dbSEli Friedman 538fde961dbSEli Friedman // If the type contains a pointer to data member we can't memset it to zero. 539fde961dbSEli Friedman // Instead, create a null constant and copy it to the destination. 540fde961dbSEli Friedman // TODO: there are other patterns besides zero that we can usefully memset, 541fde961dbSEli Friedman // like -1, which happens to be the pattern used by member-pointers. 542fde961dbSEli Friedman // TODO: isZeroInitializable can be over-conservative in the case where a 543fde961dbSEli Friedman // virtual base contains a member pointer. 5448671c6e0SDavid Majnemer llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base); 5458671c6e0SDavid Majnemer if (!NullConstantForBase->isNullValue()) { 5468671c6e0SDavid Majnemer llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable( 5478671c6e0SDavid Majnemer CGF.CGM.getModule(), NullConstantForBase->getType(), 5488671c6e0SDavid Majnemer /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, 5498671c6e0SDavid Majnemer NullConstantForBase, Twine()); 5507f416cc4SJohn McCall 5517f416cc4SJohn McCall CharUnits Align = std::max(Layout.getNonVirtualAlignment(), 5527f416cc4SJohn McCall DestPtr.getAlignment()); 553c79099e0SGuillaume Chatelet NullVariable->setAlignment(Align.getAsAlign()); 5547f416cc4SJohn McCall 5557f416cc4SJohn McCall Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align); 556fde961dbSEli Friedman 557fde961dbSEli Friedman // Get and call the appropriate llvm.memcpy overload. 5588671c6e0SDavid Majnemer for (std::pair<CharUnits, CharUnits> Store : Stores) { 5598671c6e0SDavid Majnemer CharUnits StoreOffset = Store.first; 5608671c6e0SDavid Majnemer CharUnits StoreSize = Store.second; 5618671c6e0SDavid Majnemer llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 5628671c6e0SDavid Majnemer CGF.Builder.CreateMemCpy( 5638671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 5648671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset), 5658671c6e0SDavid Majnemer StoreSizeVal); 566fde961dbSEli Friedman } 567fde961dbSEli Friedman 568fde961dbSEli Friedman // Otherwise, just memset the whole thing to zero. This is legal 569fde961dbSEli Friedman // because in LLVM, all default initializers (other than the ones we just 570fde961dbSEli Friedman // handled above) are guaranteed to have a bit pattern of all zeros. 5718671c6e0SDavid Majnemer } else { 5728671c6e0SDavid Majnemer for (std::pair<CharUnits, CharUnits> Store : Stores) { 5738671c6e0SDavid Majnemer CharUnits StoreOffset = Store.first; 5748671c6e0SDavid Majnemer CharUnits StoreSize = Store.second; 5758671c6e0SDavid Majnemer llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 5768671c6e0SDavid Majnemer CGF.Builder.CreateMemSet( 5778671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 5788671c6e0SDavid Majnemer CGF.Builder.getInt8(0), StoreSizeVal); 5798671c6e0SDavid Majnemer } 5808671c6e0SDavid Majnemer } 581fde961dbSEli Friedman } 582fde961dbSEli Friedman 58327da15baSAnders Carlsson void 5847a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, 5857a626f63SJohn McCall AggValueSlot Dest) { 5867a626f63SJohn McCall assert(!Dest.isIgnored() && "Must have a destination!"); 58727da15baSAnders Carlsson const CXXConstructorDecl *CD = E->getConstructor(); 588630c76efSDouglas Gregor 589630c76efSDouglas Gregor // If we require zero initialization before (or instead of) calling the 590630c76efSDouglas Gregor // constructor, as can be the case with a non-user-provided default 59103535265SArgyrios Kyrtzidis // constructor, emit the zero initialization now, unless destination is 59203535265SArgyrios Kyrtzidis // already zeroed. 593fde961dbSEli Friedman if (E->requiresZeroInitialization() && !Dest.isZeroed()) { 594fde961dbSEli Friedman switch (E->getConstructionKind()) { 595fde961dbSEli Friedman case CXXConstructExpr::CK_Delegating: 596fde961dbSEli Friedman case CXXConstructExpr::CK_Complete: 5977f416cc4SJohn McCall EmitNullInitialization(Dest.getAddress(), E->getType()); 598fde961dbSEli Friedman break; 599fde961dbSEli Friedman case CXXConstructExpr::CK_VirtualBase: 600fde961dbSEli Friedman case CXXConstructExpr::CK_NonVirtualBase: 6017f416cc4SJohn McCall EmitNullBaseClassInitialization(*this, Dest.getAddress(), 6027f416cc4SJohn McCall CD->getParent()); 603fde961dbSEli Friedman break; 604fde961dbSEli Friedman } 605fde961dbSEli Friedman } 606630c76efSDouglas Gregor 607630c76efSDouglas Gregor // If this is a call to a trivial default constructor, do nothing. 608630c76efSDouglas Gregor if (CD->isTrivial() && CD->isDefaultConstructor()) 60927da15baSAnders Carlsson return; 610630c76efSDouglas Gregor 6118ea46b66SJohn McCall // Elide the constructor if we're constructing from a temporary. 6129c6890a7SRichard Smith if (getLangOpts().ElideConstructors && E->isElidable()) { 613d9308aa3SMatheus Izvekov // FIXME: This only handles the simplest case, where the source object 614d9308aa3SMatheus Izvekov // is passed directly as the first argument to the constructor. 615d9308aa3SMatheus Izvekov // This should also handle stepping though implicit casts and 616d9308aa3SMatheus Izvekov // conversion sequences which involve two steps, with a 617d9308aa3SMatheus Izvekov // conversion operator followed by a converting constructor. 618d9308aa3SMatheus Izvekov const Expr *SrcObj = E->getArg(0); 619d9308aa3SMatheus Izvekov assert(SrcObj->isTemporaryObject(getContext(), CD->getParent())); 620d9308aa3SMatheus Izvekov assert( 621d9308aa3SMatheus Izvekov getContext().hasSameUnqualifiedType(E->getType(), SrcObj->getType())); 622d9308aa3SMatheus Izvekov EmitAggExpr(SrcObj, Dest); 62327da15baSAnders Carlsson return; 62427da15baSAnders Carlsson } 625630c76efSDouglas Gregor 626e7545b33SAlexey Bataev if (const ArrayType *arrayType 627e7545b33SAlexey Bataev = getContext().getAsArrayType(E->getType())) { 62837605182SSerge Pavlov EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E, 62937605182SSerge Pavlov Dest.isSanitizerChecked()); 630f677a8e9SJohn McCall } else { 631bceca20aSCameron Esfahani CXXCtorType Type = Ctor_Complete; 632271c3681SAlexis Hunt bool ForVirtualBase = false; 63361535005SDouglas Gregor bool Delegating = false; 634271c3681SAlexis Hunt 635271c3681SAlexis Hunt switch (E->getConstructionKind()) { 636271c3681SAlexis Hunt case CXXConstructExpr::CK_Delegating: 63761bc1737SAlexis Hunt // We should be emitting a constructor; GlobalDecl will assert this 63861bc1737SAlexis Hunt Type = CurGD.getCtorType(); 63961535005SDouglas Gregor Delegating = true; 640271c3681SAlexis Hunt break; 64161bc1737SAlexis Hunt 642271c3681SAlexis Hunt case CXXConstructExpr::CK_Complete: 643271c3681SAlexis Hunt Type = Ctor_Complete; 644271c3681SAlexis Hunt break; 645271c3681SAlexis Hunt 646271c3681SAlexis Hunt case CXXConstructExpr::CK_VirtualBase: 647271c3681SAlexis Hunt ForVirtualBase = true; 648f3b3ccdaSAdrian Prantl LLVM_FALLTHROUGH; 649271c3681SAlexis Hunt 650271c3681SAlexis Hunt case CXXConstructExpr::CK_NonVirtualBase: 651271c3681SAlexis Hunt Type = Ctor_Base; 652271c3681SAlexis Hunt } 653e11f9ce9SAnders Carlsson 65427da15baSAnders Carlsson // Call the constructor. 655094c7266SAnastasia Stulova EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E); 65627da15baSAnders Carlsson } 657e11f9ce9SAnders Carlsson } 65827da15baSAnders Carlsson 6597f416cc4SJohn McCall void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, 66050198098SFariborz Jahanian const Expr *Exp) { 6615d413781SJohn McCall if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp)) 662e988bdacSFariborz Jahanian Exp = E->getSubExpr(); 663e988bdacSFariborz Jahanian assert(isa<CXXConstructExpr>(Exp) && 664e988bdacSFariborz Jahanian "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"); 665e988bdacSFariborz Jahanian const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp); 666e988bdacSFariborz Jahanian const CXXConstructorDecl *CD = E->getConstructor(); 667e988bdacSFariborz Jahanian RunCleanupsScope Scope(*this); 668e988bdacSFariborz Jahanian 669e988bdacSFariborz Jahanian // If we require zero initialization before (or instead of) calling the 670e988bdacSFariborz Jahanian // constructor, as can be the case with a non-user-provided default 671e988bdacSFariborz Jahanian // constructor, emit the zero initialization now. 672e988bdacSFariborz Jahanian // FIXME. Do I still need this for a copy ctor synthesis? 673e988bdacSFariborz Jahanian if (E->requiresZeroInitialization()) 674e988bdacSFariborz Jahanian EmitNullInitialization(Dest, E->getType()); 675e988bdacSFariborz Jahanian 67699da11cfSChandler Carruth assert(!getContext().getAsConstantArrayType(E->getType()) 67799da11cfSChandler Carruth && "EmitSynthesizedCXXCopyCtor - Copied-in Array"); 678525bf650SAlexey Samsonov EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E); 679e988bdacSFariborz Jahanian } 680e988bdacSFariborz Jahanian 6818ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF, 6828ed55a54SJohn McCall const CXXNewExpr *E) { 68321122cf6SAnders Carlsson if (!E->isArray()) 6843eb55cfeSKen Dyck return CharUnits::Zero(); 68521122cf6SAnders Carlsson 6867ec4b434SJohn McCall // No cookie is required if the operator new[] being used is the 6877ec4b434SJohn McCall // reserved placement operator new[]. 6887ec4b434SJohn McCall if (E->getOperatorNew()->isReservedGlobalPlacementOperator()) 6893eb55cfeSKen Dyck return CharUnits::Zero(); 690399f499fSAnders Carlsson 691284c48ffSJohn McCall return CGF.CGM.getCXXABI().GetArrayCookieSize(E); 69259486a2dSAnders Carlsson } 69359486a2dSAnders Carlsson 694036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, 695036f2f6bSJohn McCall const CXXNewExpr *e, 696f862eb6aSSebastian Redl unsigned minElements, 697036f2f6bSJohn McCall llvm::Value *&numElements, 698036f2f6bSJohn McCall llvm::Value *&sizeWithoutCookie) { 699036f2f6bSJohn McCall QualType type = e->getAllocatedType(); 70059486a2dSAnders Carlsson 701036f2f6bSJohn McCall if (!e->isArray()) { 702036f2f6bSJohn McCall CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 703036f2f6bSJohn McCall sizeWithoutCookie 704036f2f6bSJohn McCall = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity()); 705036f2f6bSJohn McCall return sizeWithoutCookie; 70605fc5be3SDouglas Gregor } 70759486a2dSAnders Carlsson 708036f2f6bSJohn McCall // The width of size_t. 709036f2f6bSJohn McCall unsigned sizeWidth = CGF.SizeTy->getBitWidth(); 710036f2f6bSJohn McCall 7118ed55a54SJohn McCall // Figure out the cookie size. 712036f2f6bSJohn McCall llvm::APInt cookieSize(sizeWidth, 713036f2f6bSJohn McCall CalculateCookiePadding(CGF, e).getQuantity()); 7148ed55a54SJohn McCall 71559486a2dSAnders Carlsson // Emit the array size expression. 7167648fb46SArgyrios Kyrtzidis // We multiply the size of all dimensions for NumElements. 7177648fb46SArgyrios Kyrtzidis // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6. 718de0fe07eSJohn McCall numElements = 719b9fb121aSRichard Smith ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType()); 72007527621SNick Lewycky if (!numElements) 721b9fb121aSRichard Smith numElements = CGF.EmitScalarExpr(*e->getArraySize()); 722036f2f6bSJohn McCall assert(isa<llvm::IntegerType>(numElements->getType())); 7238ed55a54SJohn McCall 724036f2f6bSJohn McCall // The number of elements can be have an arbitrary integer type; 725036f2f6bSJohn McCall // essentially, we need to multiply it by a constant factor, add a 726036f2f6bSJohn McCall // cookie size, and verify that the result is representable as a 727036f2f6bSJohn McCall // size_t. That's just a gloss, though, and it's wrong in one 728036f2f6bSJohn McCall // important way: if the count is negative, it's an error even if 729036f2f6bSJohn McCall // the cookie size would bring the total size >= 0. 7306ab2fa8fSDouglas Gregor bool isSigned 731b9fb121aSRichard Smith = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType(); 7322192fe50SChris Lattner llvm::IntegerType *numElementsType 733036f2f6bSJohn McCall = cast<llvm::IntegerType>(numElements->getType()); 734036f2f6bSJohn McCall unsigned numElementsWidth = numElementsType->getBitWidth(); 735036f2f6bSJohn McCall 736036f2f6bSJohn McCall // Compute the constant factor. 737036f2f6bSJohn McCall llvm::APInt arraySizeMultiplier(sizeWidth, 1); 7387648fb46SArgyrios Kyrtzidis while (const ConstantArrayType *CAT 739036f2f6bSJohn McCall = CGF.getContext().getAsConstantArrayType(type)) { 740036f2f6bSJohn McCall type = CAT->getElementType(); 741036f2f6bSJohn McCall arraySizeMultiplier *= CAT->getSize(); 7427648fb46SArgyrios Kyrtzidis } 74359486a2dSAnders Carlsson 744036f2f6bSJohn McCall CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 745036f2f6bSJohn McCall llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity()); 746036f2f6bSJohn McCall typeSizeMultiplier *= arraySizeMultiplier; 747036f2f6bSJohn McCall 748036f2f6bSJohn McCall // This will be a size_t. 749036f2f6bSJohn McCall llvm::Value *size; 75032ac583dSChris Lattner 75132ac583dSChris Lattner // If someone is doing 'new int[42]' there is no need to do a dynamic check. 75232ac583dSChris Lattner // Don't bloat the -O0 code. 753036f2f6bSJohn McCall if (llvm::ConstantInt *numElementsC = 754036f2f6bSJohn McCall dyn_cast<llvm::ConstantInt>(numElements)) { 755036f2f6bSJohn McCall const llvm::APInt &count = numElementsC->getValue(); 75632ac583dSChris Lattner 757036f2f6bSJohn McCall bool hasAnyOverflow = false; 75832ac583dSChris Lattner 759036f2f6bSJohn McCall // If 'count' was a negative number, it's an overflow. 760036f2f6bSJohn McCall if (isSigned && count.isNegative()) 761036f2f6bSJohn McCall hasAnyOverflow = true; 7628ed55a54SJohn McCall 763036f2f6bSJohn McCall // We want to do all this arithmetic in size_t. If numElements is 764036f2f6bSJohn McCall // wider than that, check whether it's already too big, and if so, 765036f2f6bSJohn McCall // overflow. 766036f2f6bSJohn McCall else if (numElementsWidth > sizeWidth && 767036f2f6bSJohn McCall numElementsWidth - sizeWidth > count.countLeadingZeros()) 768036f2f6bSJohn McCall hasAnyOverflow = true; 769036f2f6bSJohn McCall 770036f2f6bSJohn McCall // Okay, compute a count at the right width. 771036f2f6bSJohn McCall llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth); 772036f2f6bSJohn McCall 773f862eb6aSSebastian Redl // If there is a brace-initializer, we cannot allocate fewer elements than 774f862eb6aSSebastian Redl // there are initializers. If we do, that's treated like an overflow. 775f862eb6aSSebastian Redl if (adjustedCount.ult(minElements)) 776f862eb6aSSebastian Redl hasAnyOverflow = true; 777f862eb6aSSebastian Redl 778036f2f6bSJohn McCall // Scale numElements by that. This might overflow, but we don't 779036f2f6bSJohn McCall // care because it only overflows if allocationSize does, too, and 780036f2f6bSJohn McCall // if that overflows then we shouldn't use this. 781036f2f6bSJohn McCall numElements = llvm::ConstantInt::get(CGF.SizeTy, 782036f2f6bSJohn McCall adjustedCount * arraySizeMultiplier); 783036f2f6bSJohn McCall 784036f2f6bSJohn McCall // Compute the size before cookie, and track whether it overflowed. 785036f2f6bSJohn McCall bool overflow; 786036f2f6bSJohn McCall llvm::APInt allocationSize 787036f2f6bSJohn McCall = adjustedCount.umul_ov(typeSizeMultiplier, overflow); 788036f2f6bSJohn McCall hasAnyOverflow |= overflow; 789036f2f6bSJohn McCall 790036f2f6bSJohn McCall // Add in the cookie, and check whether it's overflowed. 791036f2f6bSJohn McCall if (cookieSize != 0) { 792036f2f6bSJohn McCall // Save the current size without a cookie. This shouldn't be 793036f2f6bSJohn McCall // used if there was overflow. 794036f2f6bSJohn McCall sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 795036f2f6bSJohn McCall 796036f2f6bSJohn McCall allocationSize = allocationSize.uadd_ov(cookieSize, overflow); 797036f2f6bSJohn McCall hasAnyOverflow |= overflow; 7988ed55a54SJohn McCall } 7998ed55a54SJohn McCall 800036f2f6bSJohn McCall // On overflow, produce a -1 so operator new will fail. 801455f42c9SAaron Ballman if (hasAnyOverflow) { 802455f42c9SAaron Ballman size = llvm::Constant::getAllOnesValue(CGF.SizeTy); 803455f42c9SAaron Ballman } else { 804036f2f6bSJohn McCall size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 805455f42c9SAaron Ballman } 80632ac583dSChris Lattner 807036f2f6bSJohn McCall // Otherwise, we might need to use the overflow intrinsics. 8088ed55a54SJohn McCall } else { 809f862eb6aSSebastian Redl // There are up to five conditions we need to test for: 810036f2f6bSJohn McCall // 1) if isSigned, we need to check whether numElements is negative; 811036f2f6bSJohn McCall // 2) if numElementsWidth > sizeWidth, we need to check whether 812036f2f6bSJohn McCall // numElements is larger than something representable in size_t; 813f862eb6aSSebastian Redl // 3) if minElements > 0, we need to check whether numElements is smaller 814f862eb6aSSebastian Redl // than that. 815f862eb6aSSebastian Redl // 4) we need to compute 816036f2f6bSJohn McCall // sizeWithoutCookie := numElements * typeSizeMultiplier 817036f2f6bSJohn McCall // and check whether it overflows; and 818f862eb6aSSebastian Redl // 5) if we need a cookie, we need to compute 819036f2f6bSJohn McCall // size := sizeWithoutCookie + cookieSize 820036f2f6bSJohn McCall // and check whether it overflows. 8218ed55a54SJohn McCall 8228a13c418SCraig Topper llvm::Value *hasOverflow = nullptr; 8238ed55a54SJohn McCall 824036f2f6bSJohn McCall // If numElementsWidth > sizeWidth, then one way or another, we're 825036f2f6bSJohn McCall // going to have to do a comparison for (2), and this happens to 826036f2f6bSJohn McCall // take care of (1), too. 827036f2f6bSJohn McCall if (numElementsWidth > sizeWidth) { 828036f2f6bSJohn McCall llvm::APInt threshold(numElementsWidth, 1); 829036f2f6bSJohn McCall threshold <<= sizeWidth; 8308ed55a54SJohn McCall 831036f2f6bSJohn McCall llvm::Value *thresholdV 832036f2f6bSJohn McCall = llvm::ConstantInt::get(numElementsType, threshold); 833036f2f6bSJohn McCall 834036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV); 835036f2f6bSJohn McCall numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy); 836036f2f6bSJohn McCall 837036f2f6bSJohn McCall // Otherwise, if we're signed, we want to sext up to size_t. 838036f2f6bSJohn McCall } else if (isSigned) { 839036f2f6bSJohn McCall if (numElementsWidth < sizeWidth) 840036f2f6bSJohn McCall numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy); 841036f2f6bSJohn McCall 842036f2f6bSJohn McCall // If there's a non-1 type size multiplier, then we can do the 843036f2f6bSJohn McCall // signedness check at the same time as we do the multiply 844036f2f6bSJohn McCall // because a negative number times anything will cause an 845f862eb6aSSebastian Redl // unsigned overflow. Otherwise, we have to do it here. But at least 846f862eb6aSSebastian Redl // in this case, we can subsume the >= minElements check. 847036f2f6bSJohn McCall if (typeSizeMultiplier == 1) 848036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateICmpSLT(numElements, 849f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements)); 850036f2f6bSJohn McCall 851036f2f6bSJohn McCall // Otherwise, zext up to size_t if necessary. 852036f2f6bSJohn McCall } else if (numElementsWidth < sizeWidth) { 853036f2f6bSJohn McCall numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy); 854036f2f6bSJohn McCall } 855036f2f6bSJohn McCall 856036f2f6bSJohn McCall assert(numElements->getType() == CGF.SizeTy); 857036f2f6bSJohn McCall 858f862eb6aSSebastian Redl if (minElements) { 859f862eb6aSSebastian Redl // Don't allow allocation of fewer elements than we have initializers. 860f862eb6aSSebastian Redl if (!hasOverflow) { 861f862eb6aSSebastian Redl hasOverflow = CGF.Builder.CreateICmpULT(numElements, 862f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements)); 863f862eb6aSSebastian Redl } else if (numElementsWidth > sizeWidth) { 864f862eb6aSSebastian Redl // The other existing overflow subsumes this check. 865f862eb6aSSebastian Redl // We do an unsigned comparison, since any signed value < -1 is 866f862eb6aSSebastian Redl // taken care of either above or below. 867f862eb6aSSebastian Redl hasOverflow = CGF.Builder.CreateOr(hasOverflow, 868f862eb6aSSebastian Redl CGF.Builder.CreateICmpULT(numElements, 869f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements))); 870f862eb6aSSebastian Redl } 871f862eb6aSSebastian Redl } 872f862eb6aSSebastian Redl 873036f2f6bSJohn McCall size = numElements; 874036f2f6bSJohn McCall 875036f2f6bSJohn McCall // Multiply by the type size if necessary. This multiplier 876036f2f6bSJohn McCall // includes all the factors for nested arrays. 8778ed55a54SJohn McCall // 878036f2f6bSJohn McCall // This step also causes numElements to be scaled up by the 879036f2f6bSJohn McCall // nested-array factor if necessary. Overflow on this computation 880036f2f6bSJohn McCall // can be ignored because the result shouldn't be used if 881036f2f6bSJohn McCall // allocation fails. 882036f2f6bSJohn McCall if (typeSizeMultiplier != 1) { 8838799caeeSJames Y Knight llvm::Function *umul_with_overflow 8848d375cefSBenjamin Kramer = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy); 8858ed55a54SJohn McCall 886036f2f6bSJohn McCall llvm::Value *tsmV = 887036f2f6bSJohn McCall llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier); 888036f2f6bSJohn McCall llvm::Value *result = 88943f9bb73SDavid Blaikie CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV}); 8908ed55a54SJohn McCall 891036f2f6bSJohn McCall llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 892036f2f6bSJohn McCall if (hasOverflow) 893036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 8948ed55a54SJohn McCall else 895036f2f6bSJohn McCall hasOverflow = overflowed; 89659486a2dSAnders Carlsson 897036f2f6bSJohn McCall size = CGF.Builder.CreateExtractValue(result, 0); 898036f2f6bSJohn McCall 899036f2f6bSJohn McCall // Also scale up numElements by the array size multiplier. 900036f2f6bSJohn McCall if (arraySizeMultiplier != 1) { 901036f2f6bSJohn McCall // If the base element type size is 1, then we can re-use the 902036f2f6bSJohn McCall // multiply we just did. 903036f2f6bSJohn McCall if (typeSize.isOne()) { 904036f2f6bSJohn McCall assert(arraySizeMultiplier == typeSizeMultiplier); 905036f2f6bSJohn McCall numElements = size; 906036f2f6bSJohn McCall 907036f2f6bSJohn McCall // Otherwise we need a separate multiply. 908036f2f6bSJohn McCall } else { 909036f2f6bSJohn McCall llvm::Value *asmV = 910036f2f6bSJohn McCall llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier); 911036f2f6bSJohn McCall numElements = CGF.Builder.CreateMul(numElements, asmV); 912036f2f6bSJohn McCall } 913036f2f6bSJohn McCall } 914036f2f6bSJohn McCall } else { 915036f2f6bSJohn McCall // numElements doesn't need to be scaled. 916036f2f6bSJohn McCall assert(arraySizeMultiplier == 1); 917036f2f6bSJohn McCall } 918036f2f6bSJohn McCall 919036f2f6bSJohn McCall // Add in the cookie size if necessary. 920036f2f6bSJohn McCall if (cookieSize != 0) { 921036f2f6bSJohn McCall sizeWithoutCookie = size; 922036f2f6bSJohn McCall 9238799caeeSJames Y Knight llvm::Function *uadd_with_overflow 9248d375cefSBenjamin Kramer = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy); 925036f2f6bSJohn McCall 926036f2f6bSJohn McCall llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize); 927036f2f6bSJohn McCall llvm::Value *result = 92843f9bb73SDavid Blaikie CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV}); 929036f2f6bSJohn McCall 930036f2f6bSJohn McCall llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 931036f2f6bSJohn McCall if (hasOverflow) 932036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 933036f2f6bSJohn McCall else 934036f2f6bSJohn McCall hasOverflow = overflowed; 935036f2f6bSJohn McCall 936036f2f6bSJohn McCall size = CGF.Builder.CreateExtractValue(result, 0); 937036f2f6bSJohn McCall } 938036f2f6bSJohn McCall 939036f2f6bSJohn McCall // If we had any possibility of dynamic overflow, make a select to 940036f2f6bSJohn McCall // overwrite 'size' with an all-ones value, which should cause 941036f2f6bSJohn McCall // operator new to throw. 942036f2f6bSJohn McCall if (hasOverflow) 943455f42c9SAaron Ballman size = CGF.Builder.CreateSelect(hasOverflow, 944455f42c9SAaron Ballman llvm::Constant::getAllOnesValue(CGF.SizeTy), 945036f2f6bSJohn McCall size); 946036f2f6bSJohn McCall } 947036f2f6bSJohn McCall 948036f2f6bSJohn McCall if (cookieSize == 0) 949036f2f6bSJohn McCall sizeWithoutCookie = size; 950036f2f6bSJohn McCall else 951036f2f6bSJohn McCall assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?"); 952036f2f6bSJohn McCall 953036f2f6bSJohn McCall return size; 95459486a2dSAnders Carlsson } 95559486a2dSAnders Carlsson 956f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, 957e78fac51SRichard Smith QualType AllocType, Address NewPtr, 958e78fac51SRichard Smith AggValueSlot::Overlap_t MayOverlap) { 9591c96bc5dSRichard Smith // FIXME: Refactor with EmitExprAsInit. 96047fb9508SJohn McCall switch (CGF.getEvaluationKind(AllocType)) { 96147fb9508SJohn McCall case TEK_Scalar: 962a2c1124fSDavid Blaikie CGF.EmitScalarInit(Init, nullptr, 9637f416cc4SJohn McCall CGF.MakeAddrLValue(NewPtr, AllocType), false); 96447fb9508SJohn McCall return; 96547fb9508SJohn McCall case TEK_Complex: 9667f416cc4SJohn McCall CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType), 96747fb9508SJohn McCall /*isInit*/ true); 96847fb9508SJohn McCall return; 96947fb9508SJohn McCall case TEK_Aggregate: { 9707a626f63SJohn McCall AggValueSlot Slot 9717f416cc4SJohn McCall = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(), 9728d6fc958SJohn McCall AggValueSlot::IsDestructed, 97346759f4fSJohn McCall AggValueSlot::DoesNotNeedGCBarriers, 974e78fac51SRichard Smith AggValueSlot::IsNotAliased, 97537605182SSerge Pavlov MayOverlap, AggValueSlot::IsNotZeroed, 97637605182SSerge Pavlov AggValueSlot::IsSanitizerChecked); 9777a626f63SJohn McCall CGF.EmitAggExpr(Init, Slot); 97847fb9508SJohn McCall return; 9797a626f63SJohn McCall } 980d5202e09SFariborz Jahanian } 98147fb9508SJohn McCall llvm_unreachable("bad evaluation kind"); 98247fb9508SJohn McCall } 983d5202e09SFariborz Jahanian 984fb901c7aSDavid Blaikie void CodeGenFunction::EmitNewArrayInitializer( 985fb901c7aSDavid Blaikie const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy, 9867f416cc4SJohn McCall Address BeginPtr, llvm::Value *NumElements, 98706a67e2cSRichard Smith llvm::Value *AllocSizeWithoutCookie) { 98806a67e2cSRichard Smith // If we have a type with trivial initialization and no initializer, 98906a67e2cSRichard Smith // there's nothing to do. 9906047f07eSSebastian Redl if (!E->hasInitializer()) 99106a67e2cSRichard Smith return; 992b66b08efSFariborz Jahanian 9937f416cc4SJohn McCall Address CurPtr = BeginPtr; 994d5202e09SFariborz Jahanian 99506a67e2cSRichard Smith unsigned InitListElements = 0; 996f862eb6aSSebastian Redl 997f862eb6aSSebastian Redl const Expr *Init = E->getInitializer(); 9987f416cc4SJohn McCall Address EndOfInit = Address::invalid(); 99906a67e2cSRichard Smith QualType::DestructionKind DtorKind = ElementType.isDestructedType(); 100006a67e2cSRichard Smith EHScopeStack::stable_iterator Cleanup; 100106a67e2cSRichard Smith llvm::Instruction *CleanupDominator = nullptr; 10021c96bc5dSRichard Smith 10037f416cc4SJohn McCall CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType); 10047f416cc4SJohn McCall CharUnits ElementAlign = 10057f416cc4SJohn McCall BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize); 10067f416cc4SJohn McCall 10070511d23aSRichard Smith // Attempt to perform zero-initialization using memset. 10080511d23aSRichard Smith auto TryMemsetInitialization = [&]() -> bool { 10090511d23aSRichard Smith // FIXME: If the type is a pointer-to-data-member under the Itanium ABI, 10100511d23aSRichard Smith // we can initialize with a memset to -1. 10110511d23aSRichard Smith if (!CGM.getTypes().isZeroInitializable(ElementType)) 10120511d23aSRichard Smith return false; 10130511d23aSRichard Smith 10140511d23aSRichard Smith // Optimization: since zero initialization will just set the memory 10150511d23aSRichard Smith // to all zeroes, generate a single memset to do it in one shot. 10160511d23aSRichard Smith 10170511d23aSRichard Smith // Subtract out the size of any elements we've already initialized. 10180511d23aSRichard Smith auto *RemainingSize = AllocSizeWithoutCookie; 10190511d23aSRichard Smith if (InitListElements) { 10200511d23aSRichard Smith // We know this can't overflow; we check this when doing the allocation. 10210511d23aSRichard Smith auto *InitializedSize = llvm::ConstantInt::get( 10220511d23aSRichard Smith RemainingSize->getType(), 10230511d23aSRichard Smith getContext().getTypeSizeInChars(ElementType).getQuantity() * 10240511d23aSRichard Smith InitListElements); 10250511d23aSRichard Smith RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize); 10260511d23aSRichard Smith } 10270511d23aSRichard Smith 10280511d23aSRichard Smith // Create the memset. 10290511d23aSRichard Smith Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false); 10300511d23aSRichard Smith return true; 10310511d23aSRichard Smith }; 10320511d23aSRichard Smith 1033f862eb6aSSebastian Redl // If the initializer is an initializer list, first do the explicit elements. 1034f862eb6aSSebastian Redl if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 10350511d23aSRichard Smith // Initializing from a (braced) string literal is a special case; the init 10360511d23aSRichard Smith // list element does not initialize a (single) array element. 10370511d23aSRichard Smith if (ILE->isStringLiteralInit()) { 10380511d23aSRichard Smith // Initialize the initial portion of length equal to that of the string 10390511d23aSRichard Smith // literal. The allocation must be for at least this much; we emitted a 10400511d23aSRichard Smith // check for that earlier. 10410511d23aSRichard Smith AggValueSlot Slot = 10420511d23aSRichard Smith AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(), 10430511d23aSRichard Smith AggValueSlot::IsDestructed, 10440511d23aSRichard Smith AggValueSlot::DoesNotNeedGCBarriers, 1045e78fac51SRichard Smith AggValueSlot::IsNotAliased, 104637605182SSerge Pavlov AggValueSlot::DoesNotOverlap, 104737605182SSerge Pavlov AggValueSlot::IsNotZeroed, 104837605182SSerge Pavlov AggValueSlot::IsSanitizerChecked); 10490511d23aSRichard Smith EmitAggExpr(ILE->getInit(0), Slot); 10500511d23aSRichard Smith 10510511d23aSRichard Smith // Move past these elements. 10520511d23aSRichard Smith InitListElements = 10530511d23aSRichard Smith cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 10540511d23aSRichard Smith ->getSize().getZExtValue(); 10550511d23aSRichard Smith CurPtr = 105642eb658fSNikita Popov Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(), 105742eb658fSNikita Popov CurPtr.getPointer(), 10580511d23aSRichard Smith Builder.getSize(InitListElements), 10590511d23aSRichard Smith "string.init.end"), 10600511d23aSRichard Smith CurPtr.getAlignment().alignmentAtOffset(InitListElements * 10610511d23aSRichard Smith ElementSize)); 10620511d23aSRichard Smith 10630511d23aSRichard Smith // Zero out the rest, if any remain. 10640511d23aSRichard Smith llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 10650511d23aSRichard Smith if (!ConstNum || !ConstNum->equalsInt(InitListElements)) { 10660511d23aSRichard Smith bool OK = TryMemsetInitialization(); 10670511d23aSRichard Smith (void)OK; 10680511d23aSRichard Smith assert(OK && "couldn't memset character type?"); 10690511d23aSRichard Smith } 10700511d23aSRichard Smith return; 10710511d23aSRichard Smith } 10720511d23aSRichard Smith 107306a67e2cSRichard Smith InitListElements = ILE->getNumInits(); 1074f62290a1SChad Rosier 10751c96bc5dSRichard Smith // If this is a multi-dimensional array new, we will initialize multiple 10761c96bc5dSRichard Smith // elements with each init list element. 10771c96bc5dSRichard Smith QualType AllocType = E->getAllocatedType(); 10781c96bc5dSRichard Smith if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>( 10791c96bc5dSRichard Smith AllocType->getAsArrayTypeUnsafe())) { 1080fb901c7aSDavid Blaikie ElementTy = ConvertTypeForMem(AllocType); 10817f416cc4SJohn McCall CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy); 108206a67e2cSRichard Smith InitListElements *= getContext().getConstantArrayElementCount(CAT); 10831c96bc5dSRichard Smith } 10841c96bc5dSRichard Smith 108506a67e2cSRichard Smith // Enter a partial-destruction Cleanup if necessary. 108606a67e2cSRichard Smith if (needsEHCleanup(DtorKind)) { 108706a67e2cSRichard Smith // In principle we could tell the Cleanup where we are more 1088f62290a1SChad Rosier // directly, but the control flow can get so varied here that it 1089f62290a1SChad Rosier // would actually be quite complex. Therefore we go through an 1090f62290a1SChad Rosier // alloca. 10917f416cc4SJohn McCall EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(), 10927f416cc4SJohn McCall "array.init.end"); 10937f416cc4SJohn McCall CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit); 10947f416cc4SJohn McCall pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit, 10957f416cc4SJohn McCall ElementType, ElementAlign, 109606a67e2cSRichard Smith getDestroyer(DtorKind)); 109706a67e2cSRichard Smith Cleanup = EHStack.stable_begin(); 1098f62290a1SChad Rosier } 1099f62290a1SChad Rosier 11007f416cc4SJohn McCall CharUnits StartAlign = CurPtr.getAlignment(); 1101f862eb6aSSebastian Redl for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) { 1102f62290a1SChad Rosier // Tell the cleanup that it needs to destroy up to this 1103f62290a1SChad Rosier // element. TODO: some of these stores can be trivially 1104f62290a1SChad Rosier // observed to be unnecessary. 11057f416cc4SJohn McCall if (EndOfInit.isValid()) { 11067f416cc4SJohn McCall auto FinishedPtr = 11077f416cc4SJohn McCall Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType()); 11087f416cc4SJohn McCall Builder.CreateStore(FinishedPtr, EndOfInit); 11097f416cc4SJohn McCall } 111006a67e2cSRichard Smith // FIXME: If the last initializer is an incomplete initializer list for 111106a67e2cSRichard Smith // an array, and we have an array filler, we can fold together the two 111206a67e2cSRichard Smith // initialization loops. 11131c96bc5dSRichard Smith StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), 1114e78fac51SRichard Smith ILE->getInit(i)->getType(), CurPtr, 1115e78fac51SRichard Smith AggValueSlot::DoesNotOverlap); 111642eb658fSNikita Popov CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(), 111742eb658fSNikita Popov CurPtr.getPointer(), 11187f416cc4SJohn McCall Builder.getSize(1), 11197f416cc4SJohn McCall "array.exp.next"), 11207f416cc4SJohn McCall StartAlign.alignmentAtOffset((i + 1) * ElementSize)); 1121f862eb6aSSebastian Redl } 1122f862eb6aSSebastian Redl 1123f862eb6aSSebastian Redl // The remaining elements are filled with the array filler expression. 1124f862eb6aSSebastian Redl Init = ILE->getArrayFiller(); 11251c96bc5dSRichard Smith 112606a67e2cSRichard Smith // Extract the initializer for the individual array elements by pulling 112706a67e2cSRichard Smith // out the array filler from all the nested initializer lists. This avoids 112806a67e2cSRichard Smith // generating a nested loop for the initialization. 112906a67e2cSRichard Smith while (Init && Init->getType()->isConstantArrayType()) { 113006a67e2cSRichard Smith auto *SubILE = dyn_cast<InitListExpr>(Init); 113106a67e2cSRichard Smith if (!SubILE) 113206a67e2cSRichard Smith break; 113306a67e2cSRichard Smith assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?"); 113406a67e2cSRichard Smith Init = SubILE->getArrayFiller(); 1135f862eb6aSSebastian Redl } 1136f862eb6aSSebastian Redl 113706a67e2cSRichard Smith // Switch back to initializing one base element at a time. 1138481de0edSNikita Popov CurPtr = Builder.CreateElementBitCast(CurPtr, BeginPtr.getElementType()); 1139f62290a1SChad Rosier } 1140e6c980c4SChandler Carruth 1141454a7cdfSRichard Smith // If all elements have already been initialized, skip any further 1142454a7cdfSRichard Smith // initialization. 1143454a7cdfSRichard Smith llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 1144454a7cdfSRichard Smith if (ConstNum && ConstNum->getZExtValue() <= InitListElements) { 1145454a7cdfSRichard Smith // If there was a Cleanup, deactivate it. 1146454a7cdfSRichard Smith if (CleanupDominator) 1147454a7cdfSRichard Smith DeactivateCleanupBlock(Cleanup, CleanupDominator); 1148454a7cdfSRichard Smith return; 1149454a7cdfSRichard Smith } 1150454a7cdfSRichard Smith 1151454a7cdfSRichard Smith assert(Init && "have trailing elements to initialize but no initializer"); 1152454a7cdfSRichard Smith 115306a67e2cSRichard Smith // If this is a constructor call, try to optimize it out, and failing that 115406a67e2cSRichard Smith // emit a single loop to initialize all remaining elements. 1155454a7cdfSRichard Smith if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 11566047f07eSSebastian Redl CXXConstructorDecl *Ctor = CCE->getConstructor(); 1157d153103cSDouglas Gregor if (Ctor->isTrivial()) { 115805fc5be3SDouglas Gregor // If new expression did not specify value-initialization, then there 115905fc5be3SDouglas Gregor // is no initialization. 11606047f07eSSebastian Redl if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty()) 116105fc5be3SDouglas Gregor return; 116205fc5be3SDouglas Gregor 116306a67e2cSRichard Smith if (TryMemsetInitialization()) 11643a202f60SAnders Carlsson return; 11653a202f60SAnders Carlsson } 116605fc5be3SDouglas Gregor 116706a67e2cSRichard Smith // Store the new Cleanup position for irregular Cleanups. 116806a67e2cSRichard Smith // 116906a67e2cSRichard Smith // FIXME: Share this cleanup with the constructor call emission rather than 117006a67e2cSRichard Smith // having it create a cleanup of its own. 11717f416cc4SJohn McCall if (EndOfInit.isValid()) 11727f416cc4SJohn McCall Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 117306a67e2cSRichard Smith 117406a67e2cSRichard Smith // Emit a constructor call loop to initialize the remaining elements. 117506a67e2cSRichard Smith if (InitListElements) 117606a67e2cSRichard Smith NumElements = Builder.CreateSub( 117706a67e2cSRichard Smith NumElements, 117806a67e2cSRichard Smith llvm::ConstantInt::get(NumElements->getType(), InitListElements)); 117970b9c01bSAlexey Samsonov EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE, 118037605182SSerge Pavlov /*NewPointerIsChecked*/true, 118148ddcf2cSEli Friedman CCE->requiresZeroInitialization()); 118205fc5be3SDouglas Gregor return; 11836047f07eSSebastian Redl } 118406a67e2cSRichard Smith 118506a67e2cSRichard Smith // If this is value-initialization, we can usually use memset. 118606a67e2cSRichard Smith ImplicitValueInitExpr IVIE(ElementType); 1187454a7cdfSRichard Smith if (isa<ImplicitValueInitExpr>(Init)) { 118806a67e2cSRichard Smith if (TryMemsetInitialization()) 118906a67e2cSRichard Smith return; 119006a67e2cSRichard Smith 119106a67e2cSRichard Smith // Switch to an ImplicitValueInitExpr for the element type. This handles 119206a67e2cSRichard Smith // only one case: multidimensional array new of pointers to members. In 119306a67e2cSRichard Smith // all other cases, we already have an initializer for the array element. 119406a67e2cSRichard Smith Init = &IVIE; 119506a67e2cSRichard Smith } 119606a67e2cSRichard Smith 119706a67e2cSRichard Smith // At this point we should have found an initializer for the individual 119806a67e2cSRichard Smith // elements of the array. 119906a67e2cSRichard Smith assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) && 120006a67e2cSRichard Smith "got wrong type of element to initialize"); 120106a67e2cSRichard Smith 1202454a7cdfSRichard Smith // If we have an empty initializer list, we can usually use memset. 1203454a7cdfSRichard Smith if (auto *ILE = dyn_cast<InitListExpr>(Init)) 1204454a7cdfSRichard Smith if (ILE->getNumInits() == 0 && TryMemsetInitialization()) 1205d5202e09SFariborz Jahanian return; 120659486a2dSAnders Carlsson 1207cb77930dSYunzhong Gao // If we have a struct whose every field is value-initialized, we can 1208cb77930dSYunzhong Gao // usually use memset. 1209cb77930dSYunzhong Gao if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 1210cb77930dSYunzhong Gao if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 1211cb77930dSYunzhong Gao if (RType->getDecl()->isStruct()) { 1212872307e2SRichard Smith unsigned NumElements = 0; 1213872307e2SRichard Smith if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl())) 1214872307e2SRichard Smith NumElements = CXXRD->getNumBases(); 1215cb77930dSYunzhong Gao for (auto *Field : RType->getDecl()->fields()) 1216cb77930dSYunzhong Gao if (!Field->isUnnamedBitfield()) 1217872307e2SRichard Smith ++NumElements; 1218872307e2SRichard Smith // FIXME: Recurse into nested InitListExprs. 1219872307e2SRichard Smith if (ILE->getNumInits() == NumElements) 1220cb77930dSYunzhong Gao for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 1221cb77930dSYunzhong Gao if (!isa<ImplicitValueInitExpr>(ILE->getInit(i))) 1222872307e2SRichard Smith --NumElements; 1223872307e2SRichard Smith if (ILE->getNumInits() == NumElements && TryMemsetInitialization()) 1224cb77930dSYunzhong Gao return; 1225cb77930dSYunzhong Gao } 1226cb77930dSYunzhong Gao } 1227cb77930dSYunzhong Gao } 1228cb77930dSYunzhong Gao 122906a67e2cSRichard Smith // Create the loop blocks. 123006a67e2cSRichard Smith llvm::BasicBlock *EntryBB = Builder.GetInsertBlock(); 123106a67e2cSRichard Smith llvm::BasicBlock *LoopBB = createBasicBlock("new.loop"); 123206a67e2cSRichard Smith llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end"); 123359486a2dSAnders Carlsson 123406a67e2cSRichard Smith // Find the end of the array, hoisted out of the loop. 123506a67e2cSRichard Smith llvm::Value *EndPtr = 123642eb658fSNikita Popov Builder.CreateInBoundsGEP(BeginPtr.getElementType(), BeginPtr.getPointer(), 123742eb658fSNikita Popov NumElements, "array.end"); 123806a67e2cSRichard Smith 123906a67e2cSRichard Smith // If the number of elements isn't constant, we have to now check if there is 124006a67e2cSRichard Smith // anything left to initialize. 124106a67e2cSRichard Smith if (!ConstNum) { 12427f416cc4SJohn McCall llvm::Value *IsEmpty = 12437f416cc4SJohn McCall Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty"); 124406a67e2cSRichard Smith Builder.CreateCondBr(IsEmpty, ContBB, LoopBB); 124506a67e2cSRichard Smith } 124606a67e2cSRichard Smith 124706a67e2cSRichard Smith // Enter the loop. 124806a67e2cSRichard Smith EmitBlock(LoopBB); 124906a67e2cSRichard Smith 125006a67e2cSRichard Smith // Set up the current-element phi. 125106a67e2cSRichard Smith llvm::PHINode *CurPtrPhi = 12527f416cc4SJohn McCall Builder.CreatePHI(CurPtr.getType(), 2, "array.cur"); 12537f416cc4SJohn McCall CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB); 12547f416cc4SJohn McCall 12557f416cc4SJohn McCall CurPtr = Address(CurPtrPhi, ElementAlign); 125606a67e2cSRichard Smith 125706a67e2cSRichard Smith // Store the new Cleanup position for irregular Cleanups. 12587f416cc4SJohn McCall if (EndOfInit.isValid()) 12597f416cc4SJohn McCall Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 126006a67e2cSRichard Smith 126106a67e2cSRichard Smith // Enter a partial-destruction Cleanup if necessary. 126206a67e2cSRichard Smith if (!CleanupDominator && needsEHCleanup(DtorKind)) { 12637f416cc4SJohn McCall pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(), 12647f416cc4SJohn McCall ElementType, ElementAlign, 126506a67e2cSRichard Smith getDestroyer(DtorKind)); 126606a67e2cSRichard Smith Cleanup = EHStack.stable_begin(); 126706a67e2cSRichard Smith CleanupDominator = Builder.CreateUnreachable(); 126806a67e2cSRichard Smith } 126906a67e2cSRichard Smith 127006a67e2cSRichard Smith // Emit the initializer into this element. 1271e78fac51SRichard Smith StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr, 1272e78fac51SRichard Smith AggValueSlot::DoesNotOverlap); 127306a67e2cSRichard Smith 127406a67e2cSRichard Smith // Leave the Cleanup if we entered one. 127506a67e2cSRichard Smith if (CleanupDominator) { 127606a67e2cSRichard Smith DeactivateCleanupBlock(Cleanup, CleanupDominator); 127706a67e2cSRichard Smith CleanupDominator->eraseFromParent(); 127806a67e2cSRichard Smith } 127906a67e2cSRichard Smith 128006a67e2cSRichard Smith // Advance to the next element by adjusting the pointer type as necessary. 128106a67e2cSRichard Smith llvm::Value *NextPtr = 12827f416cc4SJohn McCall Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1, 12837f416cc4SJohn McCall "array.next"); 128406a67e2cSRichard Smith 128506a67e2cSRichard Smith // Check whether we've gotten to the end of the array and, if so, 128606a67e2cSRichard Smith // exit the loop. 128706a67e2cSRichard Smith llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend"); 128806a67e2cSRichard Smith Builder.CreateCondBr(IsEnd, ContBB, LoopBB); 128906a67e2cSRichard Smith CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock()); 129006a67e2cSRichard Smith 129106a67e2cSRichard Smith EmitBlock(ContBB); 129206a67e2cSRichard Smith } 129306a67e2cSRichard Smith 129406a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E, 1295fb901c7aSDavid Blaikie QualType ElementType, llvm::Type *ElementTy, 12967f416cc4SJohn McCall Address NewPtr, llvm::Value *NumElements, 129706a67e2cSRichard Smith llvm::Value *AllocSizeWithoutCookie) { 12989b479666SDavid Blaikie ApplyDebugLocation DL(CGF, E); 129906a67e2cSRichard Smith if (E->isArray()) 1300fb901c7aSDavid Blaikie CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements, 130106a67e2cSRichard Smith AllocSizeWithoutCookie); 130206a67e2cSRichard Smith else if (const Expr *Init = E->getInitializer()) 1303e78fac51SRichard Smith StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr, 1304e78fac51SRichard Smith AggValueSlot::DoesNotOverlap); 130559486a2dSAnders Carlsson } 130659486a2dSAnders Carlsson 13078d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly 13088d0dc31dSRichard Smith /// created by new-expressions and delete-expressions. 13098d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF, 1310b92ab1afSJohn McCall const FunctionDecl *CalleeDecl, 13118d0dc31dSRichard Smith const FunctionProtoType *CalleeType, 13128d0dc31dSRichard Smith const CallArgList &Args) { 13133933adddSJames Y Knight llvm::CallBase *CallOrInvoke; 1314b92ab1afSJohn McCall llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl); 1315de6480a3SErich Keane CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl)); 13168d0dc31dSRichard Smith RValue RV = 1317f770683fSPeter Collingbourne CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall( 131849a3ad21SRui Ueyama Args, CalleeType, /*ChainCall=*/false), 1319b92ab1afSJohn McCall Callee, ReturnValueSlot(), Args, &CallOrInvoke); 13208d0dc31dSRichard Smith 13218d0dc31dSRichard Smith /// C++1y [expr.new]p10: 13228d0dc31dSRichard Smith /// [In a new-expression,] an implementation is allowed to omit a call 13238d0dc31dSRichard Smith /// to a replaceable global allocation function. 13248d0dc31dSRichard Smith /// 13258d0dc31dSRichard Smith /// We model such elidable calls with the 'builtin' attribute. 1326b92ab1afSJohn McCall llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr); 1327b92ab1afSJohn McCall if (CalleeDecl->isReplaceableGlobalAllocationFunction() && 13286956d587SRafael Espindola Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) { 13293f4d00bcSArthur Eubanks CallOrInvoke->addFnAttr(llvm::Attribute::Builtin); 13308d0dc31dSRichard Smith } 13318d0dc31dSRichard Smith 13328d0dc31dSRichard Smith return RV; 13338d0dc31dSRichard Smith } 13348d0dc31dSRichard Smith 1335760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 1336fa752f23SEric Fiselier const CallExpr *TheCall, 1337760520bcSRichard Smith bool IsDelete) { 1338760520bcSRichard Smith CallArgList Args; 1339d7098ff2SReid Kleckner EmitCallArgs(Args, Type, TheCall->arguments()); 1340760520bcSRichard Smith // Find the allocation or deallocation function that we're calling. 1341760520bcSRichard Smith ASTContext &Ctx = getContext(); 1342760520bcSRichard Smith DeclarationName Name = Ctx.DeclarationNames 1343760520bcSRichard Smith .getCXXOperatorName(IsDelete ? OO_Delete : OO_New); 1344fa752f23SEric Fiselier 1345760520bcSRichard Smith for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name)) 1346599bed75SRichard Smith if (auto *FD = dyn_cast<FunctionDecl>(Decl)) 1347599bed75SRichard Smith if (Ctx.hasSameType(FD->getType(), QualType(Type, 0))) 1348fa752f23SEric Fiselier return EmitNewDeleteCall(*this, FD, Type, Args); 1349760520bcSRichard Smith llvm_unreachable("predeclared global operator new/delete is missing"); 1350760520bcSRichard Smith } 1351760520bcSRichard Smith 13525b34958bSRichard Smith namespace { 13535b34958bSRichard Smith /// The parameters to pass to a usual operator delete. 13545b34958bSRichard Smith struct UsualDeleteParams { 13555b34958bSRichard Smith bool DestroyingDelete = false; 13565b34958bSRichard Smith bool Size = false; 13575b34958bSRichard Smith bool Alignment = false; 13585b34958bSRichard Smith }; 13595b34958bSRichard Smith } 13605b34958bSRichard Smith 13615b34958bSRichard Smith static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) { 13625b34958bSRichard Smith UsualDeleteParams Params; 13635b34958bSRichard Smith 13645b34958bSRichard Smith const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 1365b2f0f057SRichard Smith auto AI = FPT->param_type_begin(), AE = FPT->param_type_end(); 1366e9abe648SDaniel Jasper 1367b2f0f057SRichard Smith // The first argument is always a void*. 1368b2f0f057SRichard Smith ++AI; 1369b2f0f057SRichard Smith 13705b34958bSRichard Smith // The next parameter may be a std::destroying_delete_t. 13715b34958bSRichard Smith if (FD->isDestroyingOperatorDelete()) { 13725b34958bSRichard Smith Params.DestroyingDelete = true; 13735b34958bSRichard Smith assert(AI != AE); 13745b34958bSRichard Smith ++AI; 13755b34958bSRichard Smith } 1376b2f0f057SRichard Smith 13775b34958bSRichard Smith // Figure out what other parameters we should be implicitly passing. 1378b2f0f057SRichard Smith if (AI != AE && (*AI)->isIntegerType()) { 13795b34958bSRichard Smith Params.Size = true; 1380b2f0f057SRichard Smith ++AI; 1381b2f0f057SRichard Smith } 1382b2f0f057SRichard Smith 1383b2f0f057SRichard Smith if (AI != AE && (*AI)->isAlignValT()) { 13845b34958bSRichard Smith Params.Alignment = true; 1385b2f0f057SRichard Smith ++AI; 1386b2f0f057SRichard Smith } 1387b2f0f057SRichard Smith 1388b2f0f057SRichard Smith assert(AI == AE && "unexpected usual deallocation function parameter"); 13895b34958bSRichard Smith return Params; 1390b2f0f057SRichard Smith } 1391b2f0f057SRichard Smith 1392b2f0f057SRichard Smith namespace { 1393b2f0f057SRichard Smith /// A cleanup to call the given 'operator delete' function upon abnormal 1394b2f0f057SRichard Smith /// exit from a new expression. Templated on a traits type that deals with 1395b2f0f057SRichard Smith /// ensuring that the arguments dominate the cleanup if necessary. 1396b2f0f057SRichard Smith template<typename Traits> 1397b2f0f057SRichard Smith class CallDeleteDuringNew final : public EHScopeStack::Cleanup { 1398b2f0f057SRichard Smith /// Type used to hold llvm::Value*s. 1399b2f0f057SRichard Smith typedef typename Traits::ValueTy ValueTy; 1400b2f0f057SRichard Smith /// Type used to hold RValues. 1401b2f0f057SRichard Smith typedef typename Traits::RValueTy RValueTy; 1402b2f0f057SRichard Smith struct PlacementArg { 1403b2f0f057SRichard Smith RValueTy ArgValue; 1404b2f0f057SRichard Smith QualType ArgType; 1405b2f0f057SRichard Smith }; 1406b2f0f057SRichard Smith 1407b2f0f057SRichard Smith unsigned NumPlacementArgs : 31; 1408b2f0f057SRichard Smith unsigned PassAlignmentToPlacementDelete : 1; 1409b2f0f057SRichard Smith const FunctionDecl *OperatorDelete; 1410b2f0f057SRichard Smith ValueTy Ptr; 1411b2f0f057SRichard Smith ValueTy AllocSize; 1412b2f0f057SRichard Smith CharUnits AllocAlign; 1413b2f0f057SRichard Smith 1414b2f0f057SRichard Smith PlacementArg *getPlacementArgs() { 1415b2f0f057SRichard Smith return reinterpret_cast<PlacementArg *>(this + 1); 1416b2f0f057SRichard Smith } 1417e9abe648SDaniel Jasper 1418e9abe648SDaniel Jasper public: 1419e9abe648SDaniel Jasper static size_t getExtraSize(size_t NumPlacementArgs) { 1420b2f0f057SRichard Smith return NumPlacementArgs * sizeof(PlacementArg); 1421e9abe648SDaniel Jasper } 1422e9abe648SDaniel Jasper 1423e9abe648SDaniel Jasper CallDeleteDuringNew(size_t NumPlacementArgs, 1424b2f0f057SRichard Smith const FunctionDecl *OperatorDelete, ValueTy Ptr, 1425b2f0f057SRichard Smith ValueTy AllocSize, bool PassAlignmentToPlacementDelete, 1426b2f0f057SRichard Smith CharUnits AllocAlign) 1427b2f0f057SRichard Smith : NumPlacementArgs(NumPlacementArgs), 1428b2f0f057SRichard Smith PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete), 1429b2f0f057SRichard Smith OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize), 1430b2f0f057SRichard Smith AllocAlign(AllocAlign) {} 1431e9abe648SDaniel Jasper 1432b2f0f057SRichard Smith void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) { 1433e9abe648SDaniel Jasper assert(I < NumPlacementArgs && "index out of range"); 1434b2f0f057SRichard Smith getPlacementArgs()[I] = {Arg, Type}; 1435e9abe648SDaniel Jasper } 1436e9abe648SDaniel Jasper 1437e9abe648SDaniel Jasper void Emit(CodeGenFunction &CGF, Flags flags) override { 143816c53ffcSSimon Pilgrim const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>(); 1439e9abe648SDaniel Jasper CallArgList DeleteArgs; 1440824c2f53SJohn McCall 14415b34958bSRichard Smith // The first argument is always a void* (or C* for a destroying operator 14425b34958bSRichard Smith // delete for class type C). 1443b2f0f057SRichard Smith DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0)); 1444189e52fcSRichard Smith 1445b2f0f057SRichard Smith // Figure out what other parameters we should be implicitly passing. 14465b34958bSRichard Smith UsualDeleteParams Params; 1447b2f0f057SRichard Smith if (NumPlacementArgs) { 1448b2f0f057SRichard Smith // A placement deallocation function is implicitly passed an alignment 1449b2f0f057SRichard Smith // if the placement allocation function was, but is never passed a size. 14505b34958bSRichard Smith Params.Alignment = PassAlignmentToPlacementDelete; 1451b2f0f057SRichard Smith } else { 1452b2f0f057SRichard Smith // For a non-placement new-expression, 'operator delete' can take a 1453b2f0f057SRichard Smith // size and/or an alignment if it has the right parameters. 14545b34958bSRichard Smith Params = getUsualDeleteParams(OperatorDelete); 1455189e52fcSRichard Smith } 1456824c2f53SJohn McCall 14575b34958bSRichard Smith assert(!Params.DestroyingDelete && 14585b34958bSRichard Smith "should not call destroying delete in a new-expression"); 14595b34958bSRichard Smith 1460b2f0f057SRichard Smith // The second argument can be a std::size_t (for non-placement delete). 14615b34958bSRichard Smith if (Params.Size) 1462b2f0f057SRichard Smith DeleteArgs.add(Traits::get(CGF, AllocSize), 1463b2f0f057SRichard Smith CGF.getContext().getSizeType()); 1464824c2f53SJohn McCall 1465b2f0f057SRichard Smith // The next (second or third) argument can be a std::align_val_t, which 1466b2f0f057SRichard Smith // is an enum whose underlying type is std::size_t. 1467b2f0f057SRichard Smith // FIXME: Use the right type as the parameter type. Note that in a call 1468b2f0f057SRichard Smith // to operator delete(size_t, ...), we may not have it available. 14695b34958bSRichard Smith if (Params.Alignment) 1470b2f0f057SRichard Smith DeleteArgs.add(RValue::get(llvm::ConstantInt::get( 1471b2f0f057SRichard Smith CGF.SizeTy, AllocAlign.getQuantity())), 1472b2f0f057SRichard Smith CGF.getContext().getSizeType()); 14737f9c92a9SJohn McCall 14747f9c92a9SJohn McCall // Pass the rest of the arguments, which must match exactly. 14757f9c92a9SJohn McCall for (unsigned I = 0; I != NumPlacementArgs; ++I) { 1476b2f0f057SRichard Smith auto Arg = getPlacementArgs()[I]; 1477b2f0f057SRichard Smith DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType); 14787f9c92a9SJohn McCall } 14797f9c92a9SJohn McCall 14807f9c92a9SJohn McCall // Call 'operator delete'. 14818d0dc31dSRichard Smith EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs); 14827f9c92a9SJohn McCall } 14837f9c92a9SJohn McCall }; 1484ab9db510SAlexander Kornienko } 14857f9c92a9SJohn McCall 14867f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a 14877f9c92a9SJohn McCall /// new-expression throws. 14887f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF, 14897f9c92a9SJohn McCall const CXXNewExpr *E, 14907f416cc4SJohn McCall Address NewPtr, 14917f9c92a9SJohn McCall llvm::Value *AllocSize, 1492b2f0f057SRichard Smith CharUnits AllocAlign, 14937f9c92a9SJohn McCall const CallArgList &NewArgs) { 1494b2f0f057SRichard Smith unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1; 1495b2f0f057SRichard Smith 14967f9c92a9SJohn McCall // If we're not inside a conditional branch, then the cleanup will 14977f9c92a9SJohn McCall // dominate and we can do the easier (and more efficient) thing. 14987f9c92a9SJohn McCall if (!CGF.isInConditionalBranch()) { 1499b2f0f057SRichard Smith struct DirectCleanupTraits { 1500b2f0f057SRichard Smith typedef llvm::Value *ValueTy; 1501b2f0f057SRichard Smith typedef RValue RValueTy; 1502b2f0f057SRichard Smith static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); } 1503b2f0f057SRichard Smith static RValue get(CodeGenFunction &, RValueTy V) { return V; } 1504b2f0f057SRichard Smith }; 1505b2f0f057SRichard Smith 1506b2f0f057SRichard Smith typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup; 1507b2f0f057SRichard Smith 1508b2f0f057SRichard Smith DirectCleanup *Cleanup = CGF.EHStack 1509b2f0f057SRichard Smith .pushCleanupWithExtra<DirectCleanup>(EHCleanup, 15107f9c92a9SJohn McCall E->getNumPlacementArgs(), 15117f9c92a9SJohn McCall E->getOperatorDelete(), 15127f416cc4SJohn McCall NewPtr.getPointer(), 1513b2f0f057SRichard Smith AllocSize, 1514b2f0f057SRichard Smith E->passAlignment(), 1515b2f0f057SRichard Smith AllocAlign); 1516b2f0f057SRichard Smith for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1517b2f0f057SRichard Smith auto &Arg = NewArgs[I + NumNonPlacementArgs]; 15185b330e8dSYaxun Liu Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty); 1519b2f0f057SRichard Smith } 15207f9c92a9SJohn McCall 15217f9c92a9SJohn McCall return; 15227f9c92a9SJohn McCall } 15237f9c92a9SJohn McCall 15247f9c92a9SJohn McCall // Otherwise, we need to save all this stuff. 1525cb5f77f0SJohn McCall DominatingValue<RValue>::saved_type SavedNewPtr = 15267f416cc4SJohn McCall DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer())); 1527cb5f77f0SJohn McCall DominatingValue<RValue>::saved_type SavedAllocSize = 1528cb5f77f0SJohn McCall DominatingValue<RValue>::save(CGF, RValue::get(AllocSize)); 15297f9c92a9SJohn McCall 1530b2f0f057SRichard Smith struct ConditionalCleanupTraits { 1531b2f0f057SRichard Smith typedef DominatingValue<RValue>::saved_type ValueTy; 1532b2f0f057SRichard Smith typedef DominatingValue<RValue>::saved_type RValueTy; 1533b2f0f057SRichard Smith static RValue get(CodeGenFunction &CGF, ValueTy V) { 1534b2f0f057SRichard Smith return V.restore(CGF); 1535b2f0f057SRichard Smith } 1536b2f0f057SRichard Smith }; 1537b2f0f057SRichard Smith typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup; 1538b2f0f057SRichard Smith 1539b2f0f057SRichard Smith ConditionalCleanup *Cleanup = CGF.EHStack 1540b2f0f057SRichard Smith .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup, 15417f9c92a9SJohn McCall E->getNumPlacementArgs(), 15427f9c92a9SJohn McCall E->getOperatorDelete(), 15437f9c92a9SJohn McCall SavedNewPtr, 1544b2f0f057SRichard Smith SavedAllocSize, 1545b2f0f057SRichard Smith E->passAlignment(), 1546b2f0f057SRichard Smith AllocAlign); 1547b2f0f057SRichard Smith for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1548b2f0f057SRichard Smith auto &Arg = NewArgs[I + NumNonPlacementArgs]; 15495b330e8dSYaxun Liu Cleanup->setPlacementArg( 15505b330e8dSYaxun Liu I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty); 1551b2f0f057SRichard Smith } 15527f9c92a9SJohn McCall 1553f4beacd0SJohn McCall CGF.initFullExprCleanup(); 1554824c2f53SJohn McCall } 1555824c2f53SJohn McCall 155659486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { 155775f9498aSJohn McCall // The element type being allocated. 155875f9498aSJohn McCall QualType allocType = getContext().getBaseElementType(E->getAllocatedType()); 15598ed55a54SJohn McCall 156075f9498aSJohn McCall // 1. Build a call to the allocation function. 156175f9498aSJohn McCall FunctionDecl *allocator = E->getOperatorNew(); 156259486a2dSAnders Carlsson 1563f862eb6aSSebastian Redl // If there is a brace-initializer, cannot allocate fewer elements than inits. 1564f862eb6aSSebastian Redl unsigned minElements = 0; 1565f862eb6aSSebastian Redl if (E->isArray() && E->hasInitializer()) { 15660511d23aSRichard Smith const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()); 15670511d23aSRichard Smith if (ILE && ILE->isStringLiteralInit()) 15680511d23aSRichard Smith minElements = 15690511d23aSRichard Smith cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 15700511d23aSRichard Smith ->getSize().getZExtValue(); 15710511d23aSRichard Smith else if (ILE) 1572f862eb6aSSebastian Redl minElements = ILE->getNumInits(); 1573f862eb6aSSebastian Redl } 1574f862eb6aSSebastian Redl 15758a13c418SCraig Topper llvm::Value *numElements = nullptr; 15768a13c418SCraig Topper llvm::Value *allocSizeWithoutCookie = nullptr; 157775f9498aSJohn McCall llvm::Value *allocSize = 1578f862eb6aSSebastian Redl EmitCXXNewAllocSize(*this, E, minElements, numElements, 1579f862eb6aSSebastian Redl allocSizeWithoutCookie); 15803a7487f9SXiangling Liao CharUnits allocAlign = getContext().getPreferredTypeAlignInChars(allocType); 158159486a2dSAnders Carlsson 15827f416cc4SJohn McCall // Emit the allocation call. If the allocator is a global placement 15837f416cc4SJohn McCall // operator, just "inline" it directly. 15847f416cc4SJohn McCall Address allocation = Address::invalid(); 15857f416cc4SJohn McCall CallArgList allocatorArgs; 15867f416cc4SJohn McCall if (allocator->isReservedGlobalPlacementOperator()) { 158753dcf94dSJohn McCall assert(E->getNumPlacementArgs() == 1); 158853dcf94dSJohn McCall const Expr *arg = *E->placement_arguments().begin(); 158953dcf94dSJohn McCall 15908f248234SKrzysztof Parzyszek LValueBaseInfo BaseInfo; 15918f248234SKrzysztof Parzyszek allocation = EmitPointerWithAlignment(arg, &BaseInfo); 15927f416cc4SJohn McCall 15937f416cc4SJohn McCall // The pointer expression will, in many cases, be an opaque void*. 15947f416cc4SJohn McCall // In these cases, discard the computed alignment and use the 15957f416cc4SJohn McCall // formal alignment of the allocated type. 15968f248234SKrzysztof Parzyszek if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl) 1597*e751d978SNikita Popov allocation = allocation.withAlignment(allocAlign); 15987f416cc4SJohn McCall 159953dcf94dSJohn McCall // Set up allocatorArgs for the call to operator delete if it's not 160053dcf94dSJohn McCall // the reserved global operator. 160153dcf94dSJohn McCall if (E->getOperatorDelete() && 160253dcf94dSJohn McCall !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 160353dcf94dSJohn McCall allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType()); 160453dcf94dSJohn McCall allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType()); 160553dcf94dSJohn McCall } 160653dcf94dSJohn McCall 16077f416cc4SJohn McCall } else { 16087f416cc4SJohn McCall const FunctionProtoType *allocatorType = 16097f416cc4SJohn McCall allocator->getType()->castAs<FunctionProtoType>(); 1610b2f0f057SRichard Smith unsigned ParamsToSkip = 0; 16117f416cc4SJohn McCall 16127f416cc4SJohn McCall // The allocation size is the first argument. 16137f416cc4SJohn McCall QualType sizeType = getContext().getSizeType(); 161443dca6a8SEli Friedman allocatorArgs.add(RValue::get(allocSize), sizeType); 1615b2f0f057SRichard Smith ++ParamsToSkip; 161659486a2dSAnders Carlsson 1617b2f0f057SRichard Smith if (allocSize != allocSizeWithoutCookie) { 1618b2f0f057SRichard Smith CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI. 1619b2f0f057SRichard Smith allocAlign = std::max(allocAlign, cookieAlign); 1620b2f0f057SRichard Smith } 1621b2f0f057SRichard Smith 1622b2f0f057SRichard Smith // The allocation alignment may be passed as the second argument. 1623b2f0f057SRichard Smith if (E->passAlignment()) { 1624b2f0f057SRichard Smith QualType AlignValT = sizeType; 1625b2f0f057SRichard Smith if (allocatorType->getNumParams() > 1) { 1626b2f0f057SRichard Smith AlignValT = allocatorType->getParamType(1); 1627b2f0f057SRichard Smith assert(getContext().hasSameUnqualifiedType( 1628b2f0f057SRichard Smith AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(), 1629b2f0f057SRichard Smith sizeType) && 1630b2f0f057SRichard Smith "wrong type for alignment parameter"); 1631b2f0f057SRichard Smith ++ParamsToSkip; 1632b2f0f057SRichard Smith } else { 1633b2f0f057SRichard Smith // Corner case, passing alignment to 'operator new(size_t, ...)'. 1634b2f0f057SRichard Smith assert(allocator->isVariadic() && "can't pass alignment to allocator"); 1635b2f0f057SRichard Smith } 1636b2f0f057SRichard Smith allocatorArgs.add( 1637b2f0f057SRichard Smith RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())), 1638b2f0f057SRichard Smith AlignValT); 1639b2f0f057SRichard Smith } 1640b2f0f057SRichard Smith 1641b2f0f057SRichard Smith // FIXME: Why do we not pass a CalleeDecl here? 1642f05779e2SDavid Blaikie EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(), 1643ed00ea08SVedant Kumar /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip); 164459486a2dSAnders Carlsson 16457f416cc4SJohn McCall RValue RV = 16467f416cc4SJohn McCall EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs); 16477f416cc4SJohn McCall 1648ce7d3e1cSArthur Eubanks // Set !heapallocsite metadata on the call to operator new. 1649bc387938SArthur Eubanks if (getDebugInfo()) 1650ce7d3e1cSArthur Eubanks if (auto *newCall = dyn_cast<llvm::CallBase>(RV.getScalarVal())) 1651ce7d3e1cSArthur Eubanks getDebugInfo()->addHeapAllocSiteMetadata(newCall, allocType, 1652ce7d3e1cSArthur Eubanks E->getExprLoc()); 1653ce7d3e1cSArthur Eubanks 1654b2f0f057SRichard Smith // If this was a call to a global replaceable allocation function that does 1655b2f0f057SRichard Smith // not take an alignment argument, the allocator is known to produce 1656b2f0f057SRichard Smith // storage that's suitably aligned for any object that fits, up to a known 1657b2f0f057SRichard Smith // threshold. Otherwise assume it's suitably aligned for the allocated type. 1658b2f0f057SRichard Smith CharUnits allocationAlign = allocAlign; 1659b2f0f057SRichard Smith if (!E->passAlignment() && 1660b2f0f057SRichard Smith allocator->isReplaceableGlobalAllocationFunction()) { 1661b2f0f057SRichard Smith unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>( 1662b2f0f057SRichard Smith Target.getNewAlign(), getContext().getTypeSize(allocType))); 1663b2f0f057SRichard Smith allocationAlign = std::max( 1664b2f0f057SRichard Smith allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign)); 16657f416cc4SJohn McCall } 16667f416cc4SJohn McCall 1667*e751d978SNikita Popov allocation = Address(RV.getScalarVal(), Int8Ty, allocationAlign); 16687ec4b434SJohn McCall } 166959486a2dSAnders Carlsson 167075f9498aSJohn McCall // Emit a null check on the allocation result if the allocation 167175f9498aSJohn McCall // function is allowed to return null (because it has a non-throwing 1672902a0238SRichard Smith // exception spec or is the reserved placement new) and we have an 16732f72a752SRichard Smith // interesting initializer will be running sanitizers on the initialization. 16749b6dfac5SBruno Ricci bool nullCheck = E->shouldNullCheckAllocation() && 16752f72a752SRichard Smith (!allocType.isPODType(getContext()) || E->hasInitializer() || 16762f72a752SRichard Smith sanitizePerformTypeCheck()); 167759486a2dSAnders Carlsson 16788a13c418SCraig Topper llvm::BasicBlock *nullCheckBB = nullptr; 16798a13c418SCraig Topper llvm::BasicBlock *contBB = nullptr; 168059486a2dSAnders Carlsson 1681f7dcf320SJohn McCall // The null-check means that the initializer is conditionally 1682f7dcf320SJohn McCall // evaluated. 1683f7dcf320SJohn McCall ConditionalEvaluation conditional(*this); 1684f7dcf320SJohn McCall 168575f9498aSJohn McCall if (nullCheck) { 1686f7dcf320SJohn McCall conditional.begin(*this); 168775f9498aSJohn McCall 168875f9498aSJohn McCall nullCheckBB = Builder.GetInsertBlock(); 168975f9498aSJohn McCall llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull"); 169075f9498aSJohn McCall contBB = createBasicBlock("new.cont"); 169175f9498aSJohn McCall 16927f416cc4SJohn McCall llvm::Value *isNull = 16937f416cc4SJohn McCall Builder.CreateIsNull(allocation.getPointer(), "new.isnull"); 169475f9498aSJohn McCall Builder.CreateCondBr(isNull, contBB, notNullBB); 169575f9498aSJohn McCall EmitBlock(notNullBB); 169659486a2dSAnders Carlsson } 169759486a2dSAnders Carlsson 1698824c2f53SJohn McCall // If there's an operator delete, enter a cleanup to call it if an 1699824c2f53SJohn McCall // exception is thrown. 170075f9498aSJohn McCall EHScopeStack::stable_iterator operatorDeleteCleanup; 17018a13c418SCraig Topper llvm::Instruction *cleanupDominator = nullptr; 17027ec4b434SJohn McCall if (E->getOperatorDelete() && 17037ec4b434SJohn McCall !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 1704b2f0f057SRichard Smith EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign, 1705b2f0f057SRichard Smith allocatorArgs); 170675f9498aSJohn McCall operatorDeleteCleanup = EHStack.stable_begin(); 1707f4beacd0SJohn McCall cleanupDominator = Builder.CreateUnreachable(); 1708824c2f53SJohn McCall } 1709824c2f53SJohn McCall 1710cf9b1f65SEli Friedman assert((allocSize == allocSizeWithoutCookie) == 1711cf9b1f65SEli Friedman CalculateCookiePadding(*this, E).isZero()); 1712cf9b1f65SEli Friedman if (allocSize != allocSizeWithoutCookie) { 1713cf9b1f65SEli Friedman assert(E->isArray()); 1714cf9b1f65SEli Friedman allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation, 1715cf9b1f65SEli Friedman numElements, 1716cf9b1f65SEli Friedman E, allocType); 1717cf9b1f65SEli Friedman } 1718cf9b1f65SEli Friedman 1719fb901c7aSDavid Blaikie llvm::Type *elementTy = ConvertTypeForMem(allocType); 17207f416cc4SJohn McCall Address result = Builder.CreateElementBitCast(allocation, elementTy); 1721824c2f53SJohn McCall 17225dde8094SPiotr Padlewski // Passing pointer through launder.invariant.group to avoid propagation of 1723338c9d0aSPiotr Padlewski // vptrs information which may be included in previous type. 172431fd99cfSPiotr Padlewski // To not break LTO with different optimizations levels, we do it regardless 172531fd99cfSPiotr Padlewski // of optimization level. 1726338c9d0aSPiotr Padlewski if (CGM.getCodeGenOpts().StrictVTablePointers && 1727338c9d0aSPiotr Padlewski allocator->isReservedGlobalPlacementOperator()) 1728*e751d978SNikita Popov result = result.withPointer( 1729*e751d978SNikita Popov Builder.CreateLaunderInvariantGroup(result.getPointer())); 1730338c9d0aSPiotr Padlewski 173137605182SSerge Pavlov // Emit sanitizer checks for pointer value now, so that in the case of an 1732cfa79b27SRichard Smith // array it was checked only once and not at each constructor call. We may 1733cfa79b27SRichard Smith // have already checked that the pointer is non-null. 1734cfa79b27SRichard Smith // FIXME: If we have an array cookie and a potentially-throwing allocator, 1735cfa79b27SRichard Smith // we'll null check the wrong pointer here. 1736cfa79b27SRichard Smith SanitizerSet SkippedChecks; 1737cfa79b27SRichard Smith SkippedChecks.set(SanitizerKind::Null, nullCheck); 173837605182SSerge Pavlov EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, 173937605182SSerge Pavlov E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(), 1740cfa79b27SRichard Smith result.getPointer(), allocType, result.getAlignment(), 1741cfa79b27SRichard Smith SkippedChecks, numElements); 174237605182SSerge Pavlov 1743fb901c7aSDavid Blaikie EmitNewInitializer(*this, E, allocType, elementTy, result, numElements, 174499210dc9SJohn McCall allocSizeWithoutCookie); 17458ed55a54SJohn McCall if (E->isArray()) { 17468ed55a54SJohn McCall // NewPtr is a pointer to the base element type. If we're 17478ed55a54SJohn McCall // allocating an array of arrays, we'll need to cast back to the 17488ed55a54SJohn McCall // array pointer type. 17492192fe50SChris Lattner llvm::Type *resultType = ConvertTypeForMem(E->getType()); 17507f416cc4SJohn McCall if (result.getType() != resultType) 175175f9498aSJohn McCall result = Builder.CreateBitCast(result, resultType); 175247b4629bSFariborz Jahanian } 175359486a2dSAnders Carlsson 1754824c2f53SJohn McCall // Deactivate the 'operator delete' cleanup if we finished 1755824c2f53SJohn McCall // initialization. 1756f4beacd0SJohn McCall if (operatorDeleteCleanup.isValid()) { 1757f4beacd0SJohn McCall DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator); 1758f4beacd0SJohn McCall cleanupDominator->eraseFromParent(); 1759f4beacd0SJohn McCall } 1760824c2f53SJohn McCall 17617f416cc4SJohn McCall llvm::Value *resultPtr = result.getPointer(); 176275f9498aSJohn McCall if (nullCheck) { 1763f7dcf320SJohn McCall conditional.end(*this); 1764f7dcf320SJohn McCall 176575f9498aSJohn McCall llvm::BasicBlock *notNullBB = Builder.GetInsertBlock(); 176675f9498aSJohn McCall EmitBlock(contBB); 176759486a2dSAnders Carlsson 17687f416cc4SJohn McCall llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2); 17697f416cc4SJohn McCall PHI->addIncoming(resultPtr, notNullBB); 17707f416cc4SJohn McCall PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()), 177175f9498aSJohn McCall nullCheckBB); 177259486a2dSAnders Carlsson 17737f416cc4SJohn McCall resultPtr = PHI; 177459486a2dSAnders Carlsson } 177559486a2dSAnders Carlsson 17767f416cc4SJohn McCall return resultPtr; 177759486a2dSAnders Carlsson } 177859486a2dSAnders Carlsson 177959486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD, 1780b2f0f057SRichard Smith llvm::Value *Ptr, QualType DeleteTy, 1781b2f0f057SRichard Smith llvm::Value *NumElements, 1782b2f0f057SRichard Smith CharUnits CookieSize) { 1783b2f0f057SRichard Smith assert((!NumElements && CookieSize.isZero()) || 1784b2f0f057SRichard Smith DeleteFD->getOverloadedOperator() == OO_Array_Delete); 17858ed55a54SJohn McCall 178616c53ffcSSimon Pilgrim const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>(); 178759486a2dSAnders Carlsson CallArgList DeleteArgs; 178859486a2dSAnders Carlsson 17895b34958bSRichard Smith auto Params = getUsualDeleteParams(DeleteFD); 1790b2f0f057SRichard Smith auto ParamTypeIt = DeleteFTy->param_type_begin(); 1791b2f0f057SRichard Smith 1792b2f0f057SRichard Smith // Pass the pointer itself. 1793b2f0f057SRichard Smith QualType ArgTy = *ParamTypeIt++; 179459486a2dSAnders Carlsson llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy)); 179543dca6a8SEli Friedman DeleteArgs.add(RValue::get(DeletePtr), ArgTy); 179659486a2dSAnders Carlsson 17975b34958bSRichard Smith // Pass the std::destroying_delete tag if present. 17981e7f026cSRichard Smith llvm::AllocaInst *DestroyingDeleteTag = nullptr; 17995b34958bSRichard Smith if (Params.DestroyingDelete) { 18005b34958bSRichard Smith QualType DDTag = *ParamTypeIt++; 18011e7f026cSRichard Smith llvm::Type *Ty = getTypes().ConvertType(DDTag); 18021e7f026cSRichard Smith CharUnits Align = CGM.getNaturalTypeAlignment(DDTag); 18031e7f026cSRichard Smith DestroyingDeleteTag = CreateTempAlloca(Ty, "destroying.delete.tag"); 18041e7f026cSRichard Smith DestroyingDeleteTag->setAlignment(Align.getAsAlign()); 18051e7f026cSRichard Smith DeleteArgs.add(RValue::getAggregate(Address(DestroyingDeleteTag, Align)), DDTag); 18065b34958bSRichard Smith } 18075b34958bSRichard Smith 1808b2f0f057SRichard Smith // Pass the size if the delete function has a size_t parameter. 18095b34958bSRichard Smith if (Params.Size) { 1810b2f0f057SRichard Smith QualType SizeType = *ParamTypeIt++; 1811b2f0f057SRichard Smith CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy); 1812b2f0f057SRichard Smith llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType), 1813b2f0f057SRichard Smith DeleteTypeSize.getQuantity()); 1814b2f0f057SRichard Smith 1815b2f0f057SRichard Smith // For array new, multiply by the number of elements. 1816b2f0f057SRichard Smith if (NumElements) 1817b2f0f057SRichard Smith Size = Builder.CreateMul(Size, NumElements); 1818b2f0f057SRichard Smith 1819b2f0f057SRichard Smith // If there is a cookie, add the cookie size. 1820b2f0f057SRichard Smith if (!CookieSize.isZero()) 1821b2f0f057SRichard Smith Size = Builder.CreateAdd( 1822b2f0f057SRichard Smith Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity())); 1823b2f0f057SRichard Smith 1824b2f0f057SRichard Smith DeleteArgs.add(RValue::get(Size), SizeType); 1825b2f0f057SRichard Smith } 1826b2f0f057SRichard Smith 1827b2f0f057SRichard Smith // Pass the alignment if the delete function has an align_val_t parameter. 18285b34958bSRichard Smith if (Params.Alignment) { 1829b2f0f057SRichard Smith QualType AlignValType = *ParamTypeIt++; 18303a7487f9SXiangling Liao CharUnits DeleteTypeAlign = 18313a7487f9SXiangling Liao getContext().toCharUnitsFromBits(getContext().getTypeAlignIfKnown( 18323a7487f9SXiangling Liao DeleteTy, true /* NeedsPreferredAlignment */)); 1833b2f0f057SRichard Smith llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType), 1834b2f0f057SRichard Smith DeleteTypeAlign.getQuantity()); 1835b2f0f057SRichard Smith DeleteArgs.add(RValue::get(Align), AlignValType); 1836b2f0f057SRichard Smith } 1837b2f0f057SRichard Smith 1838b2f0f057SRichard Smith assert(ParamTypeIt == DeleteFTy->param_type_end() && 1839b2f0f057SRichard Smith "unknown parameter to usual delete function"); 184059486a2dSAnders Carlsson 184159486a2dSAnders Carlsson // Emit the call to delete. 18428d0dc31dSRichard Smith EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs); 18431e7f026cSRichard Smith 18441e7f026cSRichard Smith // If call argument lowering didn't use the destroying_delete_t alloca, 18451e7f026cSRichard Smith // remove it again. 18461e7f026cSRichard Smith if (DestroyingDeleteTag && DestroyingDeleteTag->use_empty()) 18471e7f026cSRichard Smith DestroyingDeleteTag->eraseFromParent(); 184859486a2dSAnders Carlsson } 184959486a2dSAnders Carlsson 18508ed55a54SJohn McCall namespace { 18518ed55a54SJohn McCall /// Calls the given 'operator delete' on a single object. 18527e70d680SDavid Blaikie struct CallObjectDelete final : EHScopeStack::Cleanup { 18538ed55a54SJohn McCall llvm::Value *Ptr; 18548ed55a54SJohn McCall const FunctionDecl *OperatorDelete; 18558ed55a54SJohn McCall QualType ElementType; 18568ed55a54SJohn McCall 18578ed55a54SJohn McCall CallObjectDelete(llvm::Value *Ptr, 18588ed55a54SJohn McCall const FunctionDecl *OperatorDelete, 18598ed55a54SJohn McCall QualType ElementType) 18608ed55a54SJohn McCall : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {} 18618ed55a54SJohn McCall 18624f12f10dSCraig Topper void Emit(CodeGenFunction &CGF, Flags flags) override { 18638ed55a54SJohn McCall CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType); 18648ed55a54SJohn McCall } 18658ed55a54SJohn McCall }; 1866ab9db510SAlexander Kornienko } 18678ed55a54SJohn McCall 18680c0b6d9aSDavid Majnemer void 18690c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 18700c0b6d9aSDavid Majnemer llvm::Value *CompletePtr, 18710c0b6d9aSDavid Majnemer QualType ElementType) { 18720c0b6d9aSDavid Majnemer EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr, 18730c0b6d9aSDavid Majnemer OperatorDelete, ElementType); 18740c0b6d9aSDavid Majnemer } 18750c0b6d9aSDavid Majnemer 18765b34958bSRichard Smith /// Emit the code for deleting a single object with a destroying operator 18775b34958bSRichard Smith /// delete. If the element type has a non-virtual destructor, Ptr has already 18785b34958bSRichard Smith /// been converted to the type of the parameter of 'operator delete'. Otherwise 18795b34958bSRichard Smith /// Ptr points to an object of the static type. 18805b34958bSRichard Smith static void EmitDestroyingObjectDelete(CodeGenFunction &CGF, 18815b34958bSRichard Smith const CXXDeleteExpr *DE, Address Ptr, 18825b34958bSRichard Smith QualType ElementType) { 18835b34958bSRichard Smith auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor(); 18845b34958bSRichard Smith if (Dtor && Dtor->isVirtual()) 18855b34958bSRichard Smith CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType, 18865b34958bSRichard Smith Dtor); 18875b34958bSRichard Smith else 18885b34958bSRichard Smith CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType); 18895b34958bSRichard Smith } 18905b34958bSRichard Smith 18918ed55a54SJohn McCall /// Emit the code for deleting a single object. 1892f39e12a0SRichard Smith /// \return \c true if we started emitting UnconditionalDeleteBlock, \c false 1893f39e12a0SRichard Smith /// if not. 1894f39e12a0SRichard Smith static bool EmitObjectDelete(CodeGenFunction &CGF, 18950868137aSDavid Majnemer const CXXDeleteExpr *DE, 18967f416cc4SJohn McCall Address Ptr, 1897f39e12a0SRichard Smith QualType ElementType, 1898f39e12a0SRichard Smith llvm::BasicBlock *UnconditionalDeleteBlock) { 1899d98f5d78SIvan Krasin // C++11 [expr.delete]p3: 1900d98f5d78SIvan Krasin // If the static type of the object to be deleted is different from its 1901d98f5d78SIvan Krasin // dynamic type, the static type shall be a base class of the dynamic type 1902d98f5d78SIvan Krasin // of the object to be deleted and the static type shall have a virtual 1903d98f5d78SIvan Krasin // destructor or the behavior is undefined. 1904d98f5d78SIvan Krasin CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall, 1905d98f5d78SIvan Krasin DE->getExprLoc(), Ptr.getPointer(), 1906d98f5d78SIvan Krasin ElementType); 1907d98f5d78SIvan Krasin 19085b34958bSRichard Smith const FunctionDecl *OperatorDelete = DE->getOperatorDelete(); 19095b34958bSRichard Smith assert(!OperatorDelete->isDestroyingOperatorDelete()); 19105b34958bSRichard Smith 19118ed55a54SJohn McCall // Find the destructor for the type, if applicable. If the 19128ed55a54SJohn McCall // destructor is virtual, we'll just emit the vcall and return. 19138a13c418SCraig Topper const CXXDestructorDecl *Dtor = nullptr; 19148ed55a54SJohn McCall if (const RecordType *RT = ElementType->getAs<RecordType>()) { 19158ed55a54SJohn McCall CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1916b23533dbSEli Friedman if (RD->hasDefinition() && !RD->hasTrivialDestructor()) { 19178ed55a54SJohn McCall Dtor = RD->getDestructor(); 19188ed55a54SJohn McCall 19198ed55a54SJohn McCall if (Dtor->isVirtual()) { 1920cb30590dSHiroshi Yamauchi bool UseVirtualCall = true; 1921cb30590dSHiroshi Yamauchi const Expr *Base = DE->getArgument(); 1922cb30590dSHiroshi Yamauchi if (auto *DevirtualizedDtor = 1923cb30590dSHiroshi Yamauchi dyn_cast_or_null<const CXXDestructorDecl>( 1924cb30590dSHiroshi Yamauchi Dtor->getDevirtualizedMethod( 1925cb30590dSHiroshi Yamauchi Base, CGF.CGM.getLangOpts().AppleKext))) { 1926cb30590dSHiroshi Yamauchi UseVirtualCall = false; 1927cb30590dSHiroshi Yamauchi const CXXRecordDecl *DevirtualizedClass = 1928cb30590dSHiroshi Yamauchi DevirtualizedDtor->getParent(); 1929cb30590dSHiroshi Yamauchi if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) { 1930cb30590dSHiroshi Yamauchi // Devirtualized to the class of the base type (the type of the 1931cb30590dSHiroshi Yamauchi // whole expression). 1932cb30590dSHiroshi Yamauchi Dtor = DevirtualizedDtor; 1933cb30590dSHiroshi Yamauchi } else { 1934cb30590dSHiroshi Yamauchi // Devirtualized to some other type. Would need to cast the this 1935cb30590dSHiroshi Yamauchi // pointer to that type but we don't have support for that yet, so 1936cb30590dSHiroshi Yamauchi // do a virtual call. FIXME: handle the case where it is 1937cb30590dSHiroshi Yamauchi // devirtualized to the derived type (the type of the inner 1938cb30590dSHiroshi Yamauchi // expression) as in EmitCXXMemberOrOperatorMemberCallExpr. 1939cb30590dSHiroshi Yamauchi UseVirtualCall = true; 1940cb30590dSHiroshi Yamauchi } 1941cb30590dSHiroshi Yamauchi } 1942cb30590dSHiroshi Yamauchi if (UseVirtualCall) { 19430868137aSDavid Majnemer CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType, 19440868137aSDavid Majnemer Dtor); 1945f39e12a0SRichard Smith return false; 19468ed55a54SJohn McCall } 19478ed55a54SJohn McCall } 19488ed55a54SJohn McCall } 1949cb30590dSHiroshi Yamauchi } 19508ed55a54SJohn McCall 19518ed55a54SJohn McCall // Make sure that we call delete even if the dtor throws. 1952e4df6c8dSJohn McCall // This doesn't have to a conditional cleanup because we're going 1953e4df6c8dSJohn McCall // to pop it off in a second. 19548ed55a54SJohn McCall CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, 19557f416cc4SJohn McCall Ptr.getPointer(), 19567f416cc4SJohn McCall OperatorDelete, ElementType); 19578ed55a54SJohn McCall 19588ed55a54SJohn McCall if (Dtor) 19598ed55a54SJohn McCall CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 196061535005SDouglas Gregor /*ForVirtualBase=*/false, 196161535005SDouglas Gregor /*Delegating=*/false, 196288559637SMarco Antognini Ptr, ElementType); 1963460ce58fSJohn McCall else if (auto Lifetime = ElementType.getObjCLifetime()) { 1964460ce58fSJohn McCall switch (Lifetime) { 196531168b07SJohn McCall case Qualifiers::OCL_None: 196631168b07SJohn McCall case Qualifiers::OCL_ExplicitNone: 196731168b07SJohn McCall case Qualifiers::OCL_Autoreleasing: 196831168b07SJohn McCall break; 196931168b07SJohn McCall 19707f416cc4SJohn McCall case Qualifiers::OCL_Strong: 19717f416cc4SJohn McCall CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime); 197231168b07SJohn McCall break; 197331168b07SJohn McCall 197431168b07SJohn McCall case Qualifiers::OCL_Weak: 197531168b07SJohn McCall CGF.EmitARCDestroyWeak(Ptr); 197631168b07SJohn McCall break; 197731168b07SJohn McCall } 197831168b07SJohn McCall } 19798ed55a54SJohn McCall 1980f39e12a0SRichard Smith // When optimizing for size, call 'operator delete' unconditionally. 1981f39e12a0SRichard Smith if (CGF.CGM.getCodeGenOpts().OptimizeSize > 1) { 1982f39e12a0SRichard Smith CGF.EmitBlock(UnconditionalDeleteBlock); 19838ed55a54SJohn McCall CGF.PopCleanupBlock(); 1984f39e12a0SRichard Smith return true; 1985f39e12a0SRichard Smith } 1986f39e12a0SRichard Smith 1987f39e12a0SRichard Smith CGF.PopCleanupBlock(); 1988f39e12a0SRichard Smith return false; 19898ed55a54SJohn McCall } 19908ed55a54SJohn McCall 19918ed55a54SJohn McCall namespace { 19928ed55a54SJohn McCall /// Calls the given 'operator delete' on an array of objects. 19937e70d680SDavid Blaikie struct CallArrayDelete final : EHScopeStack::Cleanup { 19948ed55a54SJohn McCall llvm::Value *Ptr; 19958ed55a54SJohn McCall const FunctionDecl *OperatorDelete; 19968ed55a54SJohn McCall llvm::Value *NumElements; 19978ed55a54SJohn McCall QualType ElementType; 19988ed55a54SJohn McCall CharUnits CookieSize; 19998ed55a54SJohn McCall 20008ed55a54SJohn McCall CallArrayDelete(llvm::Value *Ptr, 20018ed55a54SJohn McCall const FunctionDecl *OperatorDelete, 20028ed55a54SJohn McCall llvm::Value *NumElements, 20038ed55a54SJohn McCall QualType ElementType, 20048ed55a54SJohn McCall CharUnits CookieSize) 20058ed55a54SJohn McCall : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements), 20068ed55a54SJohn McCall ElementType(ElementType), CookieSize(CookieSize) {} 20078ed55a54SJohn McCall 20084f12f10dSCraig Topper void Emit(CodeGenFunction &CGF, Flags flags) override { 2009b2f0f057SRichard Smith CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements, 2010b2f0f057SRichard Smith CookieSize); 20118ed55a54SJohn McCall } 20128ed55a54SJohn McCall }; 2013ab9db510SAlexander Kornienko } 20148ed55a54SJohn McCall 20158ed55a54SJohn McCall /// Emit the code for deleting an array of objects. 20168ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF, 2017284c48ffSJohn McCall const CXXDeleteExpr *E, 20187f416cc4SJohn McCall Address deletedPtr, 2019ca2c56f2SJohn McCall QualType elementType) { 20208a13c418SCraig Topper llvm::Value *numElements = nullptr; 20218a13c418SCraig Topper llvm::Value *allocatedPtr = nullptr; 2022ca2c56f2SJohn McCall CharUnits cookieSize; 2023ca2c56f2SJohn McCall CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType, 2024ca2c56f2SJohn McCall numElements, allocatedPtr, cookieSize); 20258ed55a54SJohn McCall 2026ca2c56f2SJohn McCall assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer"); 20278ed55a54SJohn McCall 20288ed55a54SJohn McCall // Make sure that we call delete even if one of the dtors throws. 2029ca2c56f2SJohn McCall const FunctionDecl *operatorDelete = E->getOperatorDelete(); 20308ed55a54SJohn McCall CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup, 2031ca2c56f2SJohn McCall allocatedPtr, operatorDelete, 2032ca2c56f2SJohn McCall numElements, elementType, 2033ca2c56f2SJohn McCall cookieSize); 20348ed55a54SJohn McCall 2035ca2c56f2SJohn McCall // Destroy the elements. 2036ca2c56f2SJohn McCall if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) { 2037ca2c56f2SJohn McCall assert(numElements && "no element count for a type with a destructor!"); 203831168b07SJohn McCall 20397f416cc4SJohn McCall CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType); 20407f416cc4SJohn McCall CharUnits elementAlign = 20417f416cc4SJohn McCall deletedPtr.getAlignment().alignmentOfArrayElement(elementSize); 20427f416cc4SJohn McCall 20437f416cc4SJohn McCall llvm::Value *arrayBegin = deletedPtr.getPointer(); 204442eb658fSNikita Popov llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP( 204542eb658fSNikita Popov deletedPtr.getElementType(), arrayBegin, numElements, "delete.end"); 204697eab0a2SJohn McCall 204797eab0a2SJohn McCall // Note that it is legal to allocate a zero-length array, and we 204897eab0a2SJohn McCall // can never fold the check away because the length should always 204997eab0a2SJohn McCall // come from a cookie. 20507f416cc4SJohn McCall CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign, 2051ca2c56f2SJohn McCall CGF.getDestroyer(dtorKind), 205297eab0a2SJohn McCall /*checkZeroLength*/ true, 2053ca2c56f2SJohn McCall CGF.needsEHCleanup(dtorKind)); 20548ed55a54SJohn McCall } 20558ed55a54SJohn McCall 2056ca2c56f2SJohn McCall // Pop the cleanup block. 20578ed55a54SJohn McCall CGF.PopCleanupBlock(); 20588ed55a54SJohn McCall } 20598ed55a54SJohn McCall 206059486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) { 206159486a2dSAnders Carlsson const Expr *Arg = E->getArgument(); 20627f416cc4SJohn McCall Address Ptr = EmitPointerWithAlignment(Arg); 206359486a2dSAnders Carlsson 206459486a2dSAnders Carlsson // Null check the pointer. 2065f39e12a0SRichard Smith // 2066f39e12a0SRichard Smith // We could avoid this null check if we can determine that the object 2067f39e12a0SRichard Smith // destruction is trivial and doesn't require an array cookie; we can 2068f39e12a0SRichard Smith // unconditionally perform the operator delete call in that case. For now, we 2069f39e12a0SRichard Smith // assume that deleted pointers are null rarely enough that it's better to 2070f39e12a0SRichard Smith // keep the branch. This might be worth revisiting for a -O0 code size win. 207159486a2dSAnders Carlsson llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull"); 207259486a2dSAnders Carlsson llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end"); 207359486a2dSAnders Carlsson 20747f416cc4SJohn McCall llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull"); 207559486a2dSAnders Carlsson 207659486a2dSAnders Carlsson Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull); 207759486a2dSAnders Carlsson EmitBlock(DeleteNotNull); 207859486a2dSAnders Carlsson 20795b34958bSRichard Smith QualType DeleteTy = E->getDestroyedType(); 20805b34958bSRichard Smith 20815b34958bSRichard Smith // A destroying operator delete overrides the entire operation of the 20825b34958bSRichard Smith // delete expression. 20835b34958bSRichard Smith if (E->getOperatorDelete()->isDestroyingOperatorDelete()) { 20845b34958bSRichard Smith EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy); 20855b34958bSRichard Smith EmitBlock(DeleteEnd); 20865b34958bSRichard Smith return; 20875b34958bSRichard Smith } 20885b34958bSRichard Smith 20898ed55a54SJohn McCall // We might be deleting a pointer to array. If so, GEP down to the 20908ed55a54SJohn McCall // first non-array element. 20918ed55a54SJohn McCall // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*) 20928ed55a54SJohn McCall if (DeleteTy->isConstantArrayType()) { 20938ed55a54SJohn McCall llvm::Value *Zero = Builder.getInt32(0); 20940e62c1ccSChris Lattner SmallVector<llvm::Value*,8> GEP; 209559486a2dSAnders Carlsson 20968ed55a54SJohn McCall GEP.push_back(Zero); // point at the outermost array 20978ed55a54SJohn McCall 20988ed55a54SJohn McCall // For each layer of array type we're pointing at: 20998ed55a54SJohn McCall while (const ConstantArrayType *Arr 21008ed55a54SJohn McCall = getContext().getAsConstantArrayType(DeleteTy)) { 21018ed55a54SJohn McCall // 1. Unpeel the array type. 21028ed55a54SJohn McCall DeleteTy = Arr->getElementType(); 21038ed55a54SJohn McCall 21048ed55a54SJohn McCall // 2. GEP to the first element of the array. 21058ed55a54SJohn McCall GEP.push_back(Zero); 21068ed55a54SJohn McCall } 21078ed55a54SJohn McCall 210842eb658fSNikita Popov Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getElementType(), 210942eb658fSNikita Popov Ptr.getPointer(), GEP, "del.first"), 21107f416cc4SJohn McCall Ptr.getAlignment()); 21118ed55a54SJohn McCall } 21128ed55a54SJohn McCall 21137f416cc4SJohn McCall assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType()); 21148ed55a54SJohn McCall 21157270ef57SReid Kleckner if (E->isArrayForm()) { 21167270ef57SReid Kleckner EmitArrayDelete(*this, E, Ptr, DeleteTy); 211759486a2dSAnders Carlsson EmitBlock(DeleteEnd); 2118f39e12a0SRichard Smith } else { 2119f39e12a0SRichard Smith if (!EmitObjectDelete(*this, E, Ptr, DeleteTy, DeleteEnd)) 2120f39e12a0SRichard Smith EmitBlock(DeleteEnd); 2121f39e12a0SRichard Smith } 212259486a2dSAnders Carlsson } 212359486a2dSAnders Carlsson 21241c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) { 21251c3d95ebSDavid Majnemer E = E->IgnoreParens(); 21261c3d95ebSDavid Majnemer 21271c3d95ebSDavid Majnemer if (const auto *CE = dyn_cast<CastExpr>(E)) { 21281c3d95ebSDavid Majnemer if (!CE->getSubExpr()->isGLValue()) 21291c3d95ebSDavid Majnemer return false; 21301c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(CE->getSubExpr()); 21311c3d95ebSDavid Majnemer } 21321c3d95ebSDavid Majnemer 21331c3d95ebSDavid Majnemer if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 21341c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(OVE->getSourceExpr()); 21351c3d95ebSDavid Majnemer 21361c3d95ebSDavid Majnemer if (const auto *BO = dyn_cast<BinaryOperator>(E)) 21371c3d95ebSDavid Majnemer if (BO->getOpcode() == BO_Comma) 21381c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(BO->getRHS()); 21391c3d95ebSDavid Majnemer 21401c3d95ebSDavid Majnemer if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E)) 21411c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(ACO->getTrueExpr()) || 21421c3d95ebSDavid Majnemer isGLValueFromPointerDeref(ACO->getFalseExpr()); 21431c3d95ebSDavid Majnemer 21441c3d95ebSDavid Majnemer // C++11 [expr.sub]p1: 21451c3d95ebSDavid Majnemer // The expression E1[E2] is identical (by definition) to *((E1)+(E2)) 21461c3d95ebSDavid Majnemer if (isa<ArraySubscriptExpr>(E)) 21471c3d95ebSDavid Majnemer return true; 21481c3d95ebSDavid Majnemer 21491c3d95ebSDavid Majnemer if (const auto *UO = dyn_cast<UnaryOperator>(E)) 21501c3d95ebSDavid Majnemer if (UO->getOpcode() == UO_Deref) 21511c3d95ebSDavid Majnemer return true; 21521c3d95ebSDavid Majnemer 21531c3d95ebSDavid Majnemer return false; 21541c3d95ebSDavid Majnemer } 21551c3d95ebSDavid Majnemer 2156747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E, 21572192fe50SChris Lattner llvm::Type *StdTypeInfoPtrTy) { 2158940f02d2SAnders Carlsson // Get the vtable pointer. 2159f139ae3dSAkira Hatanaka Address ThisPtr = CGF.EmitLValue(E).getAddress(CGF); 2160940f02d2SAnders Carlsson 2161d71ad177SStephan Bergmann QualType SrcRecordTy = E->getType(); 2162d71ad177SStephan Bergmann 2163d71ad177SStephan Bergmann // C++ [class.cdtor]p4: 2164d71ad177SStephan Bergmann // If the operand of typeid refers to the object under construction or 2165d71ad177SStephan Bergmann // destruction and the static type of the operand is neither the constructor 2166d71ad177SStephan Bergmann // or destructor’s class nor one of its bases, the behavior is undefined. 2167d71ad177SStephan Bergmann CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(), 2168d71ad177SStephan Bergmann ThisPtr.getPointer(), SrcRecordTy); 2169d71ad177SStephan Bergmann 2170940f02d2SAnders Carlsson // C++ [expr.typeid]p2: 2171940f02d2SAnders Carlsson // If the glvalue expression is obtained by applying the unary * operator to 2172940f02d2SAnders Carlsson // a pointer and the pointer is a null pointer value, the typeid expression 2173940f02d2SAnders Carlsson // throws the std::bad_typeid exception. 21741c3d95ebSDavid Majnemer // 21751c3d95ebSDavid Majnemer // However, this paragraph's intent is not clear. We choose a very generous 21761c3d95ebSDavid Majnemer // interpretation which implores us to consider comma operators, conditional 21771c3d95ebSDavid Majnemer // operators, parentheses and other such constructs. 21781c3d95ebSDavid Majnemer if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked( 21791c3d95ebSDavid Majnemer isGLValueFromPointerDeref(E), SrcRecordTy)) { 2180940f02d2SAnders Carlsson llvm::BasicBlock *BadTypeidBlock = 2181940f02d2SAnders Carlsson CGF.createBasicBlock("typeid.bad_typeid"); 21821162d25cSDavid Majnemer llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end"); 2183940f02d2SAnders Carlsson 21847f416cc4SJohn McCall llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer()); 2185940f02d2SAnders Carlsson CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock); 2186940f02d2SAnders Carlsson 2187940f02d2SAnders Carlsson CGF.EmitBlock(BadTypeidBlock); 21881162d25cSDavid Majnemer CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF); 2189940f02d2SAnders Carlsson CGF.EmitBlock(EndBlock); 2190940f02d2SAnders Carlsson } 2191940f02d2SAnders Carlsson 21921162d25cSDavid Majnemer return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr, 21931162d25cSDavid Majnemer StdTypeInfoPtrTy); 2194940f02d2SAnders Carlsson } 2195940f02d2SAnders Carlsson 219659486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { 21972192fe50SChris Lattner llvm::Type *StdTypeInfoPtrTy = 2198940f02d2SAnders Carlsson ConvertType(E->getType())->getPointerTo(); 2199fd7dfeb7SAnders Carlsson 22003f4336cbSAnders Carlsson if (E->isTypeOperand()) { 22013f4336cbSAnders Carlsson llvm::Constant *TypeInfo = 2202143c55eaSDavid Majnemer CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext())); 2203940f02d2SAnders Carlsson return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy); 22043f4336cbSAnders Carlsson } 2205fd7dfeb7SAnders Carlsson 2206940f02d2SAnders Carlsson // C++ [expr.typeid]p2: 2207940f02d2SAnders Carlsson // When typeid is applied to a glvalue expression whose type is a 2208940f02d2SAnders Carlsson // polymorphic class type, the result refers to a std::type_info object 2209940f02d2SAnders Carlsson // representing the type of the most derived object (that is, the dynamic 2210940f02d2SAnders Carlsson // type) to which the glvalue refers. 2211f975ae48SZequan Wu // If the operand is already most derived object, no need to look up vtable. 2212f975ae48SZequan Wu if (E->isPotentiallyEvaluated() && !E->isMostDerived(getContext())) 2213940f02d2SAnders Carlsson return EmitTypeidFromVTable(*this, E->getExprOperand(), 2214940f02d2SAnders Carlsson StdTypeInfoPtrTy); 2215940f02d2SAnders Carlsson 2216940f02d2SAnders Carlsson QualType OperandTy = E->getExprOperand()->getType(); 2217940f02d2SAnders Carlsson return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy), 2218940f02d2SAnders Carlsson StdTypeInfoPtrTy); 221959486a2dSAnders Carlsson } 222059486a2dSAnders Carlsson 2221c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF, 2222c1c9971cSAnders Carlsson QualType DestTy) { 22232192fe50SChris Lattner llvm::Type *DestLTy = CGF.ConvertType(DestTy); 2224c1c9971cSAnders Carlsson if (DestTy->isPointerType()) 2225c1c9971cSAnders Carlsson return llvm::Constant::getNullValue(DestLTy); 2226c1c9971cSAnders Carlsson 2227c1c9971cSAnders Carlsson /// C++ [expr.dynamic.cast]p9: 2228c1c9971cSAnders Carlsson /// A failed cast to reference type throws std::bad_cast 22291162d25cSDavid Majnemer if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF)) 22301162d25cSDavid Majnemer return nullptr; 2231c1c9971cSAnders Carlsson 2232c1c9971cSAnders Carlsson CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end")); 2233c1c9971cSAnders Carlsson return llvm::UndefValue::get(DestLTy); 2234c1c9971cSAnders Carlsson } 2235c1c9971cSAnders Carlsson 22367f416cc4SJohn McCall llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr, 223759486a2dSAnders Carlsson const CXXDynamicCastExpr *DCE) { 22382bf9b4c0SAlexey Bataev CGM.EmitExplicitCastExprType(DCE, this); 22393f4336cbSAnders Carlsson QualType DestTy = DCE->getTypeAsWritten(); 22403f4336cbSAnders Carlsson 2241c1c9971cSAnders Carlsson QualType SrcTy = DCE->getSubExpr()->getType(); 2242c1c9971cSAnders Carlsson 22431162d25cSDavid Majnemer // C++ [expr.dynamic.cast]p7: 22441162d25cSDavid Majnemer // If T is "pointer to cv void," then the result is a pointer to the most 22451162d25cSDavid Majnemer // derived object pointed to by v. 22461162d25cSDavid Majnemer const PointerType *DestPTy = DestTy->getAs<PointerType>(); 22471162d25cSDavid Majnemer 22481162d25cSDavid Majnemer bool isDynamicCastToVoid; 22491162d25cSDavid Majnemer QualType SrcRecordTy; 22501162d25cSDavid Majnemer QualType DestRecordTy; 22511162d25cSDavid Majnemer if (DestPTy) { 22521162d25cSDavid Majnemer isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType(); 22531162d25cSDavid Majnemer SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType(); 22541162d25cSDavid Majnemer DestRecordTy = DestPTy->getPointeeType(); 22551162d25cSDavid Majnemer } else { 22561162d25cSDavid Majnemer isDynamicCastToVoid = false; 22571162d25cSDavid Majnemer SrcRecordTy = SrcTy; 22581162d25cSDavid Majnemer DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType(); 22591162d25cSDavid Majnemer } 22601162d25cSDavid Majnemer 2261d71ad177SStephan Bergmann // C++ [class.cdtor]p5: 2262d71ad177SStephan Bergmann // If the operand of the dynamic_cast refers to the object under 2263d71ad177SStephan Bergmann // construction or destruction and the static type of the operand is not a 2264d71ad177SStephan Bergmann // pointer to or object of the constructor or destructor’s own class or one 2265d71ad177SStephan Bergmann // of its bases, the dynamic_cast results in undefined behavior. 2266d71ad177SStephan Bergmann EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(), 2267d71ad177SStephan Bergmann SrcRecordTy); 2268d71ad177SStephan Bergmann 2269d71ad177SStephan Bergmann if (DCE->isAlwaysNull()) 2270d71ad177SStephan Bergmann if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy)) 2271d71ad177SStephan Bergmann return T; 2272d71ad177SStephan Bergmann 22731162d25cSDavid Majnemer assert(SrcRecordTy->isRecordType() && "source type must be a record type!"); 22741162d25cSDavid Majnemer 2275882d790fSAnders Carlsson // C++ [expr.dynamic.cast]p4: 2276882d790fSAnders Carlsson // If the value of v is a null pointer value in the pointer case, the result 2277882d790fSAnders Carlsson // is the null pointer value of type T. 22781162d25cSDavid Majnemer bool ShouldNullCheckSrcValue = 22791162d25cSDavid Majnemer CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(), 22801162d25cSDavid Majnemer SrcRecordTy); 228159486a2dSAnders Carlsson 22828a13c418SCraig Topper llvm::BasicBlock *CastNull = nullptr; 22838a13c418SCraig Topper llvm::BasicBlock *CastNotNull = nullptr; 2284882d790fSAnders Carlsson llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end"); 2285fa8b4955SDouglas Gregor 2286882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2287882d790fSAnders Carlsson CastNull = createBasicBlock("dynamic_cast.null"); 2288882d790fSAnders Carlsson CastNotNull = createBasicBlock("dynamic_cast.notnull"); 2289882d790fSAnders Carlsson 22907f416cc4SJohn McCall llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer()); 2291882d790fSAnders Carlsson Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 2292882d790fSAnders Carlsson EmitBlock(CastNotNull); 229359486a2dSAnders Carlsson } 229459486a2dSAnders Carlsson 22957f416cc4SJohn McCall llvm::Value *Value; 22961162d25cSDavid Majnemer if (isDynamicCastToVoid) { 22977f416cc4SJohn McCall Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy, 22981162d25cSDavid Majnemer DestTy); 22991162d25cSDavid Majnemer } else { 23001162d25cSDavid Majnemer assert(DestRecordTy->isRecordType() && 23011162d25cSDavid Majnemer "destination type must be a record type!"); 23027f416cc4SJohn McCall Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy, 23031162d25cSDavid Majnemer DestTy, DestRecordTy, CastEnd); 230467528eaaSDavid Majnemer CastNotNull = Builder.GetInsertBlock(); 23051162d25cSDavid Majnemer } 23063f4336cbSAnders Carlsson 2307882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2308882d790fSAnders Carlsson EmitBranch(CastEnd); 230959486a2dSAnders Carlsson 2310882d790fSAnders Carlsson EmitBlock(CastNull); 2311882d790fSAnders Carlsson EmitBranch(CastEnd); 231259486a2dSAnders Carlsson } 231359486a2dSAnders Carlsson 2314882d790fSAnders Carlsson EmitBlock(CastEnd); 231559486a2dSAnders Carlsson 2316882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2317882d790fSAnders Carlsson llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 2318882d790fSAnders Carlsson PHI->addIncoming(Value, CastNotNull); 2319882d790fSAnders Carlsson PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull); 232059486a2dSAnders Carlsson 2321882d790fSAnders Carlsson Value = PHI; 232259486a2dSAnders Carlsson } 232359486a2dSAnders Carlsson 2324882d790fSAnders Carlsson return Value; 232559486a2dSAnders Carlsson } 2326