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