1 //===- CallEvent.cpp - Wrapper for all function and method calls ----------===// 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 /// \file This file defines CallEvent and its subclasses, which represent path- 11 /// sensitive instances of different kinds of function and method calls 12 /// (C, C++, and Objective-C). 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclBase.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ParentMap.h" 26 #include "clang/AST/Stmt.h" 27 #include "clang/AST/Type.h" 28 #include "clang/Analysis/AnalysisDeclContext.h" 29 #include "clang/Analysis/CFG.h" 30 #include "clang/Analysis/ProgramPoint.h" 31 #include "clang/CrossTU/CrossTranslationUnit.h" 32 #include "clang/Basic/IdentifierTable.h" 33 #include "clang/Basic/LLVM.h" 34 #include "clang/Basic/SourceLocation.h" 35 #include "clang/Basic/SourceManager.h" 36 #include "clang/Basic/Specifiers.h" 37 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 38 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 39 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h" 40 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h" 41 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" 42 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 43 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" 44 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" 45 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" 46 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h" 47 #include "llvm/ADT/ArrayRef.h" 48 #include "llvm/ADT/DenseMap.h" 49 #include "llvm/ADT/None.h" 50 #include "llvm/ADT/Optional.h" 51 #include "llvm/ADT/PointerIntPair.h" 52 #include "llvm/ADT/SmallSet.h" 53 #include "llvm/ADT/SmallVector.h" 54 #include "llvm/ADT/StringExtras.h" 55 #include "llvm/ADT/StringRef.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/Compiler.h" 58 #include "llvm/Support/Debug.h" 59 #include "llvm/Support/ErrorHandling.h" 60 #include "llvm/Support/raw_ostream.h" 61 #include <cassert> 62 #include <utility> 63 64 #define DEBUG_TYPE "static-analyzer-call-event" 65 66 using namespace clang; 67 using namespace ento; 68 69 QualType CallEvent::getResultType() const { 70 ASTContext &Ctx = getState()->getStateManager().getContext(); 71 const Expr *E = getOriginExpr(); 72 if (!E) 73 return Ctx.VoidTy; 74 assert(E); 75 76 QualType ResultTy = E->getType(); 77 78 // A function that returns a reference to 'int' will have a result type 79 // of simply 'int'. Check the origin expr's value kind to recover the 80 // proper type. 81 switch (E->getValueKind()) { 82 case VK_LValue: 83 ResultTy = Ctx.getLValueReferenceType(ResultTy); 84 break; 85 case VK_XValue: 86 ResultTy = Ctx.getRValueReferenceType(ResultTy); 87 break; 88 case VK_RValue: 89 // No adjustment is necessary. 90 break; 91 } 92 93 return ResultTy; 94 } 95 96 static bool isCallback(QualType T) { 97 // If a parameter is a block or a callback, assume it can modify pointer. 98 if (T->isBlockPointerType() || 99 T->isFunctionPointerType() || 100 T->isObjCSelType()) 101 return true; 102 103 // Check if a callback is passed inside a struct (for both, struct passed by 104 // reference and by value). Dig just one level into the struct for now. 105 106 if (T->isAnyPointerType() || T->isReferenceType()) 107 T = T->getPointeeType(); 108 109 if (const RecordType *RT = T->getAsStructureType()) { 110 const RecordDecl *RD = RT->getDecl(); 111 for (const auto *I : RD->fields()) { 112 QualType FieldT = I->getType(); 113 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType()) 114 return true; 115 } 116 } 117 return false; 118 } 119 120 static bool isVoidPointerToNonConst(QualType T) { 121 if (const auto *PT = T->getAs<PointerType>()) { 122 QualType PointeeTy = PT->getPointeeType(); 123 if (PointeeTy.isConstQualified()) 124 return false; 125 return PointeeTy->isVoidType(); 126 } else 127 return false; 128 } 129 130 bool CallEvent::hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const { 131 unsigned NumOfArgs = getNumArgs(); 132 133 // If calling using a function pointer, assume the function does not 134 // satisfy the callback. 135 // TODO: We could check the types of the arguments here. 136 if (!getDecl()) 137 return false; 138 139 unsigned Idx = 0; 140 for (CallEvent::param_type_iterator I = param_type_begin(), 141 E = param_type_end(); 142 I != E && Idx < NumOfArgs; ++I, ++Idx) { 143 // If the parameter is 0, it's harmless. 144 if (getArgSVal(Idx).isZeroConstant()) 145 continue; 146 147 if (Condition(*I)) 148 return true; 149 } 150 return false; 151 } 152 153 bool CallEvent::hasNonZeroCallbackArg() const { 154 return hasNonNullArgumentsWithType(isCallback); 155 } 156 157 bool CallEvent::hasVoidPointerToNonConstArg() const { 158 return hasNonNullArgumentsWithType(isVoidPointerToNonConst); 159 } 160 161 bool CallEvent::isGlobalCFunction(StringRef FunctionName) const { 162 const auto *FD = dyn_cast_or_null<FunctionDecl>(getDecl()); 163 if (!FD) 164 return false; 165 166 return CheckerContext::isCLibraryFunction(FD, FunctionName); 167 } 168 169 /// \brief Returns true if a type is a pointer-to-const or reference-to-const 170 /// with no further indirection. 171 static bool isPointerToConst(QualType Ty) { 172 QualType PointeeTy = Ty->getPointeeType(); 173 if (PointeeTy == QualType()) 174 return false; 175 if (!PointeeTy.isConstQualified()) 176 return false; 177 if (PointeeTy->isAnyPointerType()) 178 return false; 179 return true; 180 } 181 182 // Try to retrieve the function declaration and find the function parameter 183 // types which are pointers/references to a non-pointer const. 184 // We will not invalidate the corresponding argument regions. 185 static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs, 186 const CallEvent &Call) { 187 unsigned Idx = 0; 188 for (CallEvent::param_type_iterator I = Call.param_type_begin(), 189 E = Call.param_type_end(); 190 I != E; ++I, ++Idx) { 191 if (isPointerToConst(*I)) 192 PreserveArgs.insert(Idx); 193 } 194 } 195 196 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount, 197 ProgramStateRef Orig) const { 198 ProgramStateRef Result = (Orig ? Orig : getState()); 199 200 // Don't invalidate anything if the callee is marked pure/const. 201 if (const Decl *callee = getDecl()) 202 if (callee->hasAttr<PureAttr>() || callee->hasAttr<ConstAttr>()) 203 return Result; 204 205 SmallVector<SVal, 8> ValuesToInvalidate; 206 RegionAndSymbolInvalidationTraits ETraits; 207 208 getExtraInvalidatedValues(ValuesToInvalidate, &ETraits); 209 210 // Indexes of arguments whose values will be preserved by the call. 211 llvm::SmallSet<unsigned, 4> PreserveArgs; 212 if (!argumentsMayEscape()) 213 findPtrToConstParams(PreserveArgs, *this); 214 215 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) { 216 // Mark this region for invalidation. We batch invalidate regions 217 // below for efficiency. 218 if (PreserveArgs.count(Idx)) 219 if (const MemRegion *MR = getArgSVal(Idx).getAsRegion()) 220 ETraits.setTrait(MR->getBaseRegion(), 221 RegionAndSymbolInvalidationTraits::TK_PreserveContents); 222 // TODO: Factor this out + handle the lower level const pointers. 223 224 ValuesToInvalidate.push_back(getArgSVal(Idx)); 225 } 226 227 // Invalidate designated regions using the batch invalidation API. 228 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate 229 // global variables. 230 return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(), 231 BlockCount, getLocationContext(), 232 /*CausedByPointerEscape*/ true, 233 /*Symbols=*/nullptr, this, &ETraits); 234 } 235 236 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit, 237 const ProgramPointTag *Tag) const { 238 if (const Expr *E = getOriginExpr()) { 239 if (IsPreVisit) 240 return PreStmt(E, getLocationContext(), Tag); 241 return PostStmt(E, getLocationContext(), Tag); 242 } 243 244 const Decl *D = getDecl(); 245 assert(D && "Cannot get a program point without a statement or decl"); 246 247 SourceLocation Loc = getSourceRange().getBegin(); 248 if (IsPreVisit) 249 return PreImplicitCall(D, Loc, getLocationContext(), Tag); 250 return PostImplicitCall(D, Loc, getLocationContext(), Tag); 251 } 252 253 bool CallEvent::isCalled(const CallDescription &CD) const { 254 // FIXME: Add ObjC Message support. 255 if (getKind() == CE_ObjCMessage) 256 return false; 257 if (!CD.IsLookupDone) { 258 CD.IsLookupDone = true; 259 CD.II = &getState()->getStateManager().getContext().Idents.get(CD.FuncName); 260 } 261 const IdentifierInfo *II = getCalleeIdentifier(); 262 if (!II || II != CD.II) 263 return false; 264 return (CD.RequiredArgs == CallDescription::NoArgRequirement || 265 CD.RequiredArgs == getNumArgs()); 266 } 267 268 SVal CallEvent::getArgSVal(unsigned Index) const { 269 const Expr *ArgE = getArgExpr(Index); 270 if (!ArgE) 271 return UnknownVal(); 272 return getSVal(ArgE); 273 } 274 275 SourceRange CallEvent::getArgSourceRange(unsigned Index) const { 276 const Expr *ArgE = getArgExpr(Index); 277 if (!ArgE) 278 return {}; 279 return ArgE->getSourceRange(); 280 } 281 282 SVal CallEvent::getReturnValue() const { 283 const Expr *E = getOriginExpr(); 284 if (!E) 285 return UndefinedVal(); 286 return getSVal(E); 287 } 288 289 LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); } 290 291 void CallEvent::dump(raw_ostream &Out) const { 292 ASTContext &Ctx = getState()->getStateManager().getContext(); 293 if (const Expr *E = getOriginExpr()) { 294 E->printPretty(Out, nullptr, Ctx.getPrintingPolicy()); 295 Out << "\n"; 296 return; 297 } 298 299 if (const Decl *D = getDecl()) { 300 Out << "Call to "; 301 D->print(Out, Ctx.getPrintingPolicy()); 302 return; 303 } 304 305 // FIXME: a string representation of the kind would be nice. 306 Out << "Unknown call (type " << getKind() << ")"; 307 } 308 309 bool CallEvent::isCallStmt(const Stmt *S) { 310 return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S) 311 || isa<CXXConstructExpr>(S) 312 || isa<CXXNewExpr>(S); 313 } 314 315 QualType CallEvent::getDeclaredResultType(const Decl *D) { 316 assert(D); 317 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 318 return FD->getReturnType(); 319 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 320 return MD->getReturnType(); 321 if (const auto *BD = dyn_cast<BlockDecl>(D)) { 322 // Blocks are difficult because the return type may not be stored in the 323 // BlockDecl itself. The AST should probably be enhanced, but for now we 324 // just do what we can. 325 // If the block is declared without an explicit argument list, the 326 // signature-as-written just includes the return type, not the entire 327 // function type. 328 // FIXME: All blocks should have signatures-as-written, even if the return 329 // type is inferred. (That's signified with a dependent result type.) 330 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) { 331 QualType Ty = TSI->getType(); 332 if (const FunctionType *FT = Ty->getAs<FunctionType>()) 333 Ty = FT->getReturnType(); 334 if (!Ty->isDependentType()) 335 return Ty; 336 } 337 338 return {}; 339 } 340 341 llvm_unreachable("unknown callable kind"); 342 } 343 344 bool CallEvent::isVariadic(const Decl *D) { 345 assert(D); 346 347 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 348 return FD->isVariadic(); 349 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 350 return MD->isVariadic(); 351 if (const auto *BD = dyn_cast<BlockDecl>(D)) 352 return BD->isVariadic(); 353 354 llvm_unreachable("unknown callable kind"); 355 } 356 357 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx, 358 CallEvent::BindingsTy &Bindings, 359 SValBuilder &SVB, 360 const CallEvent &Call, 361 ArrayRef<ParmVarDecl*> parameters) { 362 MemRegionManager &MRMgr = SVB.getRegionManager(); 363 364 // If the function has fewer parameters than the call has arguments, we simply 365 // do not bind any values to them. 366 unsigned NumArgs = Call.getNumArgs(); 367 unsigned Idx = 0; 368 ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end(); 369 for (; I != E && Idx < NumArgs; ++I, ++Idx) { 370 const ParmVarDecl *ParamDecl = *I; 371 assert(ParamDecl && "Formal parameter has no decl?"); 372 373 SVal ArgVal = Call.getArgSVal(Idx); 374 if (!ArgVal.isUnknown()) { 375 Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx)); 376 Bindings.push_back(std::make_pair(ParamLoc, ArgVal)); 377 } 378 } 379 380 // FIXME: Variadic arguments are not handled at all right now. 381 } 382 383 ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const { 384 const FunctionDecl *D = getDecl(); 385 if (!D) 386 return None; 387 return D->parameters(); 388 } 389 390 RuntimeDefinition AnyFunctionCall::getRuntimeDefinition() const { 391 const FunctionDecl *FD = getDecl(); 392 // Note that the AnalysisDeclContext will have the FunctionDecl with 393 // the definition (if one exists). 394 if (FD) { 395 AnalysisDeclContext *AD = 396 getLocationContext()->getAnalysisDeclContext()-> 397 getManager()->getContext(FD); 398 bool IsAutosynthesized; 399 Stmt* Body = AD->getBody(IsAutosynthesized); 400 DEBUG({ 401 if (IsAutosynthesized) 402 llvm::dbgs() << "Using autosynthesized body for " << FD->getName() 403 << "\n"; 404 }); 405 if (Body) { 406 const Decl* Decl = AD->getDecl(); 407 return RuntimeDefinition(Decl); 408 } 409 } 410 411 SubEngine *Engine = getState()->getStateManager().getOwningEngine(); 412 AnalyzerOptions &Opts = Engine->getAnalysisManager().options; 413 414 // Try to get CTU definition only if CTUDir is provided. 415 if (!Opts.naiveCTUEnabled()) 416 return RuntimeDefinition(); 417 418 cross_tu::CrossTranslationUnitContext &CTUCtx = 419 *Engine->getCrossTranslationUnitContext(); 420 llvm::Expected<const FunctionDecl *> CTUDeclOrError = 421 CTUCtx.getCrossTUDefinition(FD, Opts.getCTUDir(), Opts.getCTUIndexName()); 422 423 if (!CTUDeclOrError) { 424 handleAllErrors(CTUDeclOrError.takeError(), 425 [&](const cross_tu::IndexError &IE) { 426 CTUCtx.emitCrossTUDiagnostics(IE); 427 }); 428 return {}; 429 } 430 431 return RuntimeDefinition(*CTUDeclOrError); 432 } 433 434 void AnyFunctionCall::getInitialStackFrameContents( 435 const StackFrameContext *CalleeCtx, 436 BindingsTy &Bindings) const { 437 const auto *D = cast<FunctionDecl>(CalleeCtx->getDecl()); 438 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 439 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 440 D->parameters()); 441 } 442 443 bool AnyFunctionCall::argumentsMayEscape() const { 444 if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg()) 445 return true; 446 447 const FunctionDecl *D = getDecl(); 448 if (!D) 449 return true; 450 451 const IdentifierInfo *II = D->getIdentifier(); 452 if (!II) 453 return false; 454 455 // This set of "escaping" APIs is 456 457 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a 458 // value into thread local storage. The value can later be retrieved with 459 // 'void *ptheread_getspecific(pthread_key)'. So even thought the 460 // parameter is 'const void *', the region escapes through the call. 461 if (II->isStr("pthread_setspecific")) 462 return true; 463 464 // - xpc_connection_set_context stores a value which can be retrieved later 465 // with xpc_connection_get_context. 466 if (II->isStr("xpc_connection_set_context")) 467 return true; 468 469 // - funopen - sets a buffer for future IO calls. 470 if (II->isStr("funopen")) 471 return true; 472 473 // - __cxa_demangle - can reallocate memory and can return the pointer to 474 // the input buffer. 475 if (II->isStr("__cxa_demangle")) 476 return true; 477 478 StringRef FName = II->getName(); 479 480 // - CoreFoundation functions that end with "NoCopy" can free a passed-in 481 // buffer even if it is const. 482 if (FName.endswith("NoCopy")) 483 return true; 484 485 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can 486 // be deallocated by NSMapRemove. 487 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos)) 488 return true; 489 490 // - Many CF containers allow objects to escape through custom 491 // allocators/deallocators upon container construction. (PR12101) 492 if (FName.startswith("CF") || FName.startswith("CG")) { 493 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos || 494 StrInStrNoCase(FName, "AddValue") != StringRef::npos || 495 StrInStrNoCase(FName, "SetValue") != StringRef::npos || 496 StrInStrNoCase(FName, "WithData") != StringRef::npos || 497 StrInStrNoCase(FName, "AppendValue") != StringRef::npos || 498 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos; 499 } 500 501 return false; 502 } 503 504 const FunctionDecl *SimpleFunctionCall::getDecl() const { 505 const FunctionDecl *D = getOriginExpr()->getDirectCallee(); 506 if (D) 507 return D; 508 509 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl(); 510 } 511 512 const FunctionDecl *CXXInstanceCall::getDecl() const { 513 const auto *CE = cast_or_null<CallExpr>(getOriginExpr()); 514 if (!CE) 515 return AnyFunctionCall::getDecl(); 516 517 const FunctionDecl *D = CE->getDirectCallee(); 518 if (D) 519 return D; 520 521 return getSVal(CE->getCallee()).getAsFunctionDecl(); 522 } 523 524 void CXXInstanceCall::getExtraInvalidatedValues( 525 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const { 526 SVal ThisVal = getCXXThisVal(); 527 Values.push_back(ThisVal); 528 529 // Don't invalidate if the method is const and there are no mutable fields. 530 if (const auto *D = cast_or_null<CXXMethodDecl>(getDecl())) { 531 if (!D->isConst()) 532 return; 533 // Get the record decl for the class of 'This'. D->getParent() may return a 534 // base class decl, rather than the class of the instance which needs to be 535 // checked for mutable fields. 536 const Expr *Ex = getCXXThisExpr()->ignoreParenBaseCasts(); 537 const CXXRecordDecl *ParentRecord = Ex->getType()->getAsCXXRecordDecl(); 538 if (!ParentRecord || ParentRecord->hasMutableFields()) 539 return; 540 // Preserve CXXThis. 541 const MemRegion *ThisRegion = ThisVal.getAsRegion(); 542 if (!ThisRegion) 543 return; 544 545 ETraits->setTrait(ThisRegion->getBaseRegion(), 546 RegionAndSymbolInvalidationTraits::TK_PreserveContents); 547 } 548 } 549 550 SVal CXXInstanceCall::getCXXThisVal() const { 551 const Expr *Base = getCXXThisExpr(); 552 // FIXME: This doesn't handle an overloaded ->* operator. 553 if (!Base) 554 return UnknownVal(); 555 556 SVal ThisVal = getSVal(Base); 557 assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>()); 558 return ThisVal; 559 } 560 561 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const { 562 // Do we have a decl at all? 563 const Decl *D = getDecl(); 564 if (!D) 565 return {}; 566 567 // If the method is non-virtual, we know we can inline it. 568 const auto *MD = cast<CXXMethodDecl>(D); 569 if (!MD->isVirtual()) 570 return AnyFunctionCall::getRuntimeDefinition(); 571 572 // Do we know the implicit 'this' object being called? 573 const MemRegion *R = getCXXThisVal().getAsRegion(); 574 if (!R) 575 return {}; 576 577 // Do we know anything about the type of 'this'? 578 DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R); 579 if (!DynType.isValid()) 580 return {}; 581 582 // Is the type a C++ class? (This is mostly a defensive check.) 583 QualType RegionType = DynType.getType()->getPointeeType(); 584 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer."); 585 586 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl(); 587 if (!RD || !RD->hasDefinition()) 588 return {}; 589 590 // Find the decl for this method in that class. 591 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true); 592 if (!Result) { 593 // We might not even get the original statically-resolved method due to 594 // some particularly nasty casting (e.g. casts to sister classes). 595 // However, we should at least be able to search up and down our own class 596 // hierarchy, and some real bugs have been caught by checking this. 597 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method"); 598 599 // FIXME: This is checking that our DynamicTypeInfo is at least as good as 600 // the static type. However, because we currently don't update 601 // DynamicTypeInfo when an object is cast, we can't actually be sure the 602 // DynamicTypeInfo is up to date. This assert should be re-enabled once 603 // this is fixed. <rdar://problem/12287087> 604 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo"); 605 606 return {}; 607 } 608 609 // Does the decl that we found have an implementation? 610 const FunctionDecl *Definition; 611 if (!Result->hasBody(Definition)) 612 return {}; 613 614 // We found a definition. If we're not sure that this devirtualization is 615 // actually what will happen at runtime, make sure to provide the region so 616 // that ExprEngine can decide what to do with it. 617 if (DynType.canBeASubClass()) 618 return RuntimeDefinition(Definition, R->StripCasts()); 619 return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr); 620 } 621 622 void CXXInstanceCall::getInitialStackFrameContents( 623 const StackFrameContext *CalleeCtx, 624 BindingsTy &Bindings) const { 625 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 626 627 // Handle the binding of 'this' in the new stack frame. 628 SVal ThisVal = getCXXThisVal(); 629 if (!ThisVal.isUnknown()) { 630 ProgramStateManager &StateMgr = getState()->getStateManager(); 631 SValBuilder &SVB = StateMgr.getSValBuilder(); 632 633 const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 634 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 635 636 // If we devirtualized to a different member function, we need to make sure 637 // we have the proper layering of CXXBaseObjectRegions. 638 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) { 639 ASTContext &Ctx = SVB.getContext(); 640 const CXXRecordDecl *Class = MD->getParent(); 641 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class)); 642 643 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager. 644 bool Failed; 645 ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed); 646 if (Failed) { 647 // We might have suffered some sort of placement new earlier, so 648 // we're constructing in a completely unexpected storage. 649 // Fall back to a generic pointer cast for this-value. 650 const CXXMethodDecl *StaticMD = cast<CXXMethodDecl>(getDecl()); 651 const CXXRecordDecl *StaticClass = StaticMD->getParent(); 652 QualType StaticTy = Ctx.getPointerType(Ctx.getRecordType(StaticClass)); 653 ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy); 654 } 655 } 656 657 if (!ThisVal.isUnknown()) 658 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 659 } 660 } 661 662 const Expr *CXXMemberCall::getCXXThisExpr() const { 663 return getOriginExpr()->getImplicitObjectArgument(); 664 } 665 666 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const { 667 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the 668 // id-expression in the class member access expression is a qualified-id, 669 // that function is called. Otherwise, its final overrider in the dynamic type 670 // of the object expression is called. 671 if (const auto *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee())) 672 if (ME->hasQualifier()) 673 return AnyFunctionCall::getRuntimeDefinition(); 674 675 return CXXInstanceCall::getRuntimeDefinition(); 676 } 677 678 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const { 679 return getOriginExpr()->getArg(0); 680 } 681 682 const BlockDataRegion *BlockCall::getBlockRegion() const { 683 const Expr *Callee = getOriginExpr()->getCallee(); 684 const MemRegion *DataReg = getSVal(Callee).getAsRegion(); 685 686 return dyn_cast_or_null<BlockDataRegion>(DataReg); 687 } 688 689 ArrayRef<ParmVarDecl*> BlockCall::parameters() const { 690 const BlockDecl *D = getDecl(); 691 if (!D) 692 return nullptr; 693 return D->parameters(); 694 } 695 696 void BlockCall::getExtraInvalidatedValues(ValueList &Values, 697 RegionAndSymbolInvalidationTraits *ETraits) const { 698 // FIXME: This also needs to invalidate captured globals. 699 if (const MemRegion *R = getBlockRegion()) 700 Values.push_back(loc::MemRegionVal(R)); 701 } 702 703 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 704 BindingsTy &Bindings) const { 705 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 706 ArrayRef<ParmVarDecl*> Params; 707 if (isConversionFromLambda()) { 708 auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 709 Params = LambdaOperatorDecl->parameters(); 710 711 // For blocks converted from a C++ lambda, the callee declaration is the 712 // operator() method on the lambda so we bind "this" to 713 // the lambda captured by the block. 714 const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda(); 715 SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion); 716 Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx); 717 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 718 } else { 719 Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters(); 720 } 721 722 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 723 Params); 724 } 725 726 SVal CXXConstructorCall::getCXXThisVal() const { 727 if (Data) 728 return loc::MemRegionVal(static_cast<const MemRegion *>(Data)); 729 return UnknownVal(); 730 } 731 732 void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values, 733 RegionAndSymbolInvalidationTraits *ETraits) const { 734 if (Data) { 735 loc::MemRegionVal MV(static_cast<const MemRegion *>(Data)); 736 if (SymbolRef Sym = MV.getAsSymbol(true)) 737 ETraits->setTrait(Sym, 738 RegionAndSymbolInvalidationTraits::TK_SuppressEscape); 739 Values.push_back(MV); 740 } 741 } 742 743 void CXXConstructorCall::getInitialStackFrameContents( 744 const StackFrameContext *CalleeCtx, 745 BindingsTy &Bindings) const { 746 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 747 748 SVal ThisVal = getCXXThisVal(); 749 if (!ThisVal.isUnknown()) { 750 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 751 const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 752 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 753 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 754 } 755 } 756 757 SVal CXXDestructorCall::getCXXThisVal() const { 758 if (Data) 759 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer()); 760 return UnknownVal(); 761 } 762 763 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const { 764 // Base destructors are always called non-virtually. 765 // Skip CXXInstanceCall's devirtualization logic in this case. 766 if (isBaseDestructor()) 767 return AnyFunctionCall::getRuntimeDefinition(); 768 769 return CXXInstanceCall::getRuntimeDefinition(); 770 } 771 772 ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const { 773 const ObjCMethodDecl *D = getDecl(); 774 if (!D) 775 return None; 776 return D->parameters(); 777 } 778 779 void ObjCMethodCall::getExtraInvalidatedValues( 780 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const { 781 782 // If the method call is a setter for property known to be backed by 783 // an instance variable, don't invalidate the entire receiver, just 784 // the storage for that instance variable. 785 if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) { 786 if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) { 787 SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal()); 788 if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) { 789 ETraits->setTrait( 790 IvarRegion, 791 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); 792 ETraits->setTrait( 793 IvarRegion, 794 RegionAndSymbolInvalidationTraits::TK_SuppressEscape); 795 Values.push_back(IvarLVal); 796 } 797 return; 798 } 799 } 800 801 Values.push_back(getReceiverSVal()); 802 } 803 804 SVal ObjCMethodCall::getSelfSVal() const { 805 const LocationContext *LCtx = getLocationContext(); 806 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl(); 807 if (!SelfDecl) 808 return SVal(); 809 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx)); 810 } 811 812 SVal ObjCMethodCall::getReceiverSVal() const { 813 // FIXME: Is this the best way to handle class receivers? 814 if (!isInstanceMessage()) 815 return UnknownVal(); 816 817 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver()) 818 return getSVal(RecE); 819 820 // An instance message with no expression means we are sending to super. 821 // In this case the object reference is the same as 'self'. 822 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance); 823 SVal SelfVal = getSelfSVal(); 824 assert(SelfVal.isValid() && "Calling super but not in ObjC method"); 825 return SelfVal; 826 } 827 828 bool ObjCMethodCall::isReceiverSelfOrSuper() const { 829 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance || 830 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass) 831 return true; 832 833 if (!isInstanceMessage()) 834 return false; 835 836 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver()); 837 838 return (RecVal == getSelfSVal()); 839 } 840 841 SourceRange ObjCMethodCall::getSourceRange() const { 842 switch (getMessageKind()) { 843 case OCM_Message: 844 return getOriginExpr()->getSourceRange(); 845 case OCM_PropertyAccess: 846 case OCM_Subscript: 847 return getContainingPseudoObjectExpr()->getSourceRange(); 848 } 849 llvm_unreachable("unknown message kind"); 850 } 851 852 using ObjCMessageDataTy = llvm::PointerIntPair<const PseudoObjectExpr *, 2>; 853 854 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const { 855 assert(Data && "Lazy lookup not yet performed."); 856 assert(getMessageKind() != OCM_Message && "Explicit message send."); 857 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer(); 858 } 859 860 static const Expr * 861 getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) { 862 const Expr *Syntactic = POE->getSyntacticForm(); 863 864 // This handles the funny case of assigning to the result of a getter. 865 // This can happen if the getter returns a non-const reference. 866 if (const auto *BO = dyn_cast<BinaryOperator>(Syntactic)) 867 Syntactic = BO->getLHS(); 868 869 return Syntactic; 870 } 871 872 ObjCMessageKind ObjCMethodCall::getMessageKind() const { 873 if (!Data) { 874 // Find the parent, ignoring implicit casts. 875 ParentMap &PM = getLocationContext()->getParentMap(); 876 const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr()); 877 878 // Check if parent is a PseudoObjectExpr. 879 if (const auto *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) { 880 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE); 881 882 ObjCMessageKind K; 883 switch (Syntactic->getStmtClass()) { 884 case Stmt::ObjCPropertyRefExprClass: 885 K = OCM_PropertyAccess; 886 break; 887 case Stmt::ObjCSubscriptRefExprClass: 888 K = OCM_Subscript; 889 break; 890 default: 891 // FIXME: Can this ever happen? 892 K = OCM_Message; 893 break; 894 } 895 896 if (K != OCM_Message) { 897 const_cast<ObjCMethodCall *>(this)->Data 898 = ObjCMessageDataTy(POE, K).getOpaqueValue(); 899 assert(getMessageKind() == K); 900 return K; 901 } 902 } 903 904 const_cast<ObjCMethodCall *>(this)->Data 905 = ObjCMessageDataTy(nullptr, 1).getOpaqueValue(); 906 assert(getMessageKind() == OCM_Message); 907 return OCM_Message; 908 } 909 910 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data); 911 if (!Info.getPointer()) 912 return OCM_Message; 913 return static_cast<ObjCMessageKind>(Info.getInt()); 914 } 915 916 const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const { 917 // Look for properties accessed with property syntax (foo.bar = ...) 918 if ( getMessageKind() == OCM_PropertyAccess) { 919 const PseudoObjectExpr *POE = getContainingPseudoObjectExpr(); 920 assert(POE && "Property access without PseudoObjectExpr?"); 921 922 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE); 923 auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic); 924 925 if (RefExpr->isExplicitProperty()) 926 return RefExpr->getExplicitProperty(); 927 } 928 929 // Look for properties accessed with method syntax ([foo setBar:...]). 930 const ObjCMethodDecl *MD = getDecl(); 931 if (!MD || !MD->isPropertyAccessor()) 932 return nullptr; 933 934 // Note: This is potentially quite slow. 935 return MD->findPropertyDecl(); 936 } 937 938 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, 939 Selector Sel) const { 940 assert(IDecl); 941 const SourceManager &SM = 942 getState()->getStateManager().getContext().getSourceManager(); 943 944 // If the class interface is declared inside the main file, assume it is not 945 // subcassed. 946 // TODO: It could actually be subclassed if the subclass is private as well. 947 // This is probably very rare. 948 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc(); 949 if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc)) 950 return false; 951 952 // Assume that property accessors are not overridden. 953 if (getMessageKind() == OCM_PropertyAccess) 954 return false; 955 956 // We assume that if the method is public (declared outside of main file) or 957 // has a parent which publicly declares the method, the method could be 958 // overridden in a subclass. 959 960 // Find the first declaration in the class hierarchy that declares 961 // the selector. 962 ObjCMethodDecl *D = nullptr; 963 while (true) { 964 D = IDecl->lookupMethod(Sel, true); 965 966 // Cannot find a public definition. 967 if (!D) 968 return false; 969 970 // If outside the main file, 971 if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation())) 972 return true; 973 974 if (D->isOverriding()) { 975 // Search in the superclass on the next iteration. 976 IDecl = D->getClassInterface(); 977 if (!IDecl) 978 return false; 979 980 IDecl = IDecl->getSuperClass(); 981 if (!IDecl) 982 return false; 983 984 continue; 985 } 986 987 return false; 988 }; 989 990 llvm_unreachable("The while loop should always terminate."); 991 } 992 993 static const ObjCMethodDecl *findDefiningRedecl(const ObjCMethodDecl *MD) { 994 if (!MD) 995 return MD; 996 997 // Find the redeclaration that defines the method. 998 if (!MD->hasBody()) { 999 for (auto I : MD->redecls()) 1000 if (I->hasBody()) 1001 MD = cast<ObjCMethodDecl>(I); 1002 } 1003 return MD; 1004 } 1005 1006 static bool isCallToSelfClass(const ObjCMessageExpr *ME) { 1007 const Expr* InstRec = ME->getInstanceReceiver(); 1008 if (!InstRec) 1009 return false; 1010 const auto *InstRecIg = dyn_cast<DeclRefExpr>(InstRec->IgnoreParenImpCasts()); 1011 1012 // Check that receiver is called 'self'. 1013 if (!InstRecIg || !InstRecIg->getFoundDecl() || 1014 !InstRecIg->getFoundDecl()->getName().equals("self")) 1015 return false; 1016 1017 // Check that the method name is 'class'. 1018 if (ME->getSelector().getNumArgs() != 0 || 1019 !ME->getSelector().getNameForSlot(0).equals("class")) 1020 return false; 1021 1022 return true; 1023 } 1024 1025 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const { 1026 const ObjCMessageExpr *E = getOriginExpr(); 1027 assert(E); 1028 Selector Sel = E->getSelector(); 1029 1030 if (E->isInstanceMessage()) { 1031 // Find the receiver type. 1032 const ObjCObjectPointerType *ReceiverT = nullptr; 1033 bool CanBeSubClassed = false; 1034 QualType SupersType = E->getSuperType(); 1035 const MemRegion *Receiver = nullptr; 1036 1037 if (!SupersType.isNull()) { 1038 // The receiver is guaranteed to be 'super' in this case. 1039 // Super always means the type of immediate predecessor to the method 1040 // where the call occurs. 1041 ReceiverT = cast<ObjCObjectPointerType>(SupersType); 1042 } else { 1043 Receiver = getReceiverSVal().getAsRegion(); 1044 if (!Receiver) 1045 return {}; 1046 1047 DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver); 1048 if (!DTI.isValid()) { 1049 assert(isa<AllocaRegion>(Receiver) && 1050 "Unhandled untyped region class!"); 1051 return {}; 1052 } 1053 1054 QualType DynType = DTI.getType(); 1055 CanBeSubClassed = DTI.canBeASubClass(); 1056 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType()); 1057 1058 if (ReceiverT && CanBeSubClassed) 1059 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) 1060 if (!canBeOverridenInSubclass(IDecl, Sel)) 1061 CanBeSubClassed = false; 1062 } 1063 1064 // Handle special cases of '[self classMethod]' and 1065 // '[[self class] classMethod]', which are treated by the compiler as 1066 // instance (not class) messages. We will statically dispatch to those. 1067 if (auto *PT = dyn_cast_or_null<ObjCObjectPointerType>(ReceiverT)) { 1068 // For [self classMethod], return the compiler visible declaration. 1069 if (PT->getObjectType()->isObjCClass() && 1070 Receiver == getSelfSVal().getAsRegion()) 1071 return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl())); 1072 1073 // Similarly, handle [[self class] classMethod]. 1074 // TODO: We are currently doing a syntactic match for this pattern with is 1075 // limiting as the test cases in Analysis/inlining/InlineObjCClassMethod.m 1076 // shows. A better way would be to associate the meta type with the symbol 1077 // using the dynamic type info tracking and use it here. We can add a new 1078 // SVal for ObjC 'Class' values that know what interface declaration they 1079 // come from. Then 'self' in a class method would be filled in with 1080 // something meaningful in ObjCMethodCall::getReceiverSVal() and we could 1081 // do proper dynamic dispatch for class methods just like we do for 1082 // instance methods now. 1083 if (E->getInstanceReceiver()) 1084 if (const auto *M = dyn_cast<ObjCMessageExpr>(E->getInstanceReceiver())) 1085 if (isCallToSelfClass(M)) 1086 return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl())); 1087 } 1088 1089 // Lookup the instance method implementation. 1090 if (ReceiverT) 1091 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) { 1092 // Repeatedly calling lookupPrivateMethod() is expensive, especially 1093 // when in many cases it returns null. We cache the results so 1094 // that repeated queries on the same ObjCIntefaceDecl and Selector 1095 // don't incur the same cost. On some test cases, we can see the 1096 // same query being issued thousands of times. 1097 // 1098 // NOTE: This cache is essentially a "global" variable, but it 1099 // only gets lazily created when we get here. The value of the 1100 // cache probably comes from it being global across ExprEngines, 1101 // where the same queries may get issued. If we are worried about 1102 // concurrency, or possibly loading/unloading ASTs, etc., we may 1103 // need to revisit this someday. In terms of memory, this table 1104 // stays around until clang quits, which also may be bad if we 1105 // need to release memory. 1106 using PrivateMethodKey = std::pair<const ObjCInterfaceDecl *, Selector>; 1107 using PrivateMethodCache = 1108 llvm::DenseMap<PrivateMethodKey, Optional<const ObjCMethodDecl *>>; 1109 1110 static PrivateMethodCache PMC; 1111 Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)]; 1112 1113 // Query lookupPrivateMethod() if the cache does not hit. 1114 if (!Val.hasValue()) { 1115 Val = IDecl->lookupPrivateMethod(Sel); 1116 1117 // If the method is a property accessor, we should try to "inline" it 1118 // even if we don't actually have an implementation. 1119 if (!*Val) 1120 if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl()) 1121 if (CompileTimeMD->isPropertyAccessor()) { 1122 if (!CompileTimeMD->getSelfDecl() && 1123 isa<ObjCCategoryDecl>(CompileTimeMD->getDeclContext())) { 1124 // If the method is an accessor in a category, and it doesn't 1125 // have a self declaration, first 1126 // try to find the method in a class extension. This 1127 // works around a bug in Sema where multiple accessors 1128 // are synthesized for properties in class 1129 // extensions that are redeclared in a category and the 1130 // the implicit parameters are not filled in for 1131 // the method on the category. 1132 // This ensures we find the accessor in the extension, which 1133 // has the implicit parameters filled in. 1134 auto *ID = CompileTimeMD->getClassInterface(); 1135 for (auto *CatDecl : ID->visible_extensions()) { 1136 Val = CatDecl->getMethod(Sel, 1137 CompileTimeMD->isInstanceMethod()); 1138 if (*Val) 1139 break; 1140 } 1141 } 1142 if (!*Val) 1143 Val = IDecl->lookupInstanceMethod(Sel); 1144 } 1145 } 1146 1147 const ObjCMethodDecl *MD = Val.getValue(); 1148 if (CanBeSubClassed) 1149 return RuntimeDefinition(MD, Receiver); 1150 else 1151 return RuntimeDefinition(MD, nullptr); 1152 } 1153 } else { 1154 // This is a class method. 1155 // If we have type info for the receiver class, we are calling via 1156 // class name. 1157 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) { 1158 // Find/Return the method implementation. 1159 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel)); 1160 } 1161 } 1162 1163 return {}; 1164 } 1165 1166 bool ObjCMethodCall::argumentsMayEscape() const { 1167 if (isInSystemHeader() && !isInstanceMessage()) { 1168 Selector Sel = getSelector(); 1169 if (Sel.getNumArgs() == 1 && 1170 Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer")) 1171 return true; 1172 } 1173 1174 return CallEvent::argumentsMayEscape(); 1175 } 1176 1177 void ObjCMethodCall::getInitialStackFrameContents( 1178 const StackFrameContext *CalleeCtx, 1179 BindingsTy &Bindings) const { 1180 const auto *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl()); 1181 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 1182 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 1183 D->parameters()); 1184 1185 SVal SelfVal = getReceiverSVal(); 1186 if (!SelfVal.isUnknown()) { 1187 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl(); 1188 MemRegionManager &MRMgr = SVB.getRegionManager(); 1189 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx)); 1190 Bindings.push_back(std::make_pair(SelfLoc, SelfVal)); 1191 } 1192 } 1193 1194 CallEventRef<> 1195 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State, 1196 const LocationContext *LCtx) { 1197 if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(CE)) 1198 return create<CXXMemberCall>(MCE, State, LCtx); 1199 1200 if (const auto *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 1201 const FunctionDecl *DirectCallee = OpCE->getDirectCallee(); 1202 if (const auto *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) 1203 if (MD->isInstance()) 1204 return create<CXXMemberOperatorCall>(OpCE, State, LCtx); 1205 1206 } else if (CE->getCallee()->getType()->isBlockPointerType()) { 1207 return create<BlockCall>(CE, State, LCtx); 1208 } 1209 1210 // Otherwise, it's a normal function call, static member function call, or 1211 // something we can't reason about. 1212 return create<SimpleFunctionCall>(CE, State, LCtx); 1213 } 1214 1215 CallEventRef<> 1216 CallEventManager::getCaller(const StackFrameContext *CalleeCtx, 1217 ProgramStateRef State) { 1218 const LocationContext *ParentCtx = CalleeCtx->getParent(); 1219 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame(); 1220 assert(CallerCtx && "This should not be used for top-level stack frames"); 1221 1222 const Stmt *CallSite = CalleeCtx->getCallSite(); 1223 1224 if (CallSite) { 1225 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite)) 1226 return getSimpleCall(CE, State, CallerCtx); 1227 1228 switch (CallSite->getStmtClass()) { 1229 case Stmt::CXXConstructExprClass: 1230 case Stmt::CXXTemporaryObjectExprClass: { 1231 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 1232 const auto *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 1233 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx); 1234 SVal ThisVal = State->getSVal(ThisPtr); 1235 1236 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite), 1237 ThisVal.getAsRegion(), State, CallerCtx); 1238 } 1239 case Stmt::CXXNewExprClass: 1240 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx); 1241 case Stmt::ObjCMessageExprClass: 1242 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite), 1243 State, CallerCtx); 1244 default: 1245 llvm_unreachable("This is not an inlineable statement."); 1246 } 1247 } 1248 1249 // Fall back to the CFG. The only thing we haven't handled yet is 1250 // destructors, though this could change in the future. 1251 const CFGBlock *B = CalleeCtx->getCallSiteBlock(); 1252 CFGElement E = (*B)[CalleeCtx->getIndex()]; 1253 assert((E.getAs<CFGImplicitDtor>() || E.getAs<CFGTemporaryDtor>()) && 1254 "All other CFG elements should have exprs"); 1255 1256 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 1257 const auto *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl()); 1258 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx); 1259 SVal ThisVal = State->getSVal(ThisPtr); 1260 1261 const Stmt *Trigger; 1262 if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>()) 1263 Trigger = AutoDtor->getTriggerStmt(); 1264 else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>()) 1265 Trigger = DeleteDtor->getDeleteExpr(); 1266 else 1267 Trigger = Dtor->getBody(); 1268 1269 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(), 1270 E.getAs<CFGBaseDtor>().hasValue(), State, 1271 CallerCtx); 1272 } 1273