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