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