1*e5dd7070Spatrick //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===// 2*e5dd7070Spatrick // 3*e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information. 5*e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*e5dd7070Spatrick // 7*e5dd7070Spatrick //===----------------------------------------------------------------------===// 8*e5dd7070Spatrick // 9*e5dd7070Spatrick // This contains code dealing with code generation of C++ expressions 10*e5dd7070Spatrick // 11*e5dd7070Spatrick //===----------------------------------------------------------------------===// 12*e5dd7070Spatrick 13*e5dd7070Spatrick #include "CGCUDARuntime.h" 14*e5dd7070Spatrick #include "CGCXXABI.h" 15*e5dd7070Spatrick #include "CGDebugInfo.h" 16*e5dd7070Spatrick #include "CGObjCRuntime.h" 17*e5dd7070Spatrick #include "CodeGenFunction.h" 18*e5dd7070Spatrick #include "ConstantEmitter.h" 19*e5dd7070Spatrick #include "TargetInfo.h" 20*e5dd7070Spatrick #include "clang/Basic/CodeGenOptions.h" 21*e5dd7070Spatrick #include "clang/CodeGen/CGFunctionInfo.h" 22*e5dd7070Spatrick #include "llvm/IR/Intrinsics.h" 23*e5dd7070Spatrick 24*e5dd7070Spatrick using namespace clang; 25*e5dd7070Spatrick using namespace CodeGen; 26*e5dd7070Spatrick 27*e5dd7070Spatrick namespace { 28*e5dd7070Spatrick struct MemberCallInfo { 29*e5dd7070Spatrick RequiredArgs ReqArgs; 30*e5dd7070Spatrick // Number of prefix arguments for the call. Ignores the `this` pointer. 31*e5dd7070Spatrick unsigned PrefixSize; 32*e5dd7070Spatrick }; 33*e5dd7070Spatrick } 34*e5dd7070Spatrick 35*e5dd7070Spatrick static MemberCallInfo 36*e5dd7070Spatrick commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD, 37*e5dd7070Spatrick llvm::Value *This, llvm::Value *ImplicitParam, 38*e5dd7070Spatrick QualType ImplicitParamTy, const CallExpr *CE, 39*e5dd7070Spatrick CallArgList &Args, CallArgList *RtlArgs) { 40*e5dd7070Spatrick assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) || 41*e5dd7070Spatrick isa<CXXOperatorCallExpr>(CE)); 42*e5dd7070Spatrick assert(MD->isInstance() && 43*e5dd7070Spatrick "Trying to emit a member or operator call expr on a static method!"); 44*e5dd7070Spatrick 45*e5dd7070Spatrick // Push the this ptr. 46*e5dd7070Spatrick const CXXRecordDecl *RD = 47*e5dd7070Spatrick CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD); 48*e5dd7070Spatrick Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD)); 49*e5dd7070Spatrick 50*e5dd7070Spatrick // If there is an implicit parameter (e.g. VTT), emit it. 51*e5dd7070Spatrick if (ImplicitParam) { 52*e5dd7070Spatrick Args.add(RValue::get(ImplicitParam), ImplicitParamTy); 53*e5dd7070Spatrick } 54*e5dd7070Spatrick 55*e5dd7070Spatrick const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 56*e5dd7070Spatrick RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size()); 57*e5dd7070Spatrick unsigned PrefixSize = Args.size() - 1; 58*e5dd7070Spatrick 59*e5dd7070Spatrick // And the rest of the call args. 60*e5dd7070Spatrick if (RtlArgs) { 61*e5dd7070Spatrick // Special case: if the caller emitted the arguments right-to-left already 62*e5dd7070Spatrick // (prior to emitting the *this argument), we're done. This happens for 63*e5dd7070Spatrick // assignment operators. 64*e5dd7070Spatrick Args.addFrom(*RtlArgs); 65*e5dd7070Spatrick } else if (CE) { 66*e5dd7070Spatrick // Special case: skip first argument of CXXOperatorCall (it is "this"). 67*e5dd7070Spatrick unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0; 68*e5dd7070Spatrick CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip), 69*e5dd7070Spatrick CE->getDirectCallee()); 70*e5dd7070Spatrick } else { 71*e5dd7070Spatrick assert( 72*e5dd7070Spatrick FPT->getNumParams() == 0 && 73*e5dd7070Spatrick "No CallExpr specified for function with non-zero number of arguments"); 74*e5dd7070Spatrick } 75*e5dd7070Spatrick return {required, PrefixSize}; 76*e5dd7070Spatrick } 77*e5dd7070Spatrick 78*e5dd7070Spatrick RValue CodeGenFunction::EmitCXXMemberOrOperatorCall( 79*e5dd7070Spatrick const CXXMethodDecl *MD, const CGCallee &Callee, 80*e5dd7070Spatrick ReturnValueSlot ReturnValue, 81*e5dd7070Spatrick llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, 82*e5dd7070Spatrick const CallExpr *CE, CallArgList *RtlArgs) { 83*e5dd7070Spatrick const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 84*e5dd7070Spatrick CallArgList Args; 85*e5dd7070Spatrick MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall( 86*e5dd7070Spatrick *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs); 87*e5dd7070Spatrick auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall( 88*e5dd7070Spatrick Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize); 89*e5dd7070Spatrick return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr, 90*e5dd7070Spatrick CE ? CE->getExprLoc() : SourceLocation()); 91*e5dd7070Spatrick } 92*e5dd7070Spatrick 93*e5dd7070Spatrick RValue CodeGenFunction::EmitCXXDestructorCall( 94*e5dd7070Spatrick GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy, 95*e5dd7070Spatrick llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) { 96*e5dd7070Spatrick const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl()); 97*e5dd7070Spatrick 98*e5dd7070Spatrick assert(!ThisTy.isNull()); 99*e5dd7070Spatrick assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() && 100*e5dd7070Spatrick "Pointer/Object mixup"); 101*e5dd7070Spatrick 102*e5dd7070Spatrick LangAS SrcAS = ThisTy.getAddressSpace(); 103*e5dd7070Spatrick LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace(); 104*e5dd7070Spatrick if (SrcAS != DstAS) { 105*e5dd7070Spatrick QualType DstTy = DtorDecl->getThisType(); 106*e5dd7070Spatrick llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy); 107*e5dd7070Spatrick This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS, 108*e5dd7070Spatrick NewType); 109*e5dd7070Spatrick } 110*e5dd7070Spatrick 111*e5dd7070Spatrick CallArgList Args; 112*e5dd7070Spatrick commonEmitCXXMemberOrOperatorCall(*this, DtorDecl, This, ImplicitParam, 113*e5dd7070Spatrick ImplicitParamTy, CE, Args, nullptr); 114*e5dd7070Spatrick return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee, 115*e5dd7070Spatrick ReturnValueSlot(), Args); 116*e5dd7070Spatrick } 117*e5dd7070Spatrick 118*e5dd7070Spatrick RValue CodeGenFunction::EmitCXXPseudoDestructorExpr( 119*e5dd7070Spatrick const CXXPseudoDestructorExpr *E) { 120*e5dd7070Spatrick QualType DestroyedType = E->getDestroyedType(); 121*e5dd7070Spatrick if (DestroyedType.hasStrongOrWeakObjCLifetime()) { 122*e5dd7070Spatrick // Automatic Reference Counting: 123*e5dd7070Spatrick // If the pseudo-expression names a retainable object with weak or 124*e5dd7070Spatrick // strong lifetime, the object shall be released. 125*e5dd7070Spatrick Expr *BaseExpr = E->getBase(); 126*e5dd7070Spatrick Address BaseValue = Address::invalid(); 127*e5dd7070Spatrick Qualifiers BaseQuals; 128*e5dd7070Spatrick 129*e5dd7070Spatrick // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 130*e5dd7070Spatrick if (E->isArrow()) { 131*e5dd7070Spatrick BaseValue = EmitPointerWithAlignment(BaseExpr); 132*e5dd7070Spatrick const auto *PTy = BaseExpr->getType()->castAs<PointerType>(); 133*e5dd7070Spatrick BaseQuals = PTy->getPointeeType().getQualifiers(); 134*e5dd7070Spatrick } else { 135*e5dd7070Spatrick LValue BaseLV = EmitLValue(BaseExpr); 136*e5dd7070Spatrick BaseValue = BaseLV.getAddress(*this); 137*e5dd7070Spatrick QualType BaseTy = BaseExpr->getType(); 138*e5dd7070Spatrick BaseQuals = BaseTy.getQualifiers(); 139*e5dd7070Spatrick } 140*e5dd7070Spatrick 141*e5dd7070Spatrick switch (DestroyedType.getObjCLifetime()) { 142*e5dd7070Spatrick case Qualifiers::OCL_None: 143*e5dd7070Spatrick case Qualifiers::OCL_ExplicitNone: 144*e5dd7070Spatrick case Qualifiers::OCL_Autoreleasing: 145*e5dd7070Spatrick break; 146*e5dd7070Spatrick 147*e5dd7070Spatrick case Qualifiers::OCL_Strong: 148*e5dd7070Spatrick EmitARCRelease(Builder.CreateLoad(BaseValue, 149*e5dd7070Spatrick DestroyedType.isVolatileQualified()), 150*e5dd7070Spatrick ARCPreciseLifetime); 151*e5dd7070Spatrick break; 152*e5dd7070Spatrick 153*e5dd7070Spatrick case Qualifiers::OCL_Weak: 154*e5dd7070Spatrick EmitARCDestroyWeak(BaseValue); 155*e5dd7070Spatrick break; 156*e5dd7070Spatrick } 157*e5dd7070Spatrick } else { 158*e5dd7070Spatrick // C++ [expr.pseudo]p1: 159*e5dd7070Spatrick // The result shall only be used as the operand for the function call 160*e5dd7070Spatrick // operator (), and the result of such a call has type void. The only 161*e5dd7070Spatrick // effect is the evaluation of the postfix-expression before the dot or 162*e5dd7070Spatrick // arrow. 163*e5dd7070Spatrick EmitIgnoredExpr(E->getBase()); 164*e5dd7070Spatrick } 165*e5dd7070Spatrick 166*e5dd7070Spatrick return RValue::get(nullptr); 167*e5dd7070Spatrick } 168*e5dd7070Spatrick 169*e5dd7070Spatrick static CXXRecordDecl *getCXXRecord(const Expr *E) { 170*e5dd7070Spatrick QualType T = E->getType(); 171*e5dd7070Spatrick if (const PointerType *PTy = T->getAs<PointerType>()) 172*e5dd7070Spatrick T = PTy->getPointeeType(); 173*e5dd7070Spatrick const RecordType *Ty = T->castAs<RecordType>(); 174*e5dd7070Spatrick return cast<CXXRecordDecl>(Ty->getDecl()); 175*e5dd7070Spatrick } 176*e5dd7070Spatrick 177*e5dd7070Spatrick // Note: This function also emit constructor calls to support a MSVC 178*e5dd7070Spatrick // extensions allowing explicit constructor function call. 179*e5dd7070Spatrick RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE, 180*e5dd7070Spatrick ReturnValueSlot ReturnValue) { 181*e5dd7070Spatrick const Expr *callee = CE->getCallee()->IgnoreParens(); 182*e5dd7070Spatrick 183*e5dd7070Spatrick if (isa<BinaryOperator>(callee)) 184*e5dd7070Spatrick return EmitCXXMemberPointerCallExpr(CE, ReturnValue); 185*e5dd7070Spatrick 186*e5dd7070Spatrick const MemberExpr *ME = cast<MemberExpr>(callee); 187*e5dd7070Spatrick const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); 188*e5dd7070Spatrick 189*e5dd7070Spatrick if (MD->isStatic()) { 190*e5dd7070Spatrick // The method is static, emit it as we would a regular call. 191*e5dd7070Spatrick CGCallee callee = 192*e5dd7070Spatrick CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD)); 193*e5dd7070Spatrick return EmitCall(getContext().getPointerType(MD->getType()), callee, CE, 194*e5dd7070Spatrick ReturnValue); 195*e5dd7070Spatrick } 196*e5dd7070Spatrick 197*e5dd7070Spatrick bool HasQualifier = ME->hasQualifier(); 198*e5dd7070Spatrick NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr; 199*e5dd7070Spatrick bool IsArrow = ME->isArrow(); 200*e5dd7070Spatrick const Expr *Base = ME->getBase(); 201*e5dd7070Spatrick 202*e5dd7070Spatrick return EmitCXXMemberOrOperatorMemberCallExpr( 203*e5dd7070Spatrick CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base); 204*e5dd7070Spatrick } 205*e5dd7070Spatrick 206*e5dd7070Spatrick RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( 207*e5dd7070Spatrick const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, 208*e5dd7070Spatrick bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow, 209*e5dd7070Spatrick const Expr *Base) { 210*e5dd7070Spatrick assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE)); 211*e5dd7070Spatrick 212*e5dd7070Spatrick // Compute the object pointer. 213*e5dd7070Spatrick bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier; 214*e5dd7070Spatrick 215*e5dd7070Spatrick const CXXMethodDecl *DevirtualizedMethod = nullptr; 216*e5dd7070Spatrick if (CanUseVirtualCall && 217*e5dd7070Spatrick MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) { 218*e5dd7070Spatrick const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 219*e5dd7070Spatrick DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl); 220*e5dd7070Spatrick assert(DevirtualizedMethod); 221*e5dd7070Spatrick const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent(); 222*e5dd7070Spatrick const Expr *Inner = Base->ignoreParenBaseCasts(); 223*e5dd7070Spatrick if (DevirtualizedMethod->getReturnType().getCanonicalType() != 224*e5dd7070Spatrick MD->getReturnType().getCanonicalType()) 225*e5dd7070Spatrick // If the return types are not the same, this might be a case where more 226*e5dd7070Spatrick // code needs to run to compensate for it. For example, the derived 227*e5dd7070Spatrick // method might return a type that inherits form from the return 228*e5dd7070Spatrick // type of MD and has a prefix. 229*e5dd7070Spatrick // For now we just avoid devirtualizing these covariant cases. 230*e5dd7070Spatrick DevirtualizedMethod = nullptr; 231*e5dd7070Spatrick else if (getCXXRecord(Inner) == DevirtualizedClass) 232*e5dd7070Spatrick // If the class of the Inner expression is where the dynamic method 233*e5dd7070Spatrick // is defined, build the this pointer from it. 234*e5dd7070Spatrick Base = Inner; 235*e5dd7070Spatrick else if (getCXXRecord(Base) != DevirtualizedClass) { 236*e5dd7070Spatrick // If the method is defined in a class that is not the best dynamic 237*e5dd7070Spatrick // one or the one of the full expression, we would have to build 238*e5dd7070Spatrick // a derived-to-base cast to compute the correct this pointer, but 239*e5dd7070Spatrick // we don't have support for that yet, so do a virtual call. 240*e5dd7070Spatrick DevirtualizedMethod = nullptr; 241*e5dd7070Spatrick } 242*e5dd7070Spatrick } 243*e5dd7070Spatrick 244*e5dd7070Spatrick bool TrivialForCodegen = 245*e5dd7070Spatrick MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion()); 246*e5dd7070Spatrick bool TrivialAssignment = 247*e5dd7070Spatrick TrivialForCodegen && 248*e5dd7070Spatrick (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) && 249*e5dd7070Spatrick !MD->getParent()->mayInsertExtraPadding(); 250*e5dd7070Spatrick 251*e5dd7070Spatrick // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment 252*e5dd7070Spatrick // operator before the LHS. 253*e5dd7070Spatrick CallArgList RtlArgStorage; 254*e5dd7070Spatrick CallArgList *RtlArgs = nullptr; 255*e5dd7070Spatrick LValue TrivialAssignmentRHS; 256*e5dd7070Spatrick if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 257*e5dd7070Spatrick if (OCE->isAssignmentOp()) { 258*e5dd7070Spatrick if (TrivialAssignment) { 259*e5dd7070Spatrick TrivialAssignmentRHS = EmitLValue(CE->getArg(1)); 260*e5dd7070Spatrick } else { 261*e5dd7070Spatrick RtlArgs = &RtlArgStorage; 262*e5dd7070Spatrick EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(), 263*e5dd7070Spatrick drop_begin(CE->arguments(), 1), CE->getDirectCallee(), 264*e5dd7070Spatrick /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft); 265*e5dd7070Spatrick } 266*e5dd7070Spatrick } 267*e5dd7070Spatrick } 268*e5dd7070Spatrick 269*e5dd7070Spatrick LValue This; 270*e5dd7070Spatrick if (IsArrow) { 271*e5dd7070Spatrick LValueBaseInfo BaseInfo; 272*e5dd7070Spatrick TBAAAccessInfo TBAAInfo; 273*e5dd7070Spatrick Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo); 274*e5dd7070Spatrick This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo); 275*e5dd7070Spatrick } else { 276*e5dd7070Spatrick This = EmitLValue(Base); 277*e5dd7070Spatrick } 278*e5dd7070Spatrick 279*e5dd7070Spatrick if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 280*e5dd7070Spatrick // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's 281*e5dd7070Spatrick // constructing a new complete object of type Ctor. 282*e5dd7070Spatrick assert(!RtlArgs); 283*e5dd7070Spatrick assert(ReturnValue.isNull() && "Constructor shouldn't have return value"); 284*e5dd7070Spatrick CallArgList Args; 285*e5dd7070Spatrick commonEmitCXXMemberOrOperatorCall( 286*e5dd7070Spatrick *this, Ctor, This.getPointer(*this), /*ImplicitParam=*/nullptr, 287*e5dd7070Spatrick /*ImplicitParamTy=*/QualType(), CE, Args, nullptr); 288*e5dd7070Spatrick 289*e5dd7070Spatrick EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false, 290*e5dd7070Spatrick /*Delegating=*/false, This.getAddress(*this), Args, 291*e5dd7070Spatrick AggValueSlot::DoesNotOverlap, CE->getExprLoc(), 292*e5dd7070Spatrick /*NewPointerIsChecked=*/false); 293*e5dd7070Spatrick return RValue::get(nullptr); 294*e5dd7070Spatrick } 295*e5dd7070Spatrick 296*e5dd7070Spatrick if (TrivialForCodegen) { 297*e5dd7070Spatrick if (isa<CXXDestructorDecl>(MD)) 298*e5dd7070Spatrick return RValue::get(nullptr); 299*e5dd7070Spatrick 300*e5dd7070Spatrick if (TrivialAssignment) { 301*e5dd7070Spatrick // We don't like to generate the trivial copy/move assignment operator 302*e5dd7070Spatrick // when it isn't necessary; just produce the proper effect here. 303*e5dd7070Spatrick // It's important that we use the result of EmitLValue here rather than 304*e5dd7070Spatrick // emitting call arguments, in order to preserve TBAA information from 305*e5dd7070Spatrick // the RHS. 306*e5dd7070Spatrick LValue RHS = isa<CXXOperatorCallExpr>(CE) 307*e5dd7070Spatrick ? TrivialAssignmentRHS 308*e5dd7070Spatrick : EmitLValue(*CE->arg_begin()); 309*e5dd7070Spatrick EmitAggregateAssign(This, RHS, CE->getType()); 310*e5dd7070Spatrick return RValue::get(This.getPointer(*this)); 311*e5dd7070Spatrick } 312*e5dd7070Spatrick 313*e5dd7070Spatrick assert(MD->getParent()->mayInsertExtraPadding() && 314*e5dd7070Spatrick "unknown trivial member function"); 315*e5dd7070Spatrick } 316*e5dd7070Spatrick 317*e5dd7070Spatrick // Compute the function type we're calling. 318*e5dd7070Spatrick const CXXMethodDecl *CalleeDecl = 319*e5dd7070Spatrick DevirtualizedMethod ? DevirtualizedMethod : MD; 320*e5dd7070Spatrick const CGFunctionInfo *FInfo = nullptr; 321*e5dd7070Spatrick if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) 322*e5dd7070Spatrick FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 323*e5dd7070Spatrick GlobalDecl(Dtor, Dtor_Complete)); 324*e5dd7070Spatrick else 325*e5dd7070Spatrick FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl); 326*e5dd7070Spatrick 327*e5dd7070Spatrick llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo); 328*e5dd7070Spatrick 329*e5dd7070Spatrick // C++11 [class.mfct.non-static]p2: 330*e5dd7070Spatrick // If a non-static member function of a class X is called for an object that 331*e5dd7070Spatrick // is not of type X, or of a type derived from X, the behavior is undefined. 332*e5dd7070Spatrick SourceLocation CallLoc; 333*e5dd7070Spatrick ASTContext &C = getContext(); 334*e5dd7070Spatrick if (CE) 335*e5dd7070Spatrick CallLoc = CE->getExprLoc(); 336*e5dd7070Spatrick 337*e5dd7070Spatrick SanitizerSet SkippedChecks; 338*e5dd7070Spatrick if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) { 339*e5dd7070Spatrick auto *IOA = CMCE->getImplicitObjectArgument(); 340*e5dd7070Spatrick bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA); 341*e5dd7070Spatrick if (IsImplicitObjectCXXThis) 342*e5dd7070Spatrick SkippedChecks.set(SanitizerKind::Alignment, true); 343*e5dd7070Spatrick if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA)) 344*e5dd7070Spatrick SkippedChecks.set(SanitizerKind::Null, true); 345*e5dd7070Spatrick } 346*e5dd7070Spatrick EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc, 347*e5dd7070Spatrick This.getPointer(*this), 348*e5dd7070Spatrick C.getRecordType(CalleeDecl->getParent()), 349*e5dd7070Spatrick /*Alignment=*/CharUnits::Zero(), SkippedChecks); 350*e5dd7070Spatrick 351*e5dd7070Spatrick // C++ [class.virtual]p12: 352*e5dd7070Spatrick // Explicit qualification with the scope operator (5.1) suppresses the 353*e5dd7070Spatrick // virtual call mechanism. 354*e5dd7070Spatrick // 355*e5dd7070Spatrick // We also don't emit a virtual call if the base expression has a record type 356*e5dd7070Spatrick // because then we know what the type is. 357*e5dd7070Spatrick bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod; 358*e5dd7070Spatrick 359*e5dd7070Spatrick if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) { 360*e5dd7070Spatrick assert(CE->arg_begin() == CE->arg_end() && 361*e5dd7070Spatrick "Destructor shouldn't have explicit parameters"); 362*e5dd7070Spatrick assert(ReturnValue.isNull() && "Destructor shouldn't have return value"); 363*e5dd7070Spatrick if (UseVirtualCall) { 364*e5dd7070Spatrick CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete, 365*e5dd7070Spatrick This.getAddress(*this), 366*e5dd7070Spatrick cast<CXXMemberCallExpr>(CE)); 367*e5dd7070Spatrick } else { 368*e5dd7070Spatrick GlobalDecl GD(Dtor, Dtor_Complete); 369*e5dd7070Spatrick CGCallee Callee; 370*e5dd7070Spatrick if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier) 371*e5dd7070Spatrick Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty); 372*e5dd7070Spatrick else if (!DevirtualizedMethod) 373*e5dd7070Spatrick Callee = 374*e5dd7070Spatrick CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD); 375*e5dd7070Spatrick else { 376*e5dd7070Spatrick Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD); 377*e5dd7070Spatrick } 378*e5dd7070Spatrick 379*e5dd7070Spatrick QualType ThisTy = 380*e5dd7070Spatrick IsArrow ? Base->getType()->getPointeeType() : Base->getType(); 381*e5dd7070Spatrick EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy, 382*e5dd7070Spatrick /*ImplicitParam=*/nullptr, 383*e5dd7070Spatrick /*ImplicitParamTy=*/QualType(), nullptr); 384*e5dd7070Spatrick } 385*e5dd7070Spatrick return RValue::get(nullptr); 386*e5dd7070Spatrick } 387*e5dd7070Spatrick 388*e5dd7070Spatrick // FIXME: Uses of 'MD' past this point need to be audited. We may need to use 389*e5dd7070Spatrick // 'CalleeDecl' instead. 390*e5dd7070Spatrick 391*e5dd7070Spatrick CGCallee Callee; 392*e5dd7070Spatrick if (UseVirtualCall) { 393*e5dd7070Spatrick Callee = CGCallee::forVirtual(CE, MD, This.getAddress(*this), Ty); 394*e5dd7070Spatrick } else { 395*e5dd7070Spatrick if (SanOpts.has(SanitizerKind::CFINVCall) && 396*e5dd7070Spatrick MD->getParent()->isDynamicClass()) { 397*e5dd7070Spatrick llvm::Value *VTable; 398*e5dd7070Spatrick const CXXRecordDecl *RD; 399*e5dd7070Spatrick std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr( 400*e5dd7070Spatrick *this, This.getAddress(*this), CalleeDecl->getParent()); 401*e5dd7070Spatrick EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc()); 402*e5dd7070Spatrick } 403*e5dd7070Spatrick 404*e5dd7070Spatrick if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier) 405*e5dd7070Spatrick Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty); 406*e5dd7070Spatrick else if (!DevirtualizedMethod) 407*e5dd7070Spatrick Callee = 408*e5dd7070Spatrick CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD)); 409*e5dd7070Spatrick else { 410*e5dd7070Spatrick Callee = 411*e5dd7070Spatrick CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty), 412*e5dd7070Spatrick GlobalDecl(DevirtualizedMethod)); 413*e5dd7070Spatrick } 414*e5dd7070Spatrick } 415*e5dd7070Spatrick 416*e5dd7070Spatrick if (MD->isVirtual()) { 417*e5dd7070Spatrick Address NewThisAddr = 418*e5dd7070Spatrick CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall( 419*e5dd7070Spatrick *this, CalleeDecl, This.getAddress(*this), UseVirtualCall); 420*e5dd7070Spatrick This.setAddress(NewThisAddr); 421*e5dd7070Spatrick } 422*e5dd7070Spatrick 423*e5dd7070Spatrick return EmitCXXMemberOrOperatorCall( 424*e5dd7070Spatrick CalleeDecl, Callee, ReturnValue, This.getPointer(*this), 425*e5dd7070Spatrick /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs); 426*e5dd7070Spatrick } 427*e5dd7070Spatrick 428*e5dd7070Spatrick RValue 429*e5dd7070Spatrick CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 430*e5dd7070Spatrick ReturnValueSlot ReturnValue) { 431*e5dd7070Spatrick const BinaryOperator *BO = 432*e5dd7070Spatrick cast<BinaryOperator>(E->getCallee()->IgnoreParens()); 433*e5dd7070Spatrick const Expr *BaseExpr = BO->getLHS(); 434*e5dd7070Spatrick const Expr *MemFnExpr = BO->getRHS(); 435*e5dd7070Spatrick 436*e5dd7070Spatrick const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>(); 437*e5dd7070Spatrick const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>(); 438*e5dd7070Spatrick const auto *RD = 439*e5dd7070Spatrick cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl()); 440*e5dd7070Spatrick 441*e5dd7070Spatrick // Emit the 'this' pointer. 442*e5dd7070Spatrick Address This = Address::invalid(); 443*e5dd7070Spatrick if (BO->getOpcode() == BO_PtrMemI) 444*e5dd7070Spatrick This = EmitPointerWithAlignment(BaseExpr); 445*e5dd7070Spatrick else 446*e5dd7070Spatrick This = EmitLValue(BaseExpr).getAddress(*this); 447*e5dd7070Spatrick 448*e5dd7070Spatrick EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(), 449*e5dd7070Spatrick QualType(MPT->getClass(), 0)); 450*e5dd7070Spatrick 451*e5dd7070Spatrick // Get the member function pointer. 452*e5dd7070Spatrick llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr); 453*e5dd7070Spatrick 454*e5dd7070Spatrick // Ask the ABI to load the callee. Note that This is modified. 455*e5dd7070Spatrick llvm::Value *ThisPtrForCall = nullptr; 456*e5dd7070Spatrick CGCallee Callee = 457*e5dd7070Spatrick CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, 458*e5dd7070Spatrick ThisPtrForCall, MemFnPtr, MPT); 459*e5dd7070Spatrick 460*e5dd7070Spatrick CallArgList Args; 461*e5dd7070Spatrick 462*e5dd7070Spatrick QualType ThisType = 463*e5dd7070Spatrick getContext().getPointerType(getContext().getTagDeclType(RD)); 464*e5dd7070Spatrick 465*e5dd7070Spatrick // Push the this ptr. 466*e5dd7070Spatrick Args.add(RValue::get(ThisPtrForCall), ThisType); 467*e5dd7070Spatrick 468*e5dd7070Spatrick RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1); 469*e5dd7070Spatrick 470*e5dd7070Spatrick // And the rest of the call args 471*e5dd7070Spatrick EmitCallArgs(Args, FPT, E->arguments()); 472*e5dd7070Spatrick return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required, 473*e5dd7070Spatrick /*PrefixSize=*/0), 474*e5dd7070Spatrick Callee, ReturnValue, Args, nullptr, E->getExprLoc()); 475*e5dd7070Spatrick } 476*e5dd7070Spatrick 477*e5dd7070Spatrick RValue 478*e5dd7070Spatrick CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 479*e5dd7070Spatrick const CXXMethodDecl *MD, 480*e5dd7070Spatrick ReturnValueSlot ReturnValue) { 481*e5dd7070Spatrick assert(MD->isInstance() && 482*e5dd7070Spatrick "Trying to emit a member call expr on a static method!"); 483*e5dd7070Spatrick return EmitCXXMemberOrOperatorMemberCallExpr( 484*e5dd7070Spatrick E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr, 485*e5dd7070Spatrick /*IsArrow=*/false, E->getArg(0)); 486*e5dd7070Spatrick } 487*e5dd7070Spatrick 488*e5dd7070Spatrick RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 489*e5dd7070Spatrick ReturnValueSlot ReturnValue) { 490*e5dd7070Spatrick return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue); 491*e5dd7070Spatrick } 492*e5dd7070Spatrick 493*e5dd7070Spatrick static void EmitNullBaseClassInitialization(CodeGenFunction &CGF, 494*e5dd7070Spatrick Address DestPtr, 495*e5dd7070Spatrick const CXXRecordDecl *Base) { 496*e5dd7070Spatrick if (Base->isEmpty()) 497*e5dd7070Spatrick return; 498*e5dd7070Spatrick 499*e5dd7070Spatrick DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty); 500*e5dd7070Spatrick 501*e5dd7070Spatrick const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base); 502*e5dd7070Spatrick CharUnits NVSize = Layout.getNonVirtualSize(); 503*e5dd7070Spatrick 504*e5dd7070Spatrick // We cannot simply zero-initialize the entire base sub-object if vbptrs are 505*e5dd7070Spatrick // present, they are initialized by the most derived class before calling the 506*e5dd7070Spatrick // constructor. 507*e5dd7070Spatrick SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores; 508*e5dd7070Spatrick Stores.emplace_back(CharUnits::Zero(), NVSize); 509*e5dd7070Spatrick 510*e5dd7070Spatrick // Each store is split by the existence of a vbptr. 511*e5dd7070Spatrick CharUnits VBPtrWidth = CGF.getPointerSize(); 512*e5dd7070Spatrick std::vector<CharUnits> VBPtrOffsets = 513*e5dd7070Spatrick CGF.CGM.getCXXABI().getVBPtrOffsets(Base); 514*e5dd7070Spatrick for (CharUnits VBPtrOffset : VBPtrOffsets) { 515*e5dd7070Spatrick // Stop before we hit any virtual base pointers located in virtual bases. 516*e5dd7070Spatrick if (VBPtrOffset >= NVSize) 517*e5dd7070Spatrick break; 518*e5dd7070Spatrick std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val(); 519*e5dd7070Spatrick CharUnits LastStoreOffset = LastStore.first; 520*e5dd7070Spatrick CharUnits LastStoreSize = LastStore.second; 521*e5dd7070Spatrick 522*e5dd7070Spatrick CharUnits SplitBeforeOffset = LastStoreOffset; 523*e5dd7070Spatrick CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset; 524*e5dd7070Spatrick assert(!SplitBeforeSize.isNegative() && "negative store size!"); 525*e5dd7070Spatrick if (!SplitBeforeSize.isZero()) 526*e5dd7070Spatrick Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize); 527*e5dd7070Spatrick 528*e5dd7070Spatrick CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth; 529*e5dd7070Spatrick CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset; 530*e5dd7070Spatrick assert(!SplitAfterSize.isNegative() && "negative store size!"); 531*e5dd7070Spatrick if (!SplitAfterSize.isZero()) 532*e5dd7070Spatrick Stores.emplace_back(SplitAfterOffset, SplitAfterSize); 533*e5dd7070Spatrick } 534*e5dd7070Spatrick 535*e5dd7070Spatrick // If the type contains a pointer to data member we can't memset it to zero. 536*e5dd7070Spatrick // Instead, create a null constant and copy it to the destination. 537*e5dd7070Spatrick // TODO: there are other patterns besides zero that we can usefully memset, 538*e5dd7070Spatrick // like -1, which happens to be the pattern used by member-pointers. 539*e5dd7070Spatrick // TODO: isZeroInitializable can be over-conservative in the case where a 540*e5dd7070Spatrick // virtual base contains a member pointer. 541*e5dd7070Spatrick llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base); 542*e5dd7070Spatrick if (!NullConstantForBase->isNullValue()) { 543*e5dd7070Spatrick llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable( 544*e5dd7070Spatrick CGF.CGM.getModule(), NullConstantForBase->getType(), 545*e5dd7070Spatrick /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, 546*e5dd7070Spatrick NullConstantForBase, Twine()); 547*e5dd7070Spatrick 548*e5dd7070Spatrick CharUnits Align = std::max(Layout.getNonVirtualAlignment(), 549*e5dd7070Spatrick DestPtr.getAlignment()); 550*e5dd7070Spatrick NullVariable->setAlignment(Align.getAsAlign()); 551*e5dd7070Spatrick 552*e5dd7070Spatrick Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align); 553*e5dd7070Spatrick 554*e5dd7070Spatrick // Get and call the appropriate llvm.memcpy overload. 555*e5dd7070Spatrick for (std::pair<CharUnits, CharUnits> Store : Stores) { 556*e5dd7070Spatrick CharUnits StoreOffset = Store.first; 557*e5dd7070Spatrick CharUnits StoreSize = Store.second; 558*e5dd7070Spatrick llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 559*e5dd7070Spatrick CGF.Builder.CreateMemCpy( 560*e5dd7070Spatrick CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 561*e5dd7070Spatrick CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset), 562*e5dd7070Spatrick StoreSizeVal); 563*e5dd7070Spatrick } 564*e5dd7070Spatrick 565*e5dd7070Spatrick // Otherwise, just memset the whole thing to zero. This is legal 566*e5dd7070Spatrick // because in LLVM, all default initializers (other than the ones we just 567*e5dd7070Spatrick // handled above) are guaranteed to have a bit pattern of all zeros. 568*e5dd7070Spatrick } else { 569*e5dd7070Spatrick for (std::pair<CharUnits, CharUnits> Store : Stores) { 570*e5dd7070Spatrick CharUnits StoreOffset = Store.first; 571*e5dd7070Spatrick CharUnits StoreSize = Store.second; 572*e5dd7070Spatrick llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 573*e5dd7070Spatrick CGF.Builder.CreateMemSet( 574*e5dd7070Spatrick CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 575*e5dd7070Spatrick CGF.Builder.getInt8(0), StoreSizeVal); 576*e5dd7070Spatrick } 577*e5dd7070Spatrick } 578*e5dd7070Spatrick } 579*e5dd7070Spatrick 580*e5dd7070Spatrick void 581*e5dd7070Spatrick CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, 582*e5dd7070Spatrick AggValueSlot Dest) { 583*e5dd7070Spatrick assert(!Dest.isIgnored() && "Must have a destination!"); 584*e5dd7070Spatrick const CXXConstructorDecl *CD = E->getConstructor(); 585*e5dd7070Spatrick 586*e5dd7070Spatrick // If we require zero initialization before (or instead of) calling the 587*e5dd7070Spatrick // constructor, as can be the case with a non-user-provided default 588*e5dd7070Spatrick // constructor, emit the zero initialization now, unless destination is 589*e5dd7070Spatrick // already zeroed. 590*e5dd7070Spatrick if (E->requiresZeroInitialization() && !Dest.isZeroed()) { 591*e5dd7070Spatrick switch (E->getConstructionKind()) { 592*e5dd7070Spatrick case CXXConstructExpr::CK_Delegating: 593*e5dd7070Spatrick case CXXConstructExpr::CK_Complete: 594*e5dd7070Spatrick EmitNullInitialization(Dest.getAddress(), E->getType()); 595*e5dd7070Spatrick break; 596*e5dd7070Spatrick case CXXConstructExpr::CK_VirtualBase: 597*e5dd7070Spatrick case CXXConstructExpr::CK_NonVirtualBase: 598*e5dd7070Spatrick EmitNullBaseClassInitialization(*this, Dest.getAddress(), 599*e5dd7070Spatrick CD->getParent()); 600*e5dd7070Spatrick break; 601*e5dd7070Spatrick } 602*e5dd7070Spatrick } 603*e5dd7070Spatrick 604*e5dd7070Spatrick // If this is a call to a trivial default constructor, do nothing. 605*e5dd7070Spatrick if (CD->isTrivial() && CD->isDefaultConstructor()) 606*e5dd7070Spatrick return; 607*e5dd7070Spatrick 608*e5dd7070Spatrick // Elide the constructor if we're constructing from a temporary. 609*e5dd7070Spatrick // The temporary check is required because Sema sets this on NRVO 610*e5dd7070Spatrick // returns. 611*e5dd7070Spatrick if (getLangOpts().ElideConstructors && E->isElidable()) { 612*e5dd7070Spatrick assert(getContext().hasSameUnqualifiedType(E->getType(), 613*e5dd7070Spatrick E->getArg(0)->getType())); 614*e5dd7070Spatrick if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) { 615*e5dd7070Spatrick EmitAggExpr(E->getArg(0), Dest); 616*e5dd7070Spatrick return; 617*e5dd7070Spatrick } 618*e5dd7070Spatrick } 619*e5dd7070Spatrick 620*e5dd7070Spatrick if (const ArrayType *arrayType 621*e5dd7070Spatrick = getContext().getAsArrayType(E->getType())) { 622*e5dd7070Spatrick EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E, 623*e5dd7070Spatrick Dest.isSanitizerChecked()); 624*e5dd7070Spatrick } else { 625*e5dd7070Spatrick CXXCtorType Type = Ctor_Complete; 626*e5dd7070Spatrick bool ForVirtualBase = false; 627*e5dd7070Spatrick bool Delegating = false; 628*e5dd7070Spatrick 629*e5dd7070Spatrick switch (E->getConstructionKind()) { 630*e5dd7070Spatrick case CXXConstructExpr::CK_Delegating: 631*e5dd7070Spatrick // We should be emitting a constructor; GlobalDecl will assert this 632*e5dd7070Spatrick Type = CurGD.getCtorType(); 633*e5dd7070Spatrick Delegating = true; 634*e5dd7070Spatrick break; 635*e5dd7070Spatrick 636*e5dd7070Spatrick case CXXConstructExpr::CK_Complete: 637*e5dd7070Spatrick Type = Ctor_Complete; 638*e5dd7070Spatrick break; 639*e5dd7070Spatrick 640*e5dd7070Spatrick case CXXConstructExpr::CK_VirtualBase: 641*e5dd7070Spatrick ForVirtualBase = true; 642*e5dd7070Spatrick LLVM_FALLTHROUGH; 643*e5dd7070Spatrick 644*e5dd7070Spatrick case CXXConstructExpr::CK_NonVirtualBase: 645*e5dd7070Spatrick Type = Ctor_Base; 646*e5dd7070Spatrick } 647*e5dd7070Spatrick 648*e5dd7070Spatrick // Call the constructor. 649*e5dd7070Spatrick EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E); 650*e5dd7070Spatrick } 651*e5dd7070Spatrick } 652*e5dd7070Spatrick 653*e5dd7070Spatrick void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, 654*e5dd7070Spatrick const Expr *Exp) { 655*e5dd7070Spatrick if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp)) 656*e5dd7070Spatrick Exp = E->getSubExpr(); 657*e5dd7070Spatrick assert(isa<CXXConstructExpr>(Exp) && 658*e5dd7070Spatrick "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"); 659*e5dd7070Spatrick const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp); 660*e5dd7070Spatrick const CXXConstructorDecl *CD = E->getConstructor(); 661*e5dd7070Spatrick RunCleanupsScope Scope(*this); 662*e5dd7070Spatrick 663*e5dd7070Spatrick // If we require zero initialization before (or instead of) calling the 664*e5dd7070Spatrick // constructor, as can be the case with a non-user-provided default 665*e5dd7070Spatrick // constructor, emit the zero initialization now. 666*e5dd7070Spatrick // FIXME. Do I still need this for a copy ctor synthesis? 667*e5dd7070Spatrick if (E->requiresZeroInitialization()) 668*e5dd7070Spatrick EmitNullInitialization(Dest, E->getType()); 669*e5dd7070Spatrick 670*e5dd7070Spatrick assert(!getContext().getAsConstantArrayType(E->getType()) 671*e5dd7070Spatrick && "EmitSynthesizedCXXCopyCtor - Copied-in Array"); 672*e5dd7070Spatrick EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E); 673*e5dd7070Spatrick } 674*e5dd7070Spatrick 675*e5dd7070Spatrick static CharUnits CalculateCookiePadding(CodeGenFunction &CGF, 676*e5dd7070Spatrick const CXXNewExpr *E) { 677*e5dd7070Spatrick if (!E->isArray()) 678*e5dd7070Spatrick return CharUnits::Zero(); 679*e5dd7070Spatrick 680*e5dd7070Spatrick // No cookie is required if the operator new[] being used is the 681*e5dd7070Spatrick // reserved placement operator new[]. 682*e5dd7070Spatrick if (E->getOperatorNew()->isReservedGlobalPlacementOperator()) 683*e5dd7070Spatrick return CharUnits::Zero(); 684*e5dd7070Spatrick 685*e5dd7070Spatrick return CGF.CGM.getCXXABI().GetArrayCookieSize(E); 686*e5dd7070Spatrick } 687*e5dd7070Spatrick 688*e5dd7070Spatrick static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, 689*e5dd7070Spatrick const CXXNewExpr *e, 690*e5dd7070Spatrick unsigned minElements, 691*e5dd7070Spatrick llvm::Value *&numElements, 692*e5dd7070Spatrick llvm::Value *&sizeWithoutCookie) { 693*e5dd7070Spatrick QualType type = e->getAllocatedType(); 694*e5dd7070Spatrick 695*e5dd7070Spatrick if (!e->isArray()) { 696*e5dd7070Spatrick CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 697*e5dd7070Spatrick sizeWithoutCookie 698*e5dd7070Spatrick = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity()); 699*e5dd7070Spatrick return sizeWithoutCookie; 700*e5dd7070Spatrick } 701*e5dd7070Spatrick 702*e5dd7070Spatrick // The width of size_t. 703*e5dd7070Spatrick unsigned sizeWidth = CGF.SizeTy->getBitWidth(); 704*e5dd7070Spatrick 705*e5dd7070Spatrick // Figure out the cookie size. 706*e5dd7070Spatrick llvm::APInt cookieSize(sizeWidth, 707*e5dd7070Spatrick CalculateCookiePadding(CGF, e).getQuantity()); 708*e5dd7070Spatrick 709*e5dd7070Spatrick // Emit the array size expression. 710*e5dd7070Spatrick // We multiply the size of all dimensions for NumElements. 711*e5dd7070Spatrick // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6. 712*e5dd7070Spatrick numElements = 713*e5dd7070Spatrick ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType()); 714*e5dd7070Spatrick if (!numElements) 715*e5dd7070Spatrick numElements = CGF.EmitScalarExpr(*e->getArraySize()); 716*e5dd7070Spatrick assert(isa<llvm::IntegerType>(numElements->getType())); 717*e5dd7070Spatrick 718*e5dd7070Spatrick // The number of elements can be have an arbitrary integer type; 719*e5dd7070Spatrick // essentially, we need to multiply it by a constant factor, add a 720*e5dd7070Spatrick // cookie size, and verify that the result is representable as a 721*e5dd7070Spatrick // size_t. That's just a gloss, though, and it's wrong in one 722*e5dd7070Spatrick // important way: if the count is negative, it's an error even if 723*e5dd7070Spatrick // the cookie size would bring the total size >= 0. 724*e5dd7070Spatrick bool isSigned 725*e5dd7070Spatrick = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType(); 726*e5dd7070Spatrick llvm::IntegerType *numElementsType 727*e5dd7070Spatrick = cast<llvm::IntegerType>(numElements->getType()); 728*e5dd7070Spatrick unsigned numElementsWidth = numElementsType->getBitWidth(); 729*e5dd7070Spatrick 730*e5dd7070Spatrick // Compute the constant factor. 731*e5dd7070Spatrick llvm::APInt arraySizeMultiplier(sizeWidth, 1); 732*e5dd7070Spatrick while (const ConstantArrayType *CAT 733*e5dd7070Spatrick = CGF.getContext().getAsConstantArrayType(type)) { 734*e5dd7070Spatrick type = CAT->getElementType(); 735*e5dd7070Spatrick arraySizeMultiplier *= CAT->getSize(); 736*e5dd7070Spatrick } 737*e5dd7070Spatrick 738*e5dd7070Spatrick CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 739*e5dd7070Spatrick llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity()); 740*e5dd7070Spatrick typeSizeMultiplier *= arraySizeMultiplier; 741*e5dd7070Spatrick 742*e5dd7070Spatrick // This will be a size_t. 743*e5dd7070Spatrick llvm::Value *size; 744*e5dd7070Spatrick 745*e5dd7070Spatrick // If someone is doing 'new int[42]' there is no need to do a dynamic check. 746*e5dd7070Spatrick // Don't bloat the -O0 code. 747*e5dd7070Spatrick if (llvm::ConstantInt *numElementsC = 748*e5dd7070Spatrick dyn_cast<llvm::ConstantInt>(numElements)) { 749*e5dd7070Spatrick const llvm::APInt &count = numElementsC->getValue(); 750*e5dd7070Spatrick 751*e5dd7070Spatrick bool hasAnyOverflow = false; 752*e5dd7070Spatrick 753*e5dd7070Spatrick // If 'count' was a negative number, it's an overflow. 754*e5dd7070Spatrick if (isSigned && count.isNegative()) 755*e5dd7070Spatrick hasAnyOverflow = true; 756*e5dd7070Spatrick 757*e5dd7070Spatrick // We want to do all this arithmetic in size_t. If numElements is 758*e5dd7070Spatrick // wider than that, check whether it's already too big, and if so, 759*e5dd7070Spatrick // overflow. 760*e5dd7070Spatrick else if (numElementsWidth > sizeWidth && 761*e5dd7070Spatrick numElementsWidth - sizeWidth > count.countLeadingZeros()) 762*e5dd7070Spatrick hasAnyOverflow = true; 763*e5dd7070Spatrick 764*e5dd7070Spatrick // Okay, compute a count at the right width. 765*e5dd7070Spatrick llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth); 766*e5dd7070Spatrick 767*e5dd7070Spatrick // If there is a brace-initializer, we cannot allocate fewer elements than 768*e5dd7070Spatrick // there are initializers. If we do, that's treated like an overflow. 769*e5dd7070Spatrick if (adjustedCount.ult(minElements)) 770*e5dd7070Spatrick hasAnyOverflow = true; 771*e5dd7070Spatrick 772*e5dd7070Spatrick // Scale numElements by that. This might overflow, but we don't 773*e5dd7070Spatrick // care because it only overflows if allocationSize does, too, and 774*e5dd7070Spatrick // if that overflows then we shouldn't use this. 775*e5dd7070Spatrick numElements = llvm::ConstantInt::get(CGF.SizeTy, 776*e5dd7070Spatrick adjustedCount * arraySizeMultiplier); 777*e5dd7070Spatrick 778*e5dd7070Spatrick // Compute the size before cookie, and track whether it overflowed. 779*e5dd7070Spatrick bool overflow; 780*e5dd7070Spatrick llvm::APInt allocationSize 781*e5dd7070Spatrick = adjustedCount.umul_ov(typeSizeMultiplier, overflow); 782*e5dd7070Spatrick hasAnyOverflow |= overflow; 783*e5dd7070Spatrick 784*e5dd7070Spatrick // Add in the cookie, and check whether it's overflowed. 785*e5dd7070Spatrick if (cookieSize != 0) { 786*e5dd7070Spatrick // Save the current size without a cookie. This shouldn't be 787*e5dd7070Spatrick // used if there was overflow. 788*e5dd7070Spatrick sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 789*e5dd7070Spatrick 790*e5dd7070Spatrick allocationSize = allocationSize.uadd_ov(cookieSize, overflow); 791*e5dd7070Spatrick hasAnyOverflow |= overflow; 792*e5dd7070Spatrick } 793*e5dd7070Spatrick 794*e5dd7070Spatrick // On overflow, produce a -1 so operator new will fail. 795*e5dd7070Spatrick if (hasAnyOverflow) { 796*e5dd7070Spatrick size = llvm::Constant::getAllOnesValue(CGF.SizeTy); 797*e5dd7070Spatrick } else { 798*e5dd7070Spatrick size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 799*e5dd7070Spatrick } 800*e5dd7070Spatrick 801*e5dd7070Spatrick // Otherwise, we might need to use the overflow intrinsics. 802*e5dd7070Spatrick } else { 803*e5dd7070Spatrick // There are up to five conditions we need to test for: 804*e5dd7070Spatrick // 1) if isSigned, we need to check whether numElements is negative; 805*e5dd7070Spatrick // 2) if numElementsWidth > sizeWidth, we need to check whether 806*e5dd7070Spatrick // numElements is larger than something representable in size_t; 807*e5dd7070Spatrick // 3) if minElements > 0, we need to check whether numElements is smaller 808*e5dd7070Spatrick // than that. 809*e5dd7070Spatrick // 4) we need to compute 810*e5dd7070Spatrick // sizeWithoutCookie := numElements * typeSizeMultiplier 811*e5dd7070Spatrick // and check whether it overflows; and 812*e5dd7070Spatrick // 5) if we need a cookie, we need to compute 813*e5dd7070Spatrick // size := sizeWithoutCookie + cookieSize 814*e5dd7070Spatrick // and check whether it overflows. 815*e5dd7070Spatrick 816*e5dd7070Spatrick llvm::Value *hasOverflow = nullptr; 817*e5dd7070Spatrick 818*e5dd7070Spatrick // If numElementsWidth > sizeWidth, then one way or another, we're 819*e5dd7070Spatrick // going to have to do a comparison for (2), and this happens to 820*e5dd7070Spatrick // take care of (1), too. 821*e5dd7070Spatrick if (numElementsWidth > sizeWidth) { 822*e5dd7070Spatrick llvm::APInt threshold(numElementsWidth, 1); 823*e5dd7070Spatrick threshold <<= sizeWidth; 824*e5dd7070Spatrick 825*e5dd7070Spatrick llvm::Value *thresholdV 826*e5dd7070Spatrick = llvm::ConstantInt::get(numElementsType, threshold); 827*e5dd7070Spatrick 828*e5dd7070Spatrick hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV); 829*e5dd7070Spatrick numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy); 830*e5dd7070Spatrick 831*e5dd7070Spatrick // Otherwise, if we're signed, we want to sext up to size_t. 832*e5dd7070Spatrick } else if (isSigned) { 833*e5dd7070Spatrick if (numElementsWidth < sizeWidth) 834*e5dd7070Spatrick numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy); 835*e5dd7070Spatrick 836*e5dd7070Spatrick // If there's a non-1 type size multiplier, then we can do the 837*e5dd7070Spatrick // signedness check at the same time as we do the multiply 838*e5dd7070Spatrick // because a negative number times anything will cause an 839*e5dd7070Spatrick // unsigned overflow. Otherwise, we have to do it here. But at least 840*e5dd7070Spatrick // in this case, we can subsume the >= minElements check. 841*e5dd7070Spatrick if (typeSizeMultiplier == 1) 842*e5dd7070Spatrick hasOverflow = CGF.Builder.CreateICmpSLT(numElements, 843*e5dd7070Spatrick llvm::ConstantInt::get(CGF.SizeTy, minElements)); 844*e5dd7070Spatrick 845*e5dd7070Spatrick // Otherwise, zext up to size_t if necessary. 846*e5dd7070Spatrick } else if (numElementsWidth < sizeWidth) { 847*e5dd7070Spatrick numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy); 848*e5dd7070Spatrick } 849*e5dd7070Spatrick 850*e5dd7070Spatrick assert(numElements->getType() == CGF.SizeTy); 851*e5dd7070Spatrick 852*e5dd7070Spatrick if (minElements) { 853*e5dd7070Spatrick // Don't allow allocation of fewer elements than we have initializers. 854*e5dd7070Spatrick if (!hasOverflow) { 855*e5dd7070Spatrick hasOverflow = CGF.Builder.CreateICmpULT(numElements, 856*e5dd7070Spatrick llvm::ConstantInt::get(CGF.SizeTy, minElements)); 857*e5dd7070Spatrick } else if (numElementsWidth > sizeWidth) { 858*e5dd7070Spatrick // The other existing overflow subsumes this check. 859*e5dd7070Spatrick // We do an unsigned comparison, since any signed value < -1 is 860*e5dd7070Spatrick // taken care of either above or below. 861*e5dd7070Spatrick hasOverflow = CGF.Builder.CreateOr(hasOverflow, 862*e5dd7070Spatrick CGF.Builder.CreateICmpULT(numElements, 863*e5dd7070Spatrick llvm::ConstantInt::get(CGF.SizeTy, minElements))); 864*e5dd7070Spatrick } 865*e5dd7070Spatrick } 866*e5dd7070Spatrick 867*e5dd7070Spatrick size = numElements; 868*e5dd7070Spatrick 869*e5dd7070Spatrick // Multiply by the type size if necessary. This multiplier 870*e5dd7070Spatrick // includes all the factors for nested arrays. 871*e5dd7070Spatrick // 872*e5dd7070Spatrick // This step also causes numElements to be scaled up by the 873*e5dd7070Spatrick // nested-array factor if necessary. Overflow on this computation 874*e5dd7070Spatrick // can be ignored because the result shouldn't be used if 875*e5dd7070Spatrick // allocation fails. 876*e5dd7070Spatrick if (typeSizeMultiplier != 1) { 877*e5dd7070Spatrick llvm::Function *umul_with_overflow 878*e5dd7070Spatrick = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy); 879*e5dd7070Spatrick 880*e5dd7070Spatrick llvm::Value *tsmV = 881*e5dd7070Spatrick llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier); 882*e5dd7070Spatrick llvm::Value *result = 883*e5dd7070Spatrick CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV}); 884*e5dd7070Spatrick 885*e5dd7070Spatrick llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 886*e5dd7070Spatrick if (hasOverflow) 887*e5dd7070Spatrick hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 888*e5dd7070Spatrick else 889*e5dd7070Spatrick hasOverflow = overflowed; 890*e5dd7070Spatrick 891*e5dd7070Spatrick size = CGF.Builder.CreateExtractValue(result, 0); 892*e5dd7070Spatrick 893*e5dd7070Spatrick // Also scale up numElements by the array size multiplier. 894*e5dd7070Spatrick if (arraySizeMultiplier != 1) { 895*e5dd7070Spatrick // If the base element type size is 1, then we can re-use the 896*e5dd7070Spatrick // multiply we just did. 897*e5dd7070Spatrick if (typeSize.isOne()) { 898*e5dd7070Spatrick assert(arraySizeMultiplier == typeSizeMultiplier); 899*e5dd7070Spatrick numElements = size; 900*e5dd7070Spatrick 901*e5dd7070Spatrick // Otherwise we need a separate multiply. 902*e5dd7070Spatrick } else { 903*e5dd7070Spatrick llvm::Value *asmV = 904*e5dd7070Spatrick llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier); 905*e5dd7070Spatrick numElements = CGF.Builder.CreateMul(numElements, asmV); 906*e5dd7070Spatrick } 907*e5dd7070Spatrick } 908*e5dd7070Spatrick } else { 909*e5dd7070Spatrick // numElements doesn't need to be scaled. 910*e5dd7070Spatrick assert(arraySizeMultiplier == 1); 911*e5dd7070Spatrick } 912*e5dd7070Spatrick 913*e5dd7070Spatrick // Add in the cookie size if necessary. 914*e5dd7070Spatrick if (cookieSize != 0) { 915*e5dd7070Spatrick sizeWithoutCookie = size; 916*e5dd7070Spatrick 917*e5dd7070Spatrick llvm::Function *uadd_with_overflow 918*e5dd7070Spatrick = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy); 919*e5dd7070Spatrick 920*e5dd7070Spatrick llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize); 921*e5dd7070Spatrick llvm::Value *result = 922*e5dd7070Spatrick CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV}); 923*e5dd7070Spatrick 924*e5dd7070Spatrick llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 925*e5dd7070Spatrick if (hasOverflow) 926*e5dd7070Spatrick hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 927*e5dd7070Spatrick else 928*e5dd7070Spatrick hasOverflow = overflowed; 929*e5dd7070Spatrick 930*e5dd7070Spatrick size = CGF.Builder.CreateExtractValue(result, 0); 931*e5dd7070Spatrick } 932*e5dd7070Spatrick 933*e5dd7070Spatrick // If we had any possibility of dynamic overflow, make a select to 934*e5dd7070Spatrick // overwrite 'size' with an all-ones value, which should cause 935*e5dd7070Spatrick // operator new to throw. 936*e5dd7070Spatrick if (hasOverflow) 937*e5dd7070Spatrick size = CGF.Builder.CreateSelect(hasOverflow, 938*e5dd7070Spatrick llvm::Constant::getAllOnesValue(CGF.SizeTy), 939*e5dd7070Spatrick size); 940*e5dd7070Spatrick } 941*e5dd7070Spatrick 942*e5dd7070Spatrick if (cookieSize == 0) 943*e5dd7070Spatrick sizeWithoutCookie = size; 944*e5dd7070Spatrick else 945*e5dd7070Spatrick assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?"); 946*e5dd7070Spatrick 947*e5dd7070Spatrick return size; 948*e5dd7070Spatrick } 949*e5dd7070Spatrick 950*e5dd7070Spatrick static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, 951*e5dd7070Spatrick QualType AllocType, Address NewPtr, 952*e5dd7070Spatrick AggValueSlot::Overlap_t MayOverlap) { 953*e5dd7070Spatrick // FIXME: Refactor with EmitExprAsInit. 954*e5dd7070Spatrick switch (CGF.getEvaluationKind(AllocType)) { 955*e5dd7070Spatrick case TEK_Scalar: 956*e5dd7070Spatrick CGF.EmitScalarInit(Init, nullptr, 957*e5dd7070Spatrick CGF.MakeAddrLValue(NewPtr, AllocType), false); 958*e5dd7070Spatrick return; 959*e5dd7070Spatrick case TEK_Complex: 960*e5dd7070Spatrick CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType), 961*e5dd7070Spatrick /*isInit*/ true); 962*e5dd7070Spatrick return; 963*e5dd7070Spatrick case TEK_Aggregate: { 964*e5dd7070Spatrick AggValueSlot Slot 965*e5dd7070Spatrick = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(), 966*e5dd7070Spatrick AggValueSlot::IsDestructed, 967*e5dd7070Spatrick AggValueSlot::DoesNotNeedGCBarriers, 968*e5dd7070Spatrick AggValueSlot::IsNotAliased, 969*e5dd7070Spatrick MayOverlap, AggValueSlot::IsNotZeroed, 970*e5dd7070Spatrick AggValueSlot::IsSanitizerChecked); 971*e5dd7070Spatrick CGF.EmitAggExpr(Init, Slot); 972*e5dd7070Spatrick return; 973*e5dd7070Spatrick } 974*e5dd7070Spatrick } 975*e5dd7070Spatrick llvm_unreachable("bad evaluation kind"); 976*e5dd7070Spatrick } 977*e5dd7070Spatrick 978*e5dd7070Spatrick void CodeGenFunction::EmitNewArrayInitializer( 979*e5dd7070Spatrick const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy, 980*e5dd7070Spatrick Address BeginPtr, llvm::Value *NumElements, 981*e5dd7070Spatrick llvm::Value *AllocSizeWithoutCookie) { 982*e5dd7070Spatrick // If we have a type with trivial initialization and no initializer, 983*e5dd7070Spatrick // there's nothing to do. 984*e5dd7070Spatrick if (!E->hasInitializer()) 985*e5dd7070Spatrick return; 986*e5dd7070Spatrick 987*e5dd7070Spatrick Address CurPtr = BeginPtr; 988*e5dd7070Spatrick 989*e5dd7070Spatrick unsigned InitListElements = 0; 990*e5dd7070Spatrick 991*e5dd7070Spatrick const Expr *Init = E->getInitializer(); 992*e5dd7070Spatrick Address EndOfInit = Address::invalid(); 993*e5dd7070Spatrick QualType::DestructionKind DtorKind = ElementType.isDestructedType(); 994*e5dd7070Spatrick EHScopeStack::stable_iterator Cleanup; 995*e5dd7070Spatrick llvm::Instruction *CleanupDominator = nullptr; 996*e5dd7070Spatrick 997*e5dd7070Spatrick CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType); 998*e5dd7070Spatrick CharUnits ElementAlign = 999*e5dd7070Spatrick BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize); 1000*e5dd7070Spatrick 1001*e5dd7070Spatrick // Attempt to perform zero-initialization using memset. 1002*e5dd7070Spatrick auto TryMemsetInitialization = [&]() -> bool { 1003*e5dd7070Spatrick // FIXME: If the type is a pointer-to-data-member under the Itanium ABI, 1004*e5dd7070Spatrick // we can initialize with a memset to -1. 1005*e5dd7070Spatrick if (!CGM.getTypes().isZeroInitializable(ElementType)) 1006*e5dd7070Spatrick return false; 1007*e5dd7070Spatrick 1008*e5dd7070Spatrick // Optimization: since zero initialization will just set the memory 1009*e5dd7070Spatrick // to all zeroes, generate a single memset to do it in one shot. 1010*e5dd7070Spatrick 1011*e5dd7070Spatrick // Subtract out the size of any elements we've already initialized. 1012*e5dd7070Spatrick auto *RemainingSize = AllocSizeWithoutCookie; 1013*e5dd7070Spatrick if (InitListElements) { 1014*e5dd7070Spatrick // We know this can't overflow; we check this when doing the allocation. 1015*e5dd7070Spatrick auto *InitializedSize = llvm::ConstantInt::get( 1016*e5dd7070Spatrick RemainingSize->getType(), 1017*e5dd7070Spatrick getContext().getTypeSizeInChars(ElementType).getQuantity() * 1018*e5dd7070Spatrick InitListElements); 1019*e5dd7070Spatrick RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize); 1020*e5dd7070Spatrick } 1021*e5dd7070Spatrick 1022*e5dd7070Spatrick // Create the memset. 1023*e5dd7070Spatrick Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false); 1024*e5dd7070Spatrick return true; 1025*e5dd7070Spatrick }; 1026*e5dd7070Spatrick 1027*e5dd7070Spatrick // If the initializer is an initializer list, first do the explicit elements. 1028*e5dd7070Spatrick if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 1029*e5dd7070Spatrick // Initializing from a (braced) string literal is a special case; the init 1030*e5dd7070Spatrick // list element does not initialize a (single) array element. 1031*e5dd7070Spatrick if (ILE->isStringLiteralInit()) { 1032*e5dd7070Spatrick // Initialize the initial portion of length equal to that of the string 1033*e5dd7070Spatrick // literal. The allocation must be for at least this much; we emitted a 1034*e5dd7070Spatrick // check for that earlier. 1035*e5dd7070Spatrick AggValueSlot Slot = 1036*e5dd7070Spatrick AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(), 1037*e5dd7070Spatrick AggValueSlot::IsDestructed, 1038*e5dd7070Spatrick AggValueSlot::DoesNotNeedGCBarriers, 1039*e5dd7070Spatrick AggValueSlot::IsNotAliased, 1040*e5dd7070Spatrick AggValueSlot::DoesNotOverlap, 1041*e5dd7070Spatrick AggValueSlot::IsNotZeroed, 1042*e5dd7070Spatrick AggValueSlot::IsSanitizerChecked); 1043*e5dd7070Spatrick EmitAggExpr(ILE->getInit(0), Slot); 1044*e5dd7070Spatrick 1045*e5dd7070Spatrick // Move past these elements. 1046*e5dd7070Spatrick InitListElements = 1047*e5dd7070Spatrick cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 1048*e5dd7070Spatrick ->getSize().getZExtValue(); 1049*e5dd7070Spatrick CurPtr = 1050*e5dd7070Spatrick Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(), 1051*e5dd7070Spatrick Builder.getSize(InitListElements), 1052*e5dd7070Spatrick "string.init.end"), 1053*e5dd7070Spatrick CurPtr.getAlignment().alignmentAtOffset(InitListElements * 1054*e5dd7070Spatrick ElementSize)); 1055*e5dd7070Spatrick 1056*e5dd7070Spatrick // Zero out the rest, if any remain. 1057*e5dd7070Spatrick llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 1058*e5dd7070Spatrick if (!ConstNum || !ConstNum->equalsInt(InitListElements)) { 1059*e5dd7070Spatrick bool OK = TryMemsetInitialization(); 1060*e5dd7070Spatrick (void)OK; 1061*e5dd7070Spatrick assert(OK && "couldn't memset character type?"); 1062*e5dd7070Spatrick } 1063*e5dd7070Spatrick return; 1064*e5dd7070Spatrick } 1065*e5dd7070Spatrick 1066*e5dd7070Spatrick InitListElements = ILE->getNumInits(); 1067*e5dd7070Spatrick 1068*e5dd7070Spatrick // If this is a multi-dimensional array new, we will initialize multiple 1069*e5dd7070Spatrick // elements with each init list element. 1070*e5dd7070Spatrick QualType AllocType = E->getAllocatedType(); 1071*e5dd7070Spatrick if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>( 1072*e5dd7070Spatrick AllocType->getAsArrayTypeUnsafe())) { 1073*e5dd7070Spatrick ElementTy = ConvertTypeForMem(AllocType); 1074*e5dd7070Spatrick CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy); 1075*e5dd7070Spatrick InitListElements *= getContext().getConstantArrayElementCount(CAT); 1076*e5dd7070Spatrick } 1077*e5dd7070Spatrick 1078*e5dd7070Spatrick // Enter a partial-destruction Cleanup if necessary. 1079*e5dd7070Spatrick if (needsEHCleanup(DtorKind)) { 1080*e5dd7070Spatrick // In principle we could tell the Cleanup where we are more 1081*e5dd7070Spatrick // directly, but the control flow can get so varied here that it 1082*e5dd7070Spatrick // would actually be quite complex. Therefore we go through an 1083*e5dd7070Spatrick // alloca. 1084*e5dd7070Spatrick EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(), 1085*e5dd7070Spatrick "array.init.end"); 1086*e5dd7070Spatrick CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit); 1087*e5dd7070Spatrick pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit, 1088*e5dd7070Spatrick ElementType, ElementAlign, 1089*e5dd7070Spatrick getDestroyer(DtorKind)); 1090*e5dd7070Spatrick Cleanup = EHStack.stable_begin(); 1091*e5dd7070Spatrick } 1092*e5dd7070Spatrick 1093*e5dd7070Spatrick CharUnits StartAlign = CurPtr.getAlignment(); 1094*e5dd7070Spatrick for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) { 1095*e5dd7070Spatrick // Tell the cleanup that it needs to destroy up to this 1096*e5dd7070Spatrick // element. TODO: some of these stores can be trivially 1097*e5dd7070Spatrick // observed to be unnecessary. 1098*e5dd7070Spatrick if (EndOfInit.isValid()) { 1099*e5dd7070Spatrick auto FinishedPtr = 1100*e5dd7070Spatrick Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType()); 1101*e5dd7070Spatrick Builder.CreateStore(FinishedPtr, EndOfInit); 1102*e5dd7070Spatrick } 1103*e5dd7070Spatrick // FIXME: If the last initializer is an incomplete initializer list for 1104*e5dd7070Spatrick // an array, and we have an array filler, we can fold together the two 1105*e5dd7070Spatrick // initialization loops. 1106*e5dd7070Spatrick StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), 1107*e5dd7070Spatrick ILE->getInit(i)->getType(), CurPtr, 1108*e5dd7070Spatrick AggValueSlot::DoesNotOverlap); 1109*e5dd7070Spatrick CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(), 1110*e5dd7070Spatrick Builder.getSize(1), 1111*e5dd7070Spatrick "array.exp.next"), 1112*e5dd7070Spatrick StartAlign.alignmentAtOffset((i + 1) * ElementSize)); 1113*e5dd7070Spatrick } 1114*e5dd7070Spatrick 1115*e5dd7070Spatrick // The remaining elements are filled with the array filler expression. 1116*e5dd7070Spatrick Init = ILE->getArrayFiller(); 1117*e5dd7070Spatrick 1118*e5dd7070Spatrick // Extract the initializer for the individual array elements by pulling 1119*e5dd7070Spatrick // out the array filler from all the nested initializer lists. This avoids 1120*e5dd7070Spatrick // generating a nested loop for the initialization. 1121*e5dd7070Spatrick while (Init && Init->getType()->isConstantArrayType()) { 1122*e5dd7070Spatrick auto *SubILE = dyn_cast<InitListExpr>(Init); 1123*e5dd7070Spatrick if (!SubILE) 1124*e5dd7070Spatrick break; 1125*e5dd7070Spatrick assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?"); 1126*e5dd7070Spatrick Init = SubILE->getArrayFiller(); 1127*e5dd7070Spatrick } 1128*e5dd7070Spatrick 1129*e5dd7070Spatrick // Switch back to initializing one base element at a time. 1130*e5dd7070Spatrick CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType()); 1131*e5dd7070Spatrick } 1132*e5dd7070Spatrick 1133*e5dd7070Spatrick // If all elements have already been initialized, skip any further 1134*e5dd7070Spatrick // initialization. 1135*e5dd7070Spatrick llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 1136*e5dd7070Spatrick if (ConstNum && ConstNum->getZExtValue() <= InitListElements) { 1137*e5dd7070Spatrick // If there was a Cleanup, deactivate it. 1138*e5dd7070Spatrick if (CleanupDominator) 1139*e5dd7070Spatrick DeactivateCleanupBlock(Cleanup, CleanupDominator); 1140*e5dd7070Spatrick return; 1141*e5dd7070Spatrick } 1142*e5dd7070Spatrick 1143*e5dd7070Spatrick assert(Init && "have trailing elements to initialize but no initializer"); 1144*e5dd7070Spatrick 1145*e5dd7070Spatrick // If this is a constructor call, try to optimize it out, and failing that 1146*e5dd7070Spatrick // emit a single loop to initialize all remaining elements. 1147*e5dd7070Spatrick if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 1148*e5dd7070Spatrick CXXConstructorDecl *Ctor = CCE->getConstructor(); 1149*e5dd7070Spatrick if (Ctor->isTrivial()) { 1150*e5dd7070Spatrick // If new expression did not specify value-initialization, then there 1151*e5dd7070Spatrick // is no initialization. 1152*e5dd7070Spatrick if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty()) 1153*e5dd7070Spatrick return; 1154*e5dd7070Spatrick 1155*e5dd7070Spatrick if (TryMemsetInitialization()) 1156*e5dd7070Spatrick return; 1157*e5dd7070Spatrick } 1158*e5dd7070Spatrick 1159*e5dd7070Spatrick // Store the new Cleanup position for irregular Cleanups. 1160*e5dd7070Spatrick // 1161*e5dd7070Spatrick // FIXME: Share this cleanup with the constructor call emission rather than 1162*e5dd7070Spatrick // having it create a cleanup of its own. 1163*e5dd7070Spatrick if (EndOfInit.isValid()) 1164*e5dd7070Spatrick Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 1165*e5dd7070Spatrick 1166*e5dd7070Spatrick // Emit a constructor call loop to initialize the remaining elements. 1167*e5dd7070Spatrick if (InitListElements) 1168*e5dd7070Spatrick NumElements = Builder.CreateSub( 1169*e5dd7070Spatrick NumElements, 1170*e5dd7070Spatrick llvm::ConstantInt::get(NumElements->getType(), InitListElements)); 1171*e5dd7070Spatrick EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE, 1172*e5dd7070Spatrick /*NewPointerIsChecked*/true, 1173*e5dd7070Spatrick CCE->requiresZeroInitialization()); 1174*e5dd7070Spatrick return; 1175*e5dd7070Spatrick } 1176*e5dd7070Spatrick 1177*e5dd7070Spatrick // If this is value-initialization, we can usually use memset. 1178*e5dd7070Spatrick ImplicitValueInitExpr IVIE(ElementType); 1179*e5dd7070Spatrick if (isa<ImplicitValueInitExpr>(Init)) { 1180*e5dd7070Spatrick if (TryMemsetInitialization()) 1181*e5dd7070Spatrick return; 1182*e5dd7070Spatrick 1183*e5dd7070Spatrick // Switch to an ImplicitValueInitExpr for the element type. This handles 1184*e5dd7070Spatrick // only one case: multidimensional array new of pointers to members. In 1185*e5dd7070Spatrick // all other cases, we already have an initializer for the array element. 1186*e5dd7070Spatrick Init = &IVIE; 1187*e5dd7070Spatrick } 1188*e5dd7070Spatrick 1189*e5dd7070Spatrick // At this point we should have found an initializer for the individual 1190*e5dd7070Spatrick // elements of the array. 1191*e5dd7070Spatrick assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) && 1192*e5dd7070Spatrick "got wrong type of element to initialize"); 1193*e5dd7070Spatrick 1194*e5dd7070Spatrick // If we have an empty initializer list, we can usually use memset. 1195*e5dd7070Spatrick if (auto *ILE = dyn_cast<InitListExpr>(Init)) 1196*e5dd7070Spatrick if (ILE->getNumInits() == 0 && TryMemsetInitialization()) 1197*e5dd7070Spatrick return; 1198*e5dd7070Spatrick 1199*e5dd7070Spatrick // If we have a struct whose every field is value-initialized, we can 1200*e5dd7070Spatrick // usually use memset. 1201*e5dd7070Spatrick if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 1202*e5dd7070Spatrick if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 1203*e5dd7070Spatrick if (RType->getDecl()->isStruct()) { 1204*e5dd7070Spatrick unsigned NumElements = 0; 1205*e5dd7070Spatrick if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl())) 1206*e5dd7070Spatrick NumElements = CXXRD->getNumBases(); 1207*e5dd7070Spatrick for (auto *Field : RType->getDecl()->fields()) 1208*e5dd7070Spatrick if (!Field->isUnnamedBitfield()) 1209*e5dd7070Spatrick ++NumElements; 1210*e5dd7070Spatrick // FIXME: Recurse into nested InitListExprs. 1211*e5dd7070Spatrick if (ILE->getNumInits() == NumElements) 1212*e5dd7070Spatrick for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 1213*e5dd7070Spatrick if (!isa<ImplicitValueInitExpr>(ILE->getInit(i))) 1214*e5dd7070Spatrick --NumElements; 1215*e5dd7070Spatrick if (ILE->getNumInits() == NumElements && TryMemsetInitialization()) 1216*e5dd7070Spatrick return; 1217*e5dd7070Spatrick } 1218*e5dd7070Spatrick } 1219*e5dd7070Spatrick } 1220*e5dd7070Spatrick 1221*e5dd7070Spatrick // Create the loop blocks. 1222*e5dd7070Spatrick llvm::BasicBlock *EntryBB = Builder.GetInsertBlock(); 1223*e5dd7070Spatrick llvm::BasicBlock *LoopBB = createBasicBlock("new.loop"); 1224*e5dd7070Spatrick llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end"); 1225*e5dd7070Spatrick 1226*e5dd7070Spatrick // Find the end of the array, hoisted out of the loop. 1227*e5dd7070Spatrick llvm::Value *EndPtr = 1228*e5dd7070Spatrick Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end"); 1229*e5dd7070Spatrick 1230*e5dd7070Spatrick // If the number of elements isn't constant, we have to now check if there is 1231*e5dd7070Spatrick // anything left to initialize. 1232*e5dd7070Spatrick if (!ConstNum) { 1233*e5dd7070Spatrick llvm::Value *IsEmpty = 1234*e5dd7070Spatrick Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty"); 1235*e5dd7070Spatrick Builder.CreateCondBr(IsEmpty, ContBB, LoopBB); 1236*e5dd7070Spatrick } 1237*e5dd7070Spatrick 1238*e5dd7070Spatrick // Enter the loop. 1239*e5dd7070Spatrick EmitBlock(LoopBB); 1240*e5dd7070Spatrick 1241*e5dd7070Spatrick // Set up the current-element phi. 1242*e5dd7070Spatrick llvm::PHINode *CurPtrPhi = 1243*e5dd7070Spatrick Builder.CreatePHI(CurPtr.getType(), 2, "array.cur"); 1244*e5dd7070Spatrick CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB); 1245*e5dd7070Spatrick 1246*e5dd7070Spatrick CurPtr = Address(CurPtrPhi, ElementAlign); 1247*e5dd7070Spatrick 1248*e5dd7070Spatrick // Store the new Cleanup position for irregular Cleanups. 1249*e5dd7070Spatrick if (EndOfInit.isValid()) 1250*e5dd7070Spatrick Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 1251*e5dd7070Spatrick 1252*e5dd7070Spatrick // Enter a partial-destruction Cleanup if necessary. 1253*e5dd7070Spatrick if (!CleanupDominator && needsEHCleanup(DtorKind)) { 1254*e5dd7070Spatrick pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(), 1255*e5dd7070Spatrick ElementType, ElementAlign, 1256*e5dd7070Spatrick getDestroyer(DtorKind)); 1257*e5dd7070Spatrick Cleanup = EHStack.stable_begin(); 1258*e5dd7070Spatrick CleanupDominator = Builder.CreateUnreachable(); 1259*e5dd7070Spatrick } 1260*e5dd7070Spatrick 1261*e5dd7070Spatrick // Emit the initializer into this element. 1262*e5dd7070Spatrick StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr, 1263*e5dd7070Spatrick AggValueSlot::DoesNotOverlap); 1264*e5dd7070Spatrick 1265*e5dd7070Spatrick // Leave the Cleanup if we entered one. 1266*e5dd7070Spatrick if (CleanupDominator) { 1267*e5dd7070Spatrick DeactivateCleanupBlock(Cleanup, CleanupDominator); 1268*e5dd7070Spatrick CleanupDominator->eraseFromParent(); 1269*e5dd7070Spatrick } 1270*e5dd7070Spatrick 1271*e5dd7070Spatrick // Advance to the next element by adjusting the pointer type as necessary. 1272*e5dd7070Spatrick llvm::Value *NextPtr = 1273*e5dd7070Spatrick Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1, 1274*e5dd7070Spatrick "array.next"); 1275*e5dd7070Spatrick 1276*e5dd7070Spatrick // Check whether we've gotten to the end of the array and, if so, 1277*e5dd7070Spatrick // exit the loop. 1278*e5dd7070Spatrick llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend"); 1279*e5dd7070Spatrick Builder.CreateCondBr(IsEnd, ContBB, LoopBB); 1280*e5dd7070Spatrick CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock()); 1281*e5dd7070Spatrick 1282*e5dd7070Spatrick EmitBlock(ContBB); 1283*e5dd7070Spatrick } 1284*e5dd7070Spatrick 1285*e5dd7070Spatrick static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E, 1286*e5dd7070Spatrick QualType ElementType, llvm::Type *ElementTy, 1287*e5dd7070Spatrick Address NewPtr, llvm::Value *NumElements, 1288*e5dd7070Spatrick llvm::Value *AllocSizeWithoutCookie) { 1289*e5dd7070Spatrick ApplyDebugLocation DL(CGF, E); 1290*e5dd7070Spatrick if (E->isArray()) 1291*e5dd7070Spatrick CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements, 1292*e5dd7070Spatrick AllocSizeWithoutCookie); 1293*e5dd7070Spatrick else if (const Expr *Init = E->getInitializer()) 1294*e5dd7070Spatrick StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr, 1295*e5dd7070Spatrick AggValueSlot::DoesNotOverlap); 1296*e5dd7070Spatrick } 1297*e5dd7070Spatrick 1298*e5dd7070Spatrick /// Emit a call to an operator new or operator delete function, as implicitly 1299*e5dd7070Spatrick /// created by new-expressions and delete-expressions. 1300*e5dd7070Spatrick static RValue EmitNewDeleteCall(CodeGenFunction &CGF, 1301*e5dd7070Spatrick const FunctionDecl *CalleeDecl, 1302*e5dd7070Spatrick const FunctionProtoType *CalleeType, 1303*e5dd7070Spatrick const CallArgList &Args) { 1304*e5dd7070Spatrick llvm::CallBase *CallOrInvoke; 1305*e5dd7070Spatrick llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl); 1306*e5dd7070Spatrick CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl)); 1307*e5dd7070Spatrick RValue RV = 1308*e5dd7070Spatrick CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall( 1309*e5dd7070Spatrick Args, CalleeType, /*ChainCall=*/false), 1310*e5dd7070Spatrick Callee, ReturnValueSlot(), Args, &CallOrInvoke); 1311*e5dd7070Spatrick 1312*e5dd7070Spatrick /// C++1y [expr.new]p10: 1313*e5dd7070Spatrick /// [In a new-expression,] an implementation is allowed to omit a call 1314*e5dd7070Spatrick /// to a replaceable global allocation function. 1315*e5dd7070Spatrick /// 1316*e5dd7070Spatrick /// We model such elidable calls with the 'builtin' attribute. 1317*e5dd7070Spatrick llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr); 1318*e5dd7070Spatrick if (CalleeDecl->isReplaceableGlobalAllocationFunction() && 1319*e5dd7070Spatrick Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) { 1320*e5dd7070Spatrick CallOrInvoke->addAttribute(llvm::AttributeList::FunctionIndex, 1321*e5dd7070Spatrick llvm::Attribute::Builtin); 1322*e5dd7070Spatrick } 1323*e5dd7070Spatrick 1324*e5dd7070Spatrick return RV; 1325*e5dd7070Spatrick } 1326*e5dd7070Spatrick 1327*e5dd7070Spatrick RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 1328*e5dd7070Spatrick const CallExpr *TheCall, 1329*e5dd7070Spatrick bool IsDelete) { 1330*e5dd7070Spatrick CallArgList Args; 1331*e5dd7070Spatrick EmitCallArgs(Args, Type->getParamTypes(), TheCall->arguments()); 1332*e5dd7070Spatrick // Find the allocation or deallocation function that we're calling. 1333*e5dd7070Spatrick ASTContext &Ctx = getContext(); 1334*e5dd7070Spatrick DeclarationName Name = Ctx.DeclarationNames 1335*e5dd7070Spatrick .getCXXOperatorName(IsDelete ? OO_Delete : OO_New); 1336*e5dd7070Spatrick 1337*e5dd7070Spatrick for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name)) 1338*e5dd7070Spatrick if (auto *FD = dyn_cast<FunctionDecl>(Decl)) 1339*e5dd7070Spatrick if (Ctx.hasSameType(FD->getType(), QualType(Type, 0))) 1340*e5dd7070Spatrick return EmitNewDeleteCall(*this, FD, Type, Args); 1341*e5dd7070Spatrick llvm_unreachable("predeclared global operator new/delete is missing"); 1342*e5dd7070Spatrick } 1343*e5dd7070Spatrick 1344*e5dd7070Spatrick namespace { 1345*e5dd7070Spatrick /// The parameters to pass to a usual operator delete. 1346*e5dd7070Spatrick struct UsualDeleteParams { 1347*e5dd7070Spatrick bool DestroyingDelete = false; 1348*e5dd7070Spatrick bool Size = false; 1349*e5dd7070Spatrick bool Alignment = false; 1350*e5dd7070Spatrick }; 1351*e5dd7070Spatrick } 1352*e5dd7070Spatrick 1353*e5dd7070Spatrick static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) { 1354*e5dd7070Spatrick UsualDeleteParams Params; 1355*e5dd7070Spatrick 1356*e5dd7070Spatrick const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 1357*e5dd7070Spatrick auto AI = FPT->param_type_begin(), AE = FPT->param_type_end(); 1358*e5dd7070Spatrick 1359*e5dd7070Spatrick // The first argument is always a void*. 1360*e5dd7070Spatrick ++AI; 1361*e5dd7070Spatrick 1362*e5dd7070Spatrick // The next parameter may be a std::destroying_delete_t. 1363*e5dd7070Spatrick if (FD->isDestroyingOperatorDelete()) { 1364*e5dd7070Spatrick Params.DestroyingDelete = true; 1365*e5dd7070Spatrick assert(AI != AE); 1366*e5dd7070Spatrick ++AI; 1367*e5dd7070Spatrick } 1368*e5dd7070Spatrick 1369*e5dd7070Spatrick // Figure out what other parameters we should be implicitly passing. 1370*e5dd7070Spatrick if (AI != AE && (*AI)->isIntegerType()) { 1371*e5dd7070Spatrick Params.Size = true; 1372*e5dd7070Spatrick ++AI; 1373*e5dd7070Spatrick } 1374*e5dd7070Spatrick 1375*e5dd7070Spatrick if (AI != AE && (*AI)->isAlignValT()) { 1376*e5dd7070Spatrick Params.Alignment = true; 1377*e5dd7070Spatrick ++AI; 1378*e5dd7070Spatrick } 1379*e5dd7070Spatrick 1380*e5dd7070Spatrick assert(AI == AE && "unexpected usual deallocation function parameter"); 1381*e5dd7070Spatrick return Params; 1382*e5dd7070Spatrick } 1383*e5dd7070Spatrick 1384*e5dd7070Spatrick namespace { 1385*e5dd7070Spatrick /// A cleanup to call the given 'operator delete' function upon abnormal 1386*e5dd7070Spatrick /// exit from a new expression. Templated on a traits type that deals with 1387*e5dd7070Spatrick /// ensuring that the arguments dominate the cleanup if necessary. 1388*e5dd7070Spatrick template<typename Traits> 1389*e5dd7070Spatrick class CallDeleteDuringNew final : public EHScopeStack::Cleanup { 1390*e5dd7070Spatrick /// Type used to hold llvm::Value*s. 1391*e5dd7070Spatrick typedef typename Traits::ValueTy ValueTy; 1392*e5dd7070Spatrick /// Type used to hold RValues. 1393*e5dd7070Spatrick typedef typename Traits::RValueTy RValueTy; 1394*e5dd7070Spatrick struct PlacementArg { 1395*e5dd7070Spatrick RValueTy ArgValue; 1396*e5dd7070Spatrick QualType ArgType; 1397*e5dd7070Spatrick }; 1398*e5dd7070Spatrick 1399*e5dd7070Spatrick unsigned NumPlacementArgs : 31; 1400*e5dd7070Spatrick unsigned PassAlignmentToPlacementDelete : 1; 1401*e5dd7070Spatrick const FunctionDecl *OperatorDelete; 1402*e5dd7070Spatrick ValueTy Ptr; 1403*e5dd7070Spatrick ValueTy AllocSize; 1404*e5dd7070Spatrick CharUnits AllocAlign; 1405*e5dd7070Spatrick 1406*e5dd7070Spatrick PlacementArg *getPlacementArgs() { 1407*e5dd7070Spatrick return reinterpret_cast<PlacementArg *>(this + 1); 1408*e5dd7070Spatrick } 1409*e5dd7070Spatrick 1410*e5dd7070Spatrick public: 1411*e5dd7070Spatrick static size_t getExtraSize(size_t NumPlacementArgs) { 1412*e5dd7070Spatrick return NumPlacementArgs * sizeof(PlacementArg); 1413*e5dd7070Spatrick } 1414*e5dd7070Spatrick 1415*e5dd7070Spatrick CallDeleteDuringNew(size_t NumPlacementArgs, 1416*e5dd7070Spatrick const FunctionDecl *OperatorDelete, ValueTy Ptr, 1417*e5dd7070Spatrick ValueTy AllocSize, bool PassAlignmentToPlacementDelete, 1418*e5dd7070Spatrick CharUnits AllocAlign) 1419*e5dd7070Spatrick : NumPlacementArgs(NumPlacementArgs), 1420*e5dd7070Spatrick PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete), 1421*e5dd7070Spatrick OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize), 1422*e5dd7070Spatrick AllocAlign(AllocAlign) {} 1423*e5dd7070Spatrick 1424*e5dd7070Spatrick void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) { 1425*e5dd7070Spatrick assert(I < NumPlacementArgs && "index out of range"); 1426*e5dd7070Spatrick getPlacementArgs()[I] = {Arg, Type}; 1427*e5dd7070Spatrick } 1428*e5dd7070Spatrick 1429*e5dd7070Spatrick void Emit(CodeGenFunction &CGF, Flags flags) override { 1430*e5dd7070Spatrick const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>(); 1431*e5dd7070Spatrick CallArgList DeleteArgs; 1432*e5dd7070Spatrick 1433*e5dd7070Spatrick // The first argument is always a void* (or C* for a destroying operator 1434*e5dd7070Spatrick // delete for class type C). 1435*e5dd7070Spatrick DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0)); 1436*e5dd7070Spatrick 1437*e5dd7070Spatrick // Figure out what other parameters we should be implicitly passing. 1438*e5dd7070Spatrick UsualDeleteParams Params; 1439*e5dd7070Spatrick if (NumPlacementArgs) { 1440*e5dd7070Spatrick // A placement deallocation function is implicitly passed an alignment 1441*e5dd7070Spatrick // if the placement allocation function was, but is never passed a size. 1442*e5dd7070Spatrick Params.Alignment = PassAlignmentToPlacementDelete; 1443*e5dd7070Spatrick } else { 1444*e5dd7070Spatrick // For a non-placement new-expression, 'operator delete' can take a 1445*e5dd7070Spatrick // size and/or an alignment if it has the right parameters. 1446*e5dd7070Spatrick Params = getUsualDeleteParams(OperatorDelete); 1447*e5dd7070Spatrick } 1448*e5dd7070Spatrick 1449*e5dd7070Spatrick assert(!Params.DestroyingDelete && 1450*e5dd7070Spatrick "should not call destroying delete in a new-expression"); 1451*e5dd7070Spatrick 1452*e5dd7070Spatrick // The second argument can be a std::size_t (for non-placement delete). 1453*e5dd7070Spatrick if (Params.Size) 1454*e5dd7070Spatrick DeleteArgs.add(Traits::get(CGF, AllocSize), 1455*e5dd7070Spatrick CGF.getContext().getSizeType()); 1456*e5dd7070Spatrick 1457*e5dd7070Spatrick // The next (second or third) argument can be a std::align_val_t, which 1458*e5dd7070Spatrick // is an enum whose underlying type is std::size_t. 1459*e5dd7070Spatrick // FIXME: Use the right type as the parameter type. Note that in a call 1460*e5dd7070Spatrick // to operator delete(size_t, ...), we may not have it available. 1461*e5dd7070Spatrick if (Params.Alignment) 1462*e5dd7070Spatrick DeleteArgs.add(RValue::get(llvm::ConstantInt::get( 1463*e5dd7070Spatrick CGF.SizeTy, AllocAlign.getQuantity())), 1464*e5dd7070Spatrick CGF.getContext().getSizeType()); 1465*e5dd7070Spatrick 1466*e5dd7070Spatrick // Pass the rest of the arguments, which must match exactly. 1467*e5dd7070Spatrick for (unsigned I = 0; I != NumPlacementArgs; ++I) { 1468*e5dd7070Spatrick auto Arg = getPlacementArgs()[I]; 1469*e5dd7070Spatrick DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType); 1470*e5dd7070Spatrick } 1471*e5dd7070Spatrick 1472*e5dd7070Spatrick // Call 'operator delete'. 1473*e5dd7070Spatrick EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs); 1474*e5dd7070Spatrick } 1475*e5dd7070Spatrick }; 1476*e5dd7070Spatrick } 1477*e5dd7070Spatrick 1478*e5dd7070Spatrick /// Enter a cleanup to call 'operator delete' if the initializer in a 1479*e5dd7070Spatrick /// new-expression throws. 1480*e5dd7070Spatrick static void EnterNewDeleteCleanup(CodeGenFunction &CGF, 1481*e5dd7070Spatrick const CXXNewExpr *E, 1482*e5dd7070Spatrick Address NewPtr, 1483*e5dd7070Spatrick llvm::Value *AllocSize, 1484*e5dd7070Spatrick CharUnits AllocAlign, 1485*e5dd7070Spatrick const CallArgList &NewArgs) { 1486*e5dd7070Spatrick unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1; 1487*e5dd7070Spatrick 1488*e5dd7070Spatrick // If we're not inside a conditional branch, then the cleanup will 1489*e5dd7070Spatrick // dominate and we can do the easier (and more efficient) thing. 1490*e5dd7070Spatrick if (!CGF.isInConditionalBranch()) { 1491*e5dd7070Spatrick struct DirectCleanupTraits { 1492*e5dd7070Spatrick typedef llvm::Value *ValueTy; 1493*e5dd7070Spatrick typedef RValue RValueTy; 1494*e5dd7070Spatrick static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); } 1495*e5dd7070Spatrick static RValue get(CodeGenFunction &, RValueTy V) { return V; } 1496*e5dd7070Spatrick }; 1497*e5dd7070Spatrick 1498*e5dd7070Spatrick typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup; 1499*e5dd7070Spatrick 1500*e5dd7070Spatrick DirectCleanup *Cleanup = CGF.EHStack 1501*e5dd7070Spatrick .pushCleanupWithExtra<DirectCleanup>(EHCleanup, 1502*e5dd7070Spatrick E->getNumPlacementArgs(), 1503*e5dd7070Spatrick E->getOperatorDelete(), 1504*e5dd7070Spatrick NewPtr.getPointer(), 1505*e5dd7070Spatrick AllocSize, 1506*e5dd7070Spatrick E->passAlignment(), 1507*e5dd7070Spatrick AllocAlign); 1508*e5dd7070Spatrick for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1509*e5dd7070Spatrick auto &Arg = NewArgs[I + NumNonPlacementArgs]; 1510*e5dd7070Spatrick Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty); 1511*e5dd7070Spatrick } 1512*e5dd7070Spatrick 1513*e5dd7070Spatrick return; 1514*e5dd7070Spatrick } 1515*e5dd7070Spatrick 1516*e5dd7070Spatrick // Otherwise, we need to save all this stuff. 1517*e5dd7070Spatrick DominatingValue<RValue>::saved_type SavedNewPtr = 1518*e5dd7070Spatrick DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer())); 1519*e5dd7070Spatrick DominatingValue<RValue>::saved_type SavedAllocSize = 1520*e5dd7070Spatrick DominatingValue<RValue>::save(CGF, RValue::get(AllocSize)); 1521*e5dd7070Spatrick 1522*e5dd7070Spatrick struct ConditionalCleanupTraits { 1523*e5dd7070Spatrick typedef DominatingValue<RValue>::saved_type ValueTy; 1524*e5dd7070Spatrick typedef DominatingValue<RValue>::saved_type RValueTy; 1525*e5dd7070Spatrick static RValue get(CodeGenFunction &CGF, ValueTy V) { 1526*e5dd7070Spatrick return V.restore(CGF); 1527*e5dd7070Spatrick } 1528*e5dd7070Spatrick }; 1529*e5dd7070Spatrick typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup; 1530*e5dd7070Spatrick 1531*e5dd7070Spatrick ConditionalCleanup *Cleanup = CGF.EHStack 1532*e5dd7070Spatrick .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup, 1533*e5dd7070Spatrick E->getNumPlacementArgs(), 1534*e5dd7070Spatrick E->getOperatorDelete(), 1535*e5dd7070Spatrick SavedNewPtr, 1536*e5dd7070Spatrick SavedAllocSize, 1537*e5dd7070Spatrick E->passAlignment(), 1538*e5dd7070Spatrick AllocAlign); 1539*e5dd7070Spatrick for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1540*e5dd7070Spatrick auto &Arg = NewArgs[I + NumNonPlacementArgs]; 1541*e5dd7070Spatrick Cleanup->setPlacementArg( 1542*e5dd7070Spatrick I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty); 1543*e5dd7070Spatrick } 1544*e5dd7070Spatrick 1545*e5dd7070Spatrick CGF.initFullExprCleanup(); 1546*e5dd7070Spatrick } 1547*e5dd7070Spatrick 1548*e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { 1549*e5dd7070Spatrick // The element type being allocated. 1550*e5dd7070Spatrick QualType allocType = getContext().getBaseElementType(E->getAllocatedType()); 1551*e5dd7070Spatrick 1552*e5dd7070Spatrick // 1. Build a call to the allocation function. 1553*e5dd7070Spatrick FunctionDecl *allocator = E->getOperatorNew(); 1554*e5dd7070Spatrick 1555*e5dd7070Spatrick // If there is a brace-initializer, cannot allocate fewer elements than inits. 1556*e5dd7070Spatrick unsigned minElements = 0; 1557*e5dd7070Spatrick if (E->isArray() && E->hasInitializer()) { 1558*e5dd7070Spatrick const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()); 1559*e5dd7070Spatrick if (ILE && ILE->isStringLiteralInit()) 1560*e5dd7070Spatrick minElements = 1561*e5dd7070Spatrick cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 1562*e5dd7070Spatrick ->getSize().getZExtValue(); 1563*e5dd7070Spatrick else if (ILE) 1564*e5dd7070Spatrick minElements = ILE->getNumInits(); 1565*e5dd7070Spatrick } 1566*e5dd7070Spatrick 1567*e5dd7070Spatrick llvm::Value *numElements = nullptr; 1568*e5dd7070Spatrick llvm::Value *allocSizeWithoutCookie = nullptr; 1569*e5dd7070Spatrick llvm::Value *allocSize = 1570*e5dd7070Spatrick EmitCXXNewAllocSize(*this, E, minElements, numElements, 1571*e5dd7070Spatrick allocSizeWithoutCookie); 1572*e5dd7070Spatrick CharUnits allocAlign = getContext().getTypeAlignInChars(allocType); 1573*e5dd7070Spatrick 1574*e5dd7070Spatrick // Emit the allocation call. If the allocator is a global placement 1575*e5dd7070Spatrick // operator, just "inline" it directly. 1576*e5dd7070Spatrick Address allocation = Address::invalid(); 1577*e5dd7070Spatrick CallArgList allocatorArgs; 1578*e5dd7070Spatrick if (allocator->isReservedGlobalPlacementOperator()) { 1579*e5dd7070Spatrick assert(E->getNumPlacementArgs() == 1); 1580*e5dd7070Spatrick const Expr *arg = *E->placement_arguments().begin(); 1581*e5dd7070Spatrick 1582*e5dd7070Spatrick LValueBaseInfo BaseInfo; 1583*e5dd7070Spatrick allocation = EmitPointerWithAlignment(arg, &BaseInfo); 1584*e5dd7070Spatrick 1585*e5dd7070Spatrick // The pointer expression will, in many cases, be an opaque void*. 1586*e5dd7070Spatrick // In these cases, discard the computed alignment and use the 1587*e5dd7070Spatrick // formal alignment of the allocated type. 1588*e5dd7070Spatrick if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl) 1589*e5dd7070Spatrick allocation = Address(allocation.getPointer(), allocAlign); 1590*e5dd7070Spatrick 1591*e5dd7070Spatrick // Set up allocatorArgs for the call to operator delete if it's not 1592*e5dd7070Spatrick // the reserved global operator. 1593*e5dd7070Spatrick if (E->getOperatorDelete() && 1594*e5dd7070Spatrick !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 1595*e5dd7070Spatrick allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType()); 1596*e5dd7070Spatrick allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType()); 1597*e5dd7070Spatrick } 1598*e5dd7070Spatrick 1599*e5dd7070Spatrick } else { 1600*e5dd7070Spatrick const FunctionProtoType *allocatorType = 1601*e5dd7070Spatrick allocator->getType()->castAs<FunctionProtoType>(); 1602*e5dd7070Spatrick unsigned ParamsToSkip = 0; 1603*e5dd7070Spatrick 1604*e5dd7070Spatrick // The allocation size is the first argument. 1605*e5dd7070Spatrick QualType sizeType = getContext().getSizeType(); 1606*e5dd7070Spatrick allocatorArgs.add(RValue::get(allocSize), sizeType); 1607*e5dd7070Spatrick ++ParamsToSkip; 1608*e5dd7070Spatrick 1609*e5dd7070Spatrick if (allocSize != allocSizeWithoutCookie) { 1610*e5dd7070Spatrick CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI. 1611*e5dd7070Spatrick allocAlign = std::max(allocAlign, cookieAlign); 1612*e5dd7070Spatrick } 1613*e5dd7070Spatrick 1614*e5dd7070Spatrick // The allocation alignment may be passed as the second argument. 1615*e5dd7070Spatrick if (E->passAlignment()) { 1616*e5dd7070Spatrick QualType AlignValT = sizeType; 1617*e5dd7070Spatrick if (allocatorType->getNumParams() > 1) { 1618*e5dd7070Spatrick AlignValT = allocatorType->getParamType(1); 1619*e5dd7070Spatrick assert(getContext().hasSameUnqualifiedType( 1620*e5dd7070Spatrick AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(), 1621*e5dd7070Spatrick sizeType) && 1622*e5dd7070Spatrick "wrong type for alignment parameter"); 1623*e5dd7070Spatrick ++ParamsToSkip; 1624*e5dd7070Spatrick } else { 1625*e5dd7070Spatrick // Corner case, passing alignment to 'operator new(size_t, ...)'. 1626*e5dd7070Spatrick assert(allocator->isVariadic() && "can't pass alignment to allocator"); 1627*e5dd7070Spatrick } 1628*e5dd7070Spatrick allocatorArgs.add( 1629*e5dd7070Spatrick RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())), 1630*e5dd7070Spatrick AlignValT); 1631*e5dd7070Spatrick } 1632*e5dd7070Spatrick 1633*e5dd7070Spatrick // FIXME: Why do we not pass a CalleeDecl here? 1634*e5dd7070Spatrick EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(), 1635*e5dd7070Spatrick /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip); 1636*e5dd7070Spatrick 1637*e5dd7070Spatrick RValue RV = 1638*e5dd7070Spatrick EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs); 1639*e5dd7070Spatrick 1640*e5dd7070Spatrick // If this was a call to a global replaceable allocation function that does 1641*e5dd7070Spatrick // not take an alignment argument, the allocator is known to produce 1642*e5dd7070Spatrick // storage that's suitably aligned for any object that fits, up to a known 1643*e5dd7070Spatrick // threshold. Otherwise assume it's suitably aligned for the allocated type. 1644*e5dd7070Spatrick CharUnits allocationAlign = allocAlign; 1645*e5dd7070Spatrick if (!E->passAlignment() && 1646*e5dd7070Spatrick allocator->isReplaceableGlobalAllocationFunction()) { 1647*e5dd7070Spatrick unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>( 1648*e5dd7070Spatrick Target.getNewAlign(), getContext().getTypeSize(allocType))); 1649*e5dd7070Spatrick allocationAlign = std::max( 1650*e5dd7070Spatrick allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign)); 1651*e5dd7070Spatrick } 1652*e5dd7070Spatrick 1653*e5dd7070Spatrick allocation = Address(RV.getScalarVal(), allocationAlign); 1654*e5dd7070Spatrick } 1655*e5dd7070Spatrick 1656*e5dd7070Spatrick // Emit a null check on the allocation result if the allocation 1657*e5dd7070Spatrick // function is allowed to return null (because it has a non-throwing 1658*e5dd7070Spatrick // exception spec or is the reserved placement new) and we have an 1659*e5dd7070Spatrick // interesting initializer will be running sanitizers on the initialization. 1660*e5dd7070Spatrick bool nullCheck = E->shouldNullCheckAllocation() && 1661*e5dd7070Spatrick (!allocType.isPODType(getContext()) || E->hasInitializer() || 1662*e5dd7070Spatrick sanitizePerformTypeCheck()); 1663*e5dd7070Spatrick 1664*e5dd7070Spatrick llvm::BasicBlock *nullCheckBB = nullptr; 1665*e5dd7070Spatrick llvm::BasicBlock *contBB = nullptr; 1666*e5dd7070Spatrick 1667*e5dd7070Spatrick // The null-check means that the initializer is conditionally 1668*e5dd7070Spatrick // evaluated. 1669*e5dd7070Spatrick ConditionalEvaluation conditional(*this); 1670*e5dd7070Spatrick 1671*e5dd7070Spatrick if (nullCheck) { 1672*e5dd7070Spatrick conditional.begin(*this); 1673*e5dd7070Spatrick 1674*e5dd7070Spatrick nullCheckBB = Builder.GetInsertBlock(); 1675*e5dd7070Spatrick llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull"); 1676*e5dd7070Spatrick contBB = createBasicBlock("new.cont"); 1677*e5dd7070Spatrick 1678*e5dd7070Spatrick llvm::Value *isNull = 1679*e5dd7070Spatrick Builder.CreateIsNull(allocation.getPointer(), "new.isnull"); 1680*e5dd7070Spatrick Builder.CreateCondBr(isNull, contBB, notNullBB); 1681*e5dd7070Spatrick EmitBlock(notNullBB); 1682*e5dd7070Spatrick } 1683*e5dd7070Spatrick 1684*e5dd7070Spatrick // If there's an operator delete, enter a cleanup to call it if an 1685*e5dd7070Spatrick // exception is thrown. 1686*e5dd7070Spatrick EHScopeStack::stable_iterator operatorDeleteCleanup; 1687*e5dd7070Spatrick llvm::Instruction *cleanupDominator = nullptr; 1688*e5dd7070Spatrick if (E->getOperatorDelete() && 1689*e5dd7070Spatrick !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 1690*e5dd7070Spatrick EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign, 1691*e5dd7070Spatrick allocatorArgs); 1692*e5dd7070Spatrick operatorDeleteCleanup = EHStack.stable_begin(); 1693*e5dd7070Spatrick cleanupDominator = Builder.CreateUnreachable(); 1694*e5dd7070Spatrick } 1695*e5dd7070Spatrick 1696*e5dd7070Spatrick assert((allocSize == allocSizeWithoutCookie) == 1697*e5dd7070Spatrick CalculateCookiePadding(*this, E).isZero()); 1698*e5dd7070Spatrick if (allocSize != allocSizeWithoutCookie) { 1699*e5dd7070Spatrick assert(E->isArray()); 1700*e5dd7070Spatrick allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation, 1701*e5dd7070Spatrick numElements, 1702*e5dd7070Spatrick E, allocType); 1703*e5dd7070Spatrick } 1704*e5dd7070Spatrick 1705*e5dd7070Spatrick llvm::Type *elementTy = ConvertTypeForMem(allocType); 1706*e5dd7070Spatrick Address result = Builder.CreateElementBitCast(allocation, elementTy); 1707*e5dd7070Spatrick 1708*e5dd7070Spatrick // Passing pointer through launder.invariant.group to avoid propagation of 1709*e5dd7070Spatrick // vptrs information which may be included in previous type. 1710*e5dd7070Spatrick // To not break LTO with different optimizations levels, we do it regardless 1711*e5dd7070Spatrick // of optimization level. 1712*e5dd7070Spatrick if (CGM.getCodeGenOpts().StrictVTablePointers && 1713*e5dd7070Spatrick allocator->isReservedGlobalPlacementOperator()) 1714*e5dd7070Spatrick result = Address(Builder.CreateLaunderInvariantGroup(result.getPointer()), 1715*e5dd7070Spatrick result.getAlignment()); 1716*e5dd7070Spatrick 1717*e5dd7070Spatrick // Emit sanitizer checks for pointer value now, so that in the case of an 1718*e5dd7070Spatrick // array it was checked only once and not at each constructor call. We may 1719*e5dd7070Spatrick // have already checked that the pointer is non-null. 1720*e5dd7070Spatrick // FIXME: If we have an array cookie and a potentially-throwing allocator, 1721*e5dd7070Spatrick // we'll null check the wrong pointer here. 1722*e5dd7070Spatrick SanitizerSet SkippedChecks; 1723*e5dd7070Spatrick SkippedChecks.set(SanitizerKind::Null, nullCheck); 1724*e5dd7070Spatrick EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, 1725*e5dd7070Spatrick E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(), 1726*e5dd7070Spatrick result.getPointer(), allocType, result.getAlignment(), 1727*e5dd7070Spatrick SkippedChecks, numElements); 1728*e5dd7070Spatrick 1729*e5dd7070Spatrick EmitNewInitializer(*this, E, allocType, elementTy, result, numElements, 1730*e5dd7070Spatrick allocSizeWithoutCookie); 1731*e5dd7070Spatrick if (E->isArray()) { 1732*e5dd7070Spatrick // NewPtr is a pointer to the base element type. If we're 1733*e5dd7070Spatrick // allocating an array of arrays, we'll need to cast back to the 1734*e5dd7070Spatrick // array pointer type. 1735*e5dd7070Spatrick llvm::Type *resultType = ConvertTypeForMem(E->getType()); 1736*e5dd7070Spatrick if (result.getType() != resultType) 1737*e5dd7070Spatrick result = Builder.CreateBitCast(result, resultType); 1738*e5dd7070Spatrick } 1739*e5dd7070Spatrick 1740*e5dd7070Spatrick // Deactivate the 'operator delete' cleanup if we finished 1741*e5dd7070Spatrick // initialization. 1742*e5dd7070Spatrick if (operatorDeleteCleanup.isValid()) { 1743*e5dd7070Spatrick DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator); 1744*e5dd7070Spatrick cleanupDominator->eraseFromParent(); 1745*e5dd7070Spatrick } 1746*e5dd7070Spatrick 1747*e5dd7070Spatrick llvm::Value *resultPtr = result.getPointer(); 1748*e5dd7070Spatrick if (nullCheck) { 1749*e5dd7070Spatrick conditional.end(*this); 1750*e5dd7070Spatrick 1751*e5dd7070Spatrick llvm::BasicBlock *notNullBB = Builder.GetInsertBlock(); 1752*e5dd7070Spatrick EmitBlock(contBB); 1753*e5dd7070Spatrick 1754*e5dd7070Spatrick llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2); 1755*e5dd7070Spatrick PHI->addIncoming(resultPtr, notNullBB); 1756*e5dd7070Spatrick PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()), 1757*e5dd7070Spatrick nullCheckBB); 1758*e5dd7070Spatrick 1759*e5dd7070Spatrick resultPtr = PHI; 1760*e5dd7070Spatrick } 1761*e5dd7070Spatrick 1762*e5dd7070Spatrick return resultPtr; 1763*e5dd7070Spatrick } 1764*e5dd7070Spatrick 1765*e5dd7070Spatrick void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD, 1766*e5dd7070Spatrick llvm::Value *Ptr, QualType DeleteTy, 1767*e5dd7070Spatrick llvm::Value *NumElements, 1768*e5dd7070Spatrick CharUnits CookieSize) { 1769*e5dd7070Spatrick assert((!NumElements && CookieSize.isZero()) || 1770*e5dd7070Spatrick DeleteFD->getOverloadedOperator() == OO_Array_Delete); 1771*e5dd7070Spatrick 1772*e5dd7070Spatrick const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>(); 1773*e5dd7070Spatrick CallArgList DeleteArgs; 1774*e5dd7070Spatrick 1775*e5dd7070Spatrick auto Params = getUsualDeleteParams(DeleteFD); 1776*e5dd7070Spatrick auto ParamTypeIt = DeleteFTy->param_type_begin(); 1777*e5dd7070Spatrick 1778*e5dd7070Spatrick // Pass the pointer itself. 1779*e5dd7070Spatrick QualType ArgTy = *ParamTypeIt++; 1780*e5dd7070Spatrick llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy)); 1781*e5dd7070Spatrick DeleteArgs.add(RValue::get(DeletePtr), ArgTy); 1782*e5dd7070Spatrick 1783*e5dd7070Spatrick // Pass the std::destroying_delete tag if present. 1784*e5dd7070Spatrick if (Params.DestroyingDelete) { 1785*e5dd7070Spatrick QualType DDTag = *ParamTypeIt++; 1786*e5dd7070Spatrick // Just pass an 'undef'. We expect the tag type to be an empty struct. 1787*e5dd7070Spatrick auto *V = llvm::UndefValue::get(getTypes().ConvertType(DDTag)); 1788*e5dd7070Spatrick DeleteArgs.add(RValue::get(V), DDTag); 1789*e5dd7070Spatrick } 1790*e5dd7070Spatrick 1791*e5dd7070Spatrick // Pass the size if the delete function has a size_t parameter. 1792*e5dd7070Spatrick if (Params.Size) { 1793*e5dd7070Spatrick QualType SizeType = *ParamTypeIt++; 1794*e5dd7070Spatrick CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy); 1795*e5dd7070Spatrick llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType), 1796*e5dd7070Spatrick DeleteTypeSize.getQuantity()); 1797*e5dd7070Spatrick 1798*e5dd7070Spatrick // For array new, multiply by the number of elements. 1799*e5dd7070Spatrick if (NumElements) 1800*e5dd7070Spatrick Size = Builder.CreateMul(Size, NumElements); 1801*e5dd7070Spatrick 1802*e5dd7070Spatrick // If there is a cookie, add the cookie size. 1803*e5dd7070Spatrick if (!CookieSize.isZero()) 1804*e5dd7070Spatrick Size = Builder.CreateAdd( 1805*e5dd7070Spatrick Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity())); 1806*e5dd7070Spatrick 1807*e5dd7070Spatrick DeleteArgs.add(RValue::get(Size), SizeType); 1808*e5dd7070Spatrick } 1809*e5dd7070Spatrick 1810*e5dd7070Spatrick // Pass the alignment if the delete function has an align_val_t parameter. 1811*e5dd7070Spatrick if (Params.Alignment) { 1812*e5dd7070Spatrick QualType AlignValType = *ParamTypeIt++; 1813*e5dd7070Spatrick CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits( 1814*e5dd7070Spatrick getContext().getTypeAlignIfKnown(DeleteTy)); 1815*e5dd7070Spatrick llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType), 1816*e5dd7070Spatrick DeleteTypeAlign.getQuantity()); 1817*e5dd7070Spatrick DeleteArgs.add(RValue::get(Align), AlignValType); 1818*e5dd7070Spatrick } 1819*e5dd7070Spatrick 1820*e5dd7070Spatrick assert(ParamTypeIt == DeleteFTy->param_type_end() && 1821*e5dd7070Spatrick "unknown parameter to usual delete function"); 1822*e5dd7070Spatrick 1823*e5dd7070Spatrick // Emit the call to delete. 1824*e5dd7070Spatrick EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs); 1825*e5dd7070Spatrick } 1826*e5dd7070Spatrick 1827*e5dd7070Spatrick namespace { 1828*e5dd7070Spatrick /// Calls the given 'operator delete' on a single object. 1829*e5dd7070Spatrick struct CallObjectDelete final : EHScopeStack::Cleanup { 1830*e5dd7070Spatrick llvm::Value *Ptr; 1831*e5dd7070Spatrick const FunctionDecl *OperatorDelete; 1832*e5dd7070Spatrick QualType ElementType; 1833*e5dd7070Spatrick 1834*e5dd7070Spatrick CallObjectDelete(llvm::Value *Ptr, 1835*e5dd7070Spatrick const FunctionDecl *OperatorDelete, 1836*e5dd7070Spatrick QualType ElementType) 1837*e5dd7070Spatrick : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {} 1838*e5dd7070Spatrick 1839*e5dd7070Spatrick void Emit(CodeGenFunction &CGF, Flags flags) override { 1840*e5dd7070Spatrick CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType); 1841*e5dd7070Spatrick } 1842*e5dd7070Spatrick }; 1843*e5dd7070Spatrick } 1844*e5dd7070Spatrick 1845*e5dd7070Spatrick void 1846*e5dd7070Spatrick CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 1847*e5dd7070Spatrick llvm::Value *CompletePtr, 1848*e5dd7070Spatrick QualType ElementType) { 1849*e5dd7070Spatrick EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr, 1850*e5dd7070Spatrick OperatorDelete, ElementType); 1851*e5dd7070Spatrick } 1852*e5dd7070Spatrick 1853*e5dd7070Spatrick /// Emit the code for deleting a single object with a destroying operator 1854*e5dd7070Spatrick /// delete. If the element type has a non-virtual destructor, Ptr has already 1855*e5dd7070Spatrick /// been converted to the type of the parameter of 'operator delete'. Otherwise 1856*e5dd7070Spatrick /// Ptr points to an object of the static type. 1857*e5dd7070Spatrick static void EmitDestroyingObjectDelete(CodeGenFunction &CGF, 1858*e5dd7070Spatrick const CXXDeleteExpr *DE, Address Ptr, 1859*e5dd7070Spatrick QualType ElementType) { 1860*e5dd7070Spatrick auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor(); 1861*e5dd7070Spatrick if (Dtor && Dtor->isVirtual()) 1862*e5dd7070Spatrick CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType, 1863*e5dd7070Spatrick Dtor); 1864*e5dd7070Spatrick else 1865*e5dd7070Spatrick CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType); 1866*e5dd7070Spatrick } 1867*e5dd7070Spatrick 1868*e5dd7070Spatrick /// Emit the code for deleting a single object. 1869*e5dd7070Spatrick static void EmitObjectDelete(CodeGenFunction &CGF, 1870*e5dd7070Spatrick const CXXDeleteExpr *DE, 1871*e5dd7070Spatrick Address Ptr, 1872*e5dd7070Spatrick QualType ElementType) { 1873*e5dd7070Spatrick // C++11 [expr.delete]p3: 1874*e5dd7070Spatrick // If the static type of the object to be deleted is different from its 1875*e5dd7070Spatrick // dynamic type, the static type shall be a base class of the dynamic type 1876*e5dd7070Spatrick // of the object to be deleted and the static type shall have a virtual 1877*e5dd7070Spatrick // destructor or the behavior is undefined. 1878*e5dd7070Spatrick CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall, 1879*e5dd7070Spatrick DE->getExprLoc(), Ptr.getPointer(), 1880*e5dd7070Spatrick ElementType); 1881*e5dd7070Spatrick 1882*e5dd7070Spatrick const FunctionDecl *OperatorDelete = DE->getOperatorDelete(); 1883*e5dd7070Spatrick assert(!OperatorDelete->isDestroyingOperatorDelete()); 1884*e5dd7070Spatrick 1885*e5dd7070Spatrick // Find the destructor for the type, if applicable. If the 1886*e5dd7070Spatrick // destructor is virtual, we'll just emit the vcall and return. 1887*e5dd7070Spatrick const CXXDestructorDecl *Dtor = nullptr; 1888*e5dd7070Spatrick if (const RecordType *RT = ElementType->getAs<RecordType>()) { 1889*e5dd7070Spatrick CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1890*e5dd7070Spatrick if (RD->hasDefinition() && !RD->hasTrivialDestructor()) { 1891*e5dd7070Spatrick Dtor = RD->getDestructor(); 1892*e5dd7070Spatrick 1893*e5dd7070Spatrick if (Dtor->isVirtual()) { 1894*e5dd7070Spatrick bool UseVirtualCall = true; 1895*e5dd7070Spatrick const Expr *Base = DE->getArgument(); 1896*e5dd7070Spatrick if (auto *DevirtualizedDtor = 1897*e5dd7070Spatrick dyn_cast_or_null<const CXXDestructorDecl>( 1898*e5dd7070Spatrick Dtor->getDevirtualizedMethod( 1899*e5dd7070Spatrick Base, CGF.CGM.getLangOpts().AppleKext))) { 1900*e5dd7070Spatrick UseVirtualCall = false; 1901*e5dd7070Spatrick const CXXRecordDecl *DevirtualizedClass = 1902*e5dd7070Spatrick DevirtualizedDtor->getParent(); 1903*e5dd7070Spatrick if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) { 1904*e5dd7070Spatrick // Devirtualized to the class of the base type (the type of the 1905*e5dd7070Spatrick // whole expression). 1906*e5dd7070Spatrick Dtor = DevirtualizedDtor; 1907*e5dd7070Spatrick } else { 1908*e5dd7070Spatrick // Devirtualized to some other type. Would need to cast the this 1909*e5dd7070Spatrick // pointer to that type but we don't have support for that yet, so 1910*e5dd7070Spatrick // do a virtual call. FIXME: handle the case where it is 1911*e5dd7070Spatrick // devirtualized to the derived type (the type of the inner 1912*e5dd7070Spatrick // expression) as in EmitCXXMemberOrOperatorMemberCallExpr. 1913*e5dd7070Spatrick UseVirtualCall = true; 1914*e5dd7070Spatrick } 1915*e5dd7070Spatrick } 1916*e5dd7070Spatrick if (UseVirtualCall) { 1917*e5dd7070Spatrick CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType, 1918*e5dd7070Spatrick Dtor); 1919*e5dd7070Spatrick return; 1920*e5dd7070Spatrick } 1921*e5dd7070Spatrick } 1922*e5dd7070Spatrick } 1923*e5dd7070Spatrick } 1924*e5dd7070Spatrick 1925*e5dd7070Spatrick // Make sure that we call delete even if the dtor throws. 1926*e5dd7070Spatrick // This doesn't have to a conditional cleanup because we're going 1927*e5dd7070Spatrick // to pop it off in a second. 1928*e5dd7070Spatrick CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, 1929*e5dd7070Spatrick Ptr.getPointer(), 1930*e5dd7070Spatrick OperatorDelete, ElementType); 1931*e5dd7070Spatrick 1932*e5dd7070Spatrick if (Dtor) 1933*e5dd7070Spatrick CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 1934*e5dd7070Spatrick /*ForVirtualBase=*/false, 1935*e5dd7070Spatrick /*Delegating=*/false, 1936*e5dd7070Spatrick Ptr, ElementType); 1937*e5dd7070Spatrick else if (auto Lifetime = ElementType.getObjCLifetime()) { 1938*e5dd7070Spatrick switch (Lifetime) { 1939*e5dd7070Spatrick case Qualifiers::OCL_None: 1940*e5dd7070Spatrick case Qualifiers::OCL_ExplicitNone: 1941*e5dd7070Spatrick case Qualifiers::OCL_Autoreleasing: 1942*e5dd7070Spatrick break; 1943*e5dd7070Spatrick 1944*e5dd7070Spatrick case Qualifiers::OCL_Strong: 1945*e5dd7070Spatrick CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime); 1946*e5dd7070Spatrick break; 1947*e5dd7070Spatrick 1948*e5dd7070Spatrick case Qualifiers::OCL_Weak: 1949*e5dd7070Spatrick CGF.EmitARCDestroyWeak(Ptr); 1950*e5dd7070Spatrick break; 1951*e5dd7070Spatrick } 1952*e5dd7070Spatrick } 1953*e5dd7070Spatrick 1954*e5dd7070Spatrick CGF.PopCleanupBlock(); 1955*e5dd7070Spatrick } 1956*e5dd7070Spatrick 1957*e5dd7070Spatrick namespace { 1958*e5dd7070Spatrick /// Calls the given 'operator delete' on an array of objects. 1959*e5dd7070Spatrick struct CallArrayDelete final : EHScopeStack::Cleanup { 1960*e5dd7070Spatrick llvm::Value *Ptr; 1961*e5dd7070Spatrick const FunctionDecl *OperatorDelete; 1962*e5dd7070Spatrick llvm::Value *NumElements; 1963*e5dd7070Spatrick QualType ElementType; 1964*e5dd7070Spatrick CharUnits CookieSize; 1965*e5dd7070Spatrick 1966*e5dd7070Spatrick CallArrayDelete(llvm::Value *Ptr, 1967*e5dd7070Spatrick const FunctionDecl *OperatorDelete, 1968*e5dd7070Spatrick llvm::Value *NumElements, 1969*e5dd7070Spatrick QualType ElementType, 1970*e5dd7070Spatrick CharUnits CookieSize) 1971*e5dd7070Spatrick : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements), 1972*e5dd7070Spatrick ElementType(ElementType), CookieSize(CookieSize) {} 1973*e5dd7070Spatrick 1974*e5dd7070Spatrick void Emit(CodeGenFunction &CGF, Flags flags) override { 1975*e5dd7070Spatrick CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements, 1976*e5dd7070Spatrick CookieSize); 1977*e5dd7070Spatrick } 1978*e5dd7070Spatrick }; 1979*e5dd7070Spatrick } 1980*e5dd7070Spatrick 1981*e5dd7070Spatrick /// Emit the code for deleting an array of objects. 1982*e5dd7070Spatrick static void EmitArrayDelete(CodeGenFunction &CGF, 1983*e5dd7070Spatrick const CXXDeleteExpr *E, 1984*e5dd7070Spatrick Address deletedPtr, 1985*e5dd7070Spatrick QualType elementType) { 1986*e5dd7070Spatrick llvm::Value *numElements = nullptr; 1987*e5dd7070Spatrick llvm::Value *allocatedPtr = nullptr; 1988*e5dd7070Spatrick CharUnits cookieSize; 1989*e5dd7070Spatrick CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType, 1990*e5dd7070Spatrick numElements, allocatedPtr, cookieSize); 1991*e5dd7070Spatrick 1992*e5dd7070Spatrick assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer"); 1993*e5dd7070Spatrick 1994*e5dd7070Spatrick // Make sure that we call delete even if one of the dtors throws. 1995*e5dd7070Spatrick const FunctionDecl *operatorDelete = E->getOperatorDelete(); 1996*e5dd7070Spatrick CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup, 1997*e5dd7070Spatrick allocatedPtr, operatorDelete, 1998*e5dd7070Spatrick numElements, elementType, 1999*e5dd7070Spatrick cookieSize); 2000*e5dd7070Spatrick 2001*e5dd7070Spatrick // Destroy the elements. 2002*e5dd7070Spatrick if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) { 2003*e5dd7070Spatrick assert(numElements && "no element count for a type with a destructor!"); 2004*e5dd7070Spatrick 2005*e5dd7070Spatrick CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType); 2006*e5dd7070Spatrick CharUnits elementAlign = 2007*e5dd7070Spatrick deletedPtr.getAlignment().alignmentOfArrayElement(elementSize); 2008*e5dd7070Spatrick 2009*e5dd7070Spatrick llvm::Value *arrayBegin = deletedPtr.getPointer(); 2010*e5dd7070Spatrick llvm::Value *arrayEnd = 2011*e5dd7070Spatrick CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end"); 2012*e5dd7070Spatrick 2013*e5dd7070Spatrick // Note that it is legal to allocate a zero-length array, and we 2014*e5dd7070Spatrick // can never fold the check away because the length should always 2015*e5dd7070Spatrick // come from a cookie. 2016*e5dd7070Spatrick CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign, 2017*e5dd7070Spatrick CGF.getDestroyer(dtorKind), 2018*e5dd7070Spatrick /*checkZeroLength*/ true, 2019*e5dd7070Spatrick CGF.needsEHCleanup(dtorKind)); 2020*e5dd7070Spatrick } 2021*e5dd7070Spatrick 2022*e5dd7070Spatrick // Pop the cleanup block. 2023*e5dd7070Spatrick CGF.PopCleanupBlock(); 2024*e5dd7070Spatrick } 2025*e5dd7070Spatrick 2026*e5dd7070Spatrick void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) { 2027*e5dd7070Spatrick const Expr *Arg = E->getArgument(); 2028*e5dd7070Spatrick Address Ptr = EmitPointerWithAlignment(Arg); 2029*e5dd7070Spatrick 2030*e5dd7070Spatrick // Null check the pointer. 2031*e5dd7070Spatrick llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull"); 2032*e5dd7070Spatrick llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end"); 2033*e5dd7070Spatrick 2034*e5dd7070Spatrick llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull"); 2035*e5dd7070Spatrick 2036*e5dd7070Spatrick Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull); 2037*e5dd7070Spatrick EmitBlock(DeleteNotNull); 2038*e5dd7070Spatrick 2039*e5dd7070Spatrick QualType DeleteTy = E->getDestroyedType(); 2040*e5dd7070Spatrick 2041*e5dd7070Spatrick // A destroying operator delete overrides the entire operation of the 2042*e5dd7070Spatrick // delete expression. 2043*e5dd7070Spatrick if (E->getOperatorDelete()->isDestroyingOperatorDelete()) { 2044*e5dd7070Spatrick EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy); 2045*e5dd7070Spatrick EmitBlock(DeleteEnd); 2046*e5dd7070Spatrick return; 2047*e5dd7070Spatrick } 2048*e5dd7070Spatrick 2049*e5dd7070Spatrick // We might be deleting a pointer to array. If so, GEP down to the 2050*e5dd7070Spatrick // first non-array element. 2051*e5dd7070Spatrick // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*) 2052*e5dd7070Spatrick if (DeleteTy->isConstantArrayType()) { 2053*e5dd7070Spatrick llvm::Value *Zero = Builder.getInt32(0); 2054*e5dd7070Spatrick SmallVector<llvm::Value*,8> GEP; 2055*e5dd7070Spatrick 2056*e5dd7070Spatrick GEP.push_back(Zero); // point at the outermost array 2057*e5dd7070Spatrick 2058*e5dd7070Spatrick // For each layer of array type we're pointing at: 2059*e5dd7070Spatrick while (const ConstantArrayType *Arr 2060*e5dd7070Spatrick = getContext().getAsConstantArrayType(DeleteTy)) { 2061*e5dd7070Spatrick // 1. Unpeel the array type. 2062*e5dd7070Spatrick DeleteTy = Arr->getElementType(); 2063*e5dd7070Spatrick 2064*e5dd7070Spatrick // 2. GEP to the first element of the array. 2065*e5dd7070Spatrick GEP.push_back(Zero); 2066*e5dd7070Spatrick } 2067*e5dd7070Spatrick 2068*e5dd7070Spatrick Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"), 2069*e5dd7070Spatrick Ptr.getAlignment()); 2070*e5dd7070Spatrick } 2071*e5dd7070Spatrick 2072*e5dd7070Spatrick assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType()); 2073*e5dd7070Spatrick 2074*e5dd7070Spatrick if (E->isArrayForm()) { 2075*e5dd7070Spatrick EmitArrayDelete(*this, E, Ptr, DeleteTy); 2076*e5dd7070Spatrick } else { 2077*e5dd7070Spatrick EmitObjectDelete(*this, E, Ptr, DeleteTy); 2078*e5dd7070Spatrick } 2079*e5dd7070Spatrick 2080*e5dd7070Spatrick EmitBlock(DeleteEnd); 2081*e5dd7070Spatrick } 2082*e5dd7070Spatrick 2083*e5dd7070Spatrick static bool isGLValueFromPointerDeref(const Expr *E) { 2084*e5dd7070Spatrick E = E->IgnoreParens(); 2085*e5dd7070Spatrick 2086*e5dd7070Spatrick if (const auto *CE = dyn_cast<CastExpr>(E)) { 2087*e5dd7070Spatrick if (!CE->getSubExpr()->isGLValue()) 2088*e5dd7070Spatrick return false; 2089*e5dd7070Spatrick return isGLValueFromPointerDeref(CE->getSubExpr()); 2090*e5dd7070Spatrick } 2091*e5dd7070Spatrick 2092*e5dd7070Spatrick if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 2093*e5dd7070Spatrick return isGLValueFromPointerDeref(OVE->getSourceExpr()); 2094*e5dd7070Spatrick 2095*e5dd7070Spatrick if (const auto *BO = dyn_cast<BinaryOperator>(E)) 2096*e5dd7070Spatrick if (BO->getOpcode() == BO_Comma) 2097*e5dd7070Spatrick return isGLValueFromPointerDeref(BO->getRHS()); 2098*e5dd7070Spatrick 2099*e5dd7070Spatrick if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E)) 2100*e5dd7070Spatrick return isGLValueFromPointerDeref(ACO->getTrueExpr()) || 2101*e5dd7070Spatrick isGLValueFromPointerDeref(ACO->getFalseExpr()); 2102*e5dd7070Spatrick 2103*e5dd7070Spatrick // C++11 [expr.sub]p1: 2104*e5dd7070Spatrick // The expression E1[E2] is identical (by definition) to *((E1)+(E2)) 2105*e5dd7070Spatrick if (isa<ArraySubscriptExpr>(E)) 2106*e5dd7070Spatrick return true; 2107*e5dd7070Spatrick 2108*e5dd7070Spatrick if (const auto *UO = dyn_cast<UnaryOperator>(E)) 2109*e5dd7070Spatrick if (UO->getOpcode() == UO_Deref) 2110*e5dd7070Spatrick return true; 2111*e5dd7070Spatrick 2112*e5dd7070Spatrick return false; 2113*e5dd7070Spatrick } 2114*e5dd7070Spatrick 2115*e5dd7070Spatrick static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E, 2116*e5dd7070Spatrick llvm::Type *StdTypeInfoPtrTy) { 2117*e5dd7070Spatrick // Get the vtable pointer. 2118*e5dd7070Spatrick Address ThisPtr = CGF.EmitLValue(E).getAddress(CGF); 2119*e5dd7070Spatrick 2120*e5dd7070Spatrick QualType SrcRecordTy = E->getType(); 2121*e5dd7070Spatrick 2122*e5dd7070Spatrick // C++ [class.cdtor]p4: 2123*e5dd7070Spatrick // If the operand of typeid refers to the object under construction or 2124*e5dd7070Spatrick // destruction and the static type of the operand is neither the constructor 2125*e5dd7070Spatrick // or destructor’s class nor one of its bases, the behavior is undefined. 2126*e5dd7070Spatrick CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(), 2127*e5dd7070Spatrick ThisPtr.getPointer(), SrcRecordTy); 2128*e5dd7070Spatrick 2129*e5dd7070Spatrick // C++ [expr.typeid]p2: 2130*e5dd7070Spatrick // If the glvalue expression is obtained by applying the unary * operator to 2131*e5dd7070Spatrick // a pointer and the pointer is a null pointer value, the typeid expression 2132*e5dd7070Spatrick // throws the std::bad_typeid exception. 2133*e5dd7070Spatrick // 2134*e5dd7070Spatrick // However, this paragraph's intent is not clear. We choose a very generous 2135*e5dd7070Spatrick // interpretation which implores us to consider comma operators, conditional 2136*e5dd7070Spatrick // operators, parentheses and other such constructs. 2137*e5dd7070Spatrick if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked( 2138*e5dd7070Spatrick isGLValueFromPointerDeref(E), SrcRecordTy)) { 2139*e5dd7070Spatrick llvm::BasicBlock *BadTypeidBlock = 2140*e5dd7070Spatrick CGF.createBasicBlock("typeid.bad_typeid"); 2141*e5dd7070Spatrick llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end"); 2142*e5dd7070Spatrick 2143*e5dd7070Spatrick llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer()); 2144*e5dd7070Spatrick CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock); 2145*e5dd7070Spatrick 2146*e5dd7070Spatrick CGF.EmitBlock(BadTypeidBlock); 2147*e5dd7070Spatrick CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF); 2148*e5dd7070Spatrick CGF.EmitBlock(EndBlock); 2149*e5dd7070Spatrick } 2150*e5dd7070Spatrick 2151*e5dd7070Spatrick return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr, 2152*e5dd7070Spatrick StdTypeInfoPtrTy); 2153*e5dd7070Spatrick } 2154*e5dd7070Spatrick 2155*e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { 2156*e5dd7070Spatrick llvm::Type *StdTypeInfoPtrTy = 2157*e5dd7070Spatrick ConvertType(E->getType())->getPointerTo(); 2158*e5dd7070Spatrick 2159*e5dd7070Spatrick if (E->isTypeOperand()) { 2160*e5dd7070Spatrick llvm::Constant *TypeInfo = 2161*e5dd7070Spatrick CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext())); 2162*e5dd7070Spatrick return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy); 2163*e5dd7070Spatrick } 2164*e5dd7070Spatrick 2165*e5dd7070Spatrick // C++ [expr.typeid]p2: 2166*e5dd7070Spatrick // When typeid is applied to a glvalue expression whose type is a 2167*e5dd7070Spatrick // polymorphic class type, the result refers to a std::type_info object 2168*e5dd7070Spatrick // representing the type of the most derived object (that is, the dynamic 2169*e5dd7070Spatrick // type) to which the glvalue refers. 2170*e5dd7070Spatrick if (E->isPotentiallyEvaluated()) 2171*e5dd7070Spatrick return EmitTypeidFromVTable(*this, E->getExprOperand(), 2172*e5dd7070Spatrick StdTypeInfoPtrTy); 2173*e5dd7070Spatrick 2174*e5dd7070Spatrick QualType OperandTy = E->getExprOperand()->getType(); 2175*e5dd7070Spatrick return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy), 2176*e5dd7070Spatrick StdTypeInfoPtrTy); 2177*e5dd7070Spatrick } 2178*e5dd7070Spatrick 2179*e5dd7070Spatrick static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF, 2180*e5dd7070Spatrick QualType DestTy) { 2181*e5dd7070Spatrick llvm::Type *DestLTy = CGF.ConvertType(DestTy); 2182*e5dd7070Spatrick if (DestTy->isPointerType()) 2183*e5dd7070Spatrick return llvm::Constant::getNullValue(DestLTy); 2184*e5dd7070Spatrick 2185*e5dd7070Spatrick /// C++ [expr.dynamic.cast]p9: 2186*e5dd7070Spatrick /// A failed cast to reference type throws std::bad_cast 2187*e5dd7070Spatrick if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF)) 2188*e5dd7070Spatrick return nullptr; 2189*e5dd7070Spatrick 2190*e5dd7070Spatrick CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end")); 2191*e5dd7070Spatrick return llvm::UndefValue::get(DestLTy); 2192*e5dd7070Spatrick } 2193*e5dd7070Spatrick 2194*e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr, 2195*e5dd7070Spatrick const CXXDynamicCastExpr *DCE) { 2196*e5dd7070Spatrick CGM.EmitExplicitCastExprType(DCE, this); 2197*e5dd7070Spatrick QualType DestTy = DCE->getTypeAsWritten(); 2198*e5dd7070Spatrick 2199*e5dd7070Spatrick QualType SrcTy = DCE->getSubExpr()->getType(); 2200*e5dd7070Spatrick 2201*e5dd7070Spatrick // C++ [expr.dynamic.cast]p7: 2202*e5dd7070Spatrick // If T is "pointer to cv void," then the result is a pointer to the most 2203*e5dd7070Spatrick // derived object pointed to by v. 2204*e5dd7070Spatrick const PointerType *DestPTy = DestTy->getAs<PointerType>(); 2205*e5dd7070Spatrick 2206*e5dd7070Spatrick bool isDynamicCastToVoid; 2207*e5dd7070Spatrick QualType SrcRecordTy; 2208*e5dd7070Spatrick QualType DestRecordTy; 2209*e5dd7070Spatrick if (DestPTy) { 2210*e5dd7070Spatrick isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType(); 2211*e5dd7070Spatrick SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType(); 2212*e5dd7070Spatrick DestRecordTy = DestPTy->getPointeeType(); 2213*e5dd7070Spatrick } else { 2214*e5dd7070Spatrick isDynamicCastToVoid = false; 2215*e5dd7070Spatrick SrcRecordTy = SrcTy; 2216*e5dd7070Spatrick DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType(); 2217*e5dd7070Spatrick } 2218*e5dd7070Spatrick 2219*e5dd7070Spatrick // C++ [class.cdtor]p5: 2220*e5dd7070Spatrick // If the operand of the dynamic_cast refers to the object under 2221*e5dd7070Spatrick // construction or destruction and the static type of the operand is not a 2222*e5dd7070Spatrick // pointer to or object of the constructor or destructor’s own class or one 2223*e5dd7070Spatrick // of its bases, the dynamic_cast results in undefined behavior. 2224*e5dd7070Spatrick EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(), 2225*e5dd7070Spatrick SrcRecordTy); 2226*e5dd7070Spatrick 2227*e5dd7070Spatrick if (DCE->isAlwaysNull()) 2228*e5dd7070Spatrick if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy)) 2229*e5dd7070Spatrick return T; 2230*e5dd7070Spatrick 2231*e5dd7070Spatrick assert(SrcRecordTy->isRecordType() && "source type must be a record type!"); 2232*e5dd7070Spatrick 2233*e5dd7070Spatrick // C++ [expr.dynamic.cast]p4: 2234*e5dd7070Spatrick // If the value of v is a null pointer value in the pointer case, the result 2235*e5dd7070Spatrick // is the null pointer value of type T. 2236*e5dd7070Spatrick bool ShouldNullCheckSrcValue = 2237*e5dd7070Spatrick CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(), 2238*e5dd7070Spatrick SrcRecordTy); 2239*e5dd7070Spatrick 2240*e5dd7070Spatrick llvm::BasicBlock *CastNull = nullptr; 2241*e5dd7070Spatrick llvm::BasicBlock *CastNotNull = nullptr; 2242*e5dd7070Spatrick llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end"); 2243*e5dd7070Spatrick 2244*e5dd7070Spatrick if (ShouldNullCheckSrcValue) { 2245*e5dd7070Spatrick CastNull = createBasicBlock("dynamic_cast.null"); 2246*e5dd7070Spatrick CastNotNull = createBasicBlock("dynamic_cast.notnull"); 2247*e5dd7070Spatrick 2248*e5dd7070Spatrick llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer()); 2249*e5dd7070Spatrick Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 2250*e5dd7070Spatrick EmitBlock(CastNotNull); 2251*e5dd7070Spatrick } 2252*e5dd7070Spatrick 2253*e5dd7070Spatrick llvm::Value *Value; 2254*e5dd7070Spatrick if (isDynamicCastToVoid) { 2255*e5dd7070Spatrick Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy, 2256*e5dd7070Spatrick DestTy); 2257*e5dd7070Spatrick } else { 2258*e5dd7070Spatrick assert(DestRecordTy->isRecordType() && 2259*e5dd7070Spatrick "destination type must be a record type!"); 2260*e5dd7070Spatrick Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy, 2261*e5dd7070Spatrick DestTy, DestRecordTy, CastEnd); 2262*e5dd7070Spatrick CastNotNull = Builder.GetInsertBlock(); 2263*e5dd7070Spatrick } 2264*e5dd7070Spatrick 2265*e5dd7070Spatrick if (ShouldNullCheckSrcValue) { 2266*e5dd7070Spatrick EmitBranch(CastEnd); 2267*e5dd7070Spatrick 2268*e5dd7070Spatrick EmitBlock(CastNull); 2269*e5dd7070Spatrick EmitBranch(CastEnd); 2270*e5dd7070Spatrick } 2271*e5dd7070Spatrick 2272*e5dd7070Spatrick EmitBlock(CastEnd); 2273*e5dd7070Spatrick 2274*e5dd7070Spatrick if (ShouldNullCheckSrcValue) { 2275*e5dd7070Spatrick llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 2276*e5dd7070Spatrick PHI->addIncoming(Value, CastNotNull); 2277*e5dd7070Spatrick PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull); 2278*e5dd7070Spatrick 2279*e5dd7070Spatrick Value = PHI; 2280*e5dd7070Spatrick } 2281*e5dd7070Spatrick 2282*e5dd7070Spatrick return Value; 2283*e5dd7070Spatrick } 2284