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