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