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     loc::MemRegionVal MV(static_cast<const MemRegion *>(Data));
677     if (SymbolRef Sym = MV.getAsSymbol(true))
678       ETraits->setTrait(Sym,
679                         RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
680     Values.push_back(MV);
681   }
682 }
683 
684 void CXXConstructorCall::getInitialStackFrameContents(
685                                              const StackFrameContext *CalleeCtx,
686                                              BindingsTy &Bindings) const {
687   AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
688 
689   SVal ThisVal = getCXXThisVal();
690   if (!ThisVal.isUnknown()) {
691     SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
692     const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
693     Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
694     Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
695   }
696 }
697 
698 SVal CXXDestructorCall::getCXXThisVal() const {
699   if (Data)
700     return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
701   return UnknownVal();
702 }
703 
704 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
705   // Base destructors are always called non-virtually.
706   // Skip CXXInstanceCall's devirtualization logic in this case.
707   if (isBaseDestructor())
708     return AnyFunctionCall::getRuntimeDefinition();
709 
710   return CXXInstanceCall::getRuntimeDefinition();
711 }
712 
713 ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const {
714   const ObjCMethodDecl *D = getDecl();
715   if (!D)
716     return None;
717   return D->parameters();
718 }
719 
720 void ObjCMethodCall::getExtraInvalidatedValues(
721     ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
722 
723   // If the method call is a setter for property known to be backed by
724   // an instance variable, don't invalidate the entire receiver, just
725   // the storage for that instance variable.
726   if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
727     if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
728       SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
729       if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) {
730         ETraits->setTrait(
731           IvarRegion,
732           RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
733         ETraits->setTrait(
734           IvarRegion,
735           RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
736         Values.push_back(IvarLVal);
737       }
738       return;
739     }
740   }
741 
742   Values.push_back(getReceiverSVal());
743 }
744 
745 SVal ObjCMethodCall::getSelfSVal() const {
746   const LocationContext *LCtx = getLocationContext();
747   const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
748   if (!SelfDecl)
749     return SVal();
750   return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
751 }
752 
753 SVal ObjCMethodCall::getReceiverSVal() const {
754   // FIXME: Is this the best way to handle class receivers?
755   if (!isInstanceMessage())
756     return UnknownVal();
757 
758   if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
759     return getSVal(RecE);
760 
761   // An instance message with no expression means we are sending to super.
762   // In this case the object reference is the same as 'self'.
763   assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
764   SVal SelfVal = getSelfSVal();
765   assert(SelfVal.isValid() && "Calling super but not in ObjC method");
766   return SelfVal;
767 }
768 
769 bool ObjCMethodCall::isReceiverSelfOrSuper() const {
770   if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
771       getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
772       return true;
773 
774   if (!isInstanceMessage())
775     return false;
776 
777   SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
778 
779   return (RecVal == getSelfSVal());
780 }
781 
782 SourceRange ObjCMethodCall::getSourceRange() const {
783   switch (getMessageKind()) {
784   case OCM_Message:
785     return getOriginExpr()->getSourceRange();
786   case OCM_PropertyAccess:
787   case OCM_Subscript:
788     return getContainingPseudoObjectExpr()->getSourceRange();
789   }
790   llvm_unreachable("unknown message kind");
791 }
792 
793 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
794 
795 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
796   assert(Data && "Lazy lookup not yet performed.");
797   assert(getMessageKind() != OCM_Message && "Explicit message send.");
798   return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
799 }
800 
801 static const Expr *
802 getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) {
803   const Expr *Syntactic = POE->getSyntacticForm();
804 
805   // This handles the funny case of assigning to the result of a getter.
806   // This can happen if the getter returns a non-const reference.
807   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
808     Syntactic = BO->getLHS();
809 
810   return Syntactic;
811 }
812 
813 ObjCMessageKind ObjCMethodCall::getMessageKind() const {
814   if (!Data) {
815 
816     // Find the parent, ignoring implicit casts.
817     ParentMap &PM = getLocationContext()->getParentMap();
818     const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr());
819 
820     // Check if parent is a PseudoObjectExpr.
821     if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
822       const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
823 
824       ObjCMessageKind K;
825       switch (Syntactic->getStmtClass()) {
826       case Stmt::ObjCPropertyRefExprClass:
827         K = OCM_PropertyAccess;
828         break;
829       case Stmt::ObjCSubscriptRefExprClass:
830         K = OCM_Subscript;
831         break;
832       default:
833         // FIXME: Can this ever happen?
834         K = OCM_Message;
835         break;
836       }
837 
838       if (K != OCM_Message) {
839         const_cast<ObjCMethodCall *>(this)->Data
840           = ObjCMessageDataTy(POE, K).getOpaqueValue();
841         assert(getMessageKind() == K);
842         return K;
843       }
844     }
845 
846     const_cast<ObjCMethodCall *>(this)->Data
847       = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
848     assert(getMessageKind() == OCM_Message);
849     return OCM_Message;
850   }
851 
852   ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
853   if (!Info.getPointer())
854     return OCM_Message;
855   return static_cast<ObjCMessageKind>(Info.getInt());
856 }
857 
858 const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const {
859   // Look for properties accessed with property syntax (foo.bar = ...)
860   if ( getMessageKind() == OCM_PropertyAccess) {
861     const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
862     assert(POE && "Property access without PseudoObjectExpr?");
863 
864     const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
865     auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
866 
867     if (RefExpr->isExplicitProperty())
868       return RefExpr->getExplicitProperty();
869   }
870 
871   // Look for properties accessed with method syntax ([foo setBar:...]).
872   const ObjCMethodDecl *MD = getDecl();
873   if (!MD || !MD->isPropertyAccessor())
874     return nullptr;
875 
876   // Note: This is potentially quite slow.
877   return MD->findPropertyDecl();
878 }
879 
880 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
881                                              Selector Sel) const {
882   assert(IDecl);
883   const SourceManager &SM =
884     getState()->getStateManager().getContext().getSourceManager();
885 
886   // If the class interface is declared inside the main file, assume it is not
887   // subcassed.
888   // TODO: It could actually be subclassed if the subclass is private as well.
889   // This is probably very rare.
890   SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
891   if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc))
892     return false;
893 
894   // Assume that property accessors are not overridden.
895   if (getMessageKind() == OCM_PropertyAccess)
896     return false;
897 
898   // We assume that if the method is public (declared outside of main file) or
899   // has a parent which publicly declares the method, the method could be
900   // overridden in a subclass.
901 
902   // Find the first declaration in the class hierarchy that declares
903   // the selector.
904   ObjCMethodDecl *D = nullptr;
905   while (true) {
906     D = IDecl->lookupMethod(Sel, true);
907 
908     // Cannot find a public definition.
909     if (!D)
910       return false;
911 
912     // If outside the main file,
913     if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation()))
914       return true;
915 
916     if (D->isOverriding()) {
917       // Search in the superclass on the next iteration.
918       IDecl = D->getClassInterface();
919       if (!IDecl)
920         return false;
921 
922       IDecl = IDecl->getSuperClass();
923       if (!IDecl)
924         return false;
925 
926       continue;
927     }
928 
929     return false;
930   };
931 
932   llvm_unreachable("The while loop should always terminate.");
933 }
934 
935 static const ObjCMethodDecl *findDefiningRedecl(const ObjCMethodDecl *MD) {
936   if (!MD)
937     return MD;
938 
939   // Find the redeclaration that defines the method.
940   if (!MD->hasBody()) {
941     for (auto I : MD->redecls())
942       if (I->hasBody())
943         MD = cast<ObjCMethodDecl>(I);
944   }
945   return MD;
946 }
947 
948 static bool isCallToSelfClass(const ObjCMessageExpr *ME) {
949   const Expr* InstRec = ME->getInstanceReceiver();
950   if (!InstRec)
951     return false;
952   const auto *InstRecIg = dyn_cast<DeclRefExpr>(InstRec->IgnoreParenImpCasts());
953 
954   // Check that receiver is called 'self'.
955   if (!InstRecIg || !InstRecIg->getFoundDecl() ||
956       !InstRecIg->getFoundDecl()->getName().equals("self"))
957     return false;
958 
959   // Check that the method name is 'class'.
960   if (ME->getSelector().getNumArgs() != 0 ||
961       !ME->getSelector().getNameForSlot(0).equals("class"))
962     return false;
963 
964   return true;
965 }
966 
967 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
968   const ObjCMessageExpr *E = getOriginExpr();
969   assert(E);
970   Selector Sel = E->getSelector();
971 
972   if (E->isInstanceMessage()) {
973 
974     // Find the receiver type.
975     const ObjCObjectPointerType *ReceiverT = nullptr;
976     bool CanBeSubClassed = false;
977     QualType SupersType = E->getSuperType();
978     const MemRegion *Receiver = nullptr;
979 
980     if (!SupersType.isNull()) {
981       // The receiver is guaranteed to be 'super' in this case.
982       // Super always means the type of immediate predecessor to the method
983       // where the call occurs.
984       ReceiverT = cast<ObjCObjectPointerType>(SupersType);
985     } else {
986       Receiver = getReceiverSVal().getAsRegion();
987       if (!Receiver)
988         return RuntimeDefinition();
989 
990       DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
991       if (!DTI.isValid()) {
992         assert(isa<AllocaRegion>(Receiver) &&
993                "Unhandled untyped region class!");
994         return RuntimeDefinition();
995       }
996 
997       QualType DynType = DTI.getType();
998       CanBeSubClassed = DTI.canBeASubClass();
999       ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType());
1000 
1001       if (ReceiverT && CanBeSubClassed)
1002         if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
1003           if (!canBeOverridenInSubclass(IDecl, Sel))
1004             CanBeSubClassed = false;
1005     }
1006 
1007     // Handle special cases of '[self classMethod]' and
1008     // '[[self class] classMethod]', which are treated by the compiler as
1009     // instance (not class) messages. We will statically dispatch to those.
1010     if (auto *PT = dyn_cast_or_null<ObjCObjectPointerType>(ReceiverT)) {
1011       // For [self classMethod], return the compiler visible declaration.
1012       if (PT->getObjectType()->isObjCClass() &&
1013           Receiver == getSelfSVal().getAsRegion())
1014         return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
1015 
1016       // Similarly, handle [[self class] classMethod].
1017       // TODO: We are currently doing a syntactic match for this pattern with is
1018       // limiting as the test cases in Analysis/inlining/InlineObjCClassMethod.m
1019       // shows. A better way would be to associate the meta type with the symbol
1020       // using the dynamic type info tracking and use it here. We can add a new
1021       // SVal for ObjC 'Class' values that know what interface declaration they
1022       // come from. Then 'self' in a class method would be filled in with
1023       // something meaningful in ObjCMethodCall::getReceiverSVal() and we could
1024       // do proper dynamic dispatch for class methods just like we do for
1025       // instance methods now.
1026       if (E->getInstanceReceiver())
1027         if (const auto *M = dyn_cast<ObjCMessageExpr>(E->getInstanceReceiver()))
1028           if (isCallToSelfClass(M))
1029             return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
1030     }
1031 
1032     // Lookup the instance method implementation.
1033     if (ReceiverT)
1034       if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
1035         // Repeatedly calling lookupPrivateMethod() is expensive, especially
1036         // when in many cases it returns null.  We cache the results so
1037         // that repeated queries on the same ObjCIntefaceDecl and Selector
1038         // don't incur the same cost.  On some test cases, we can see the
1039         // same query being issued thousands of times.
1040         //
1041         // NOTE: This cache is essentially a "global" variable, but it
1042         // only gets lazily created when we get here.  The value of the
1043         // cache probably comes from it being global across ExprEngines,
1044         // where the same queries may get issued.  If we are worried about
1045         // concurrency, or possibly loading/unloading ASTs, etc., we may
1046         // need to revisit this someday.  In terms of memory, this table
1047         // stays around until clang quits, which also may be bad if we
1048         // need to release memory.
1049         typedef std::pair<const ObjCInterfaceDecl*, Selector>
1050                 PrivateMethodKey;
1051         typedef llvm::DenseMap<PrivateMethodKey,
1052                                Optional<const ObjCMethodDecl *> >
1053                 PrivateMethodCache;
1054 
1055         static PrivateMethodCache PMC;
1056         Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
1057 
1058         // Query lookupPrivateMethod() if the cache does not hit.
1059         if (!Val.hasValue()) {
1060           Val = IDecl->lookupPrivateMethod(Sel);
1061 
1062           // If the method is a property accessor, we should try to "inline" it
1063           // even if we don't actually have an implementation.
1064           if (!*Val)
1065             if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl())
1066               if (CompileTimeMD->isPropertyAccessor()) {
1067                 if (!CompileTimeMD->getSelfDecl() &&
1068                     isa<ObjCCategoryDecl>(CompileTimeMD->getDeclContext())) {
1069                   // If the method is an accessor in a category, and it doesn't
1070                   // have a self declaration, first
1071                   // try to find the method in a class extension. This
1072                   // works around a bug in Sema where multiple accessors
1073                   // are synthesized for properties in class
1074                   // extensions that are redeclared in a category and the
1075                   // the implicit parameters are not filled in for
1076                   // the method on the category.
1077                   // This ensures we find the accessor in the extension, which
1078                   // has the implicit parameters filled in.
1079                   auto *ID = CompileTimeMD->getClassInterface();
1080                   for (auto *CatDecl : ID->visible_extensions()) {
1081                     Val = CatDecl->getMethod(Sel,
1082                                              CompileTimeMD->isInstanceMethod());
1083                     if (*Val)
1084                       break;
1085                   }
1086                 }
1087                 if (!*Val)
1088                   Val = IDecl->lookupInstanceMethod(Sel);
1089               }
1090         }
1091 
1092         const ObjCMethodDecl *MD = Val.getValue();
1093         if (CanBeSubClassed)
1094           return RuntimeDefinition(MD, Receiver);
1095         else
1096           return RuntimeDefinition(MD, nullptr);
1097       }
1098 
1099   } else {
1100     // This is a class method.
1101     // If we have type info for the receiver class, we are calling via
1102     // class name.
1103     if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
1104       // Find/Return the method implementation.
1105       return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
1106     }
1107   }
1108 
1109   return RuntimeDefinition();
1110 }
1111 
1112 bool ObjCMethodCall::argumentsMayEscape() const {
1113   if (isInSystemHeader() && !isInstanceMessage()) {
1114     Selector Sel = getSelector();
1115     if (Sel.getNumArgs() == 1 &&
1116         Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
1117       return true;
1118   }
1119 
1120   return CallEvent::argumentsMayEscape();
1121 }
1122 
1123 void ObjCMethodCall::getInitialStackFrameContents(
1124                                              const StackFrameContext *CalleeCtx,
1125                                              BindingsTy &Bindings) const {
1126   const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
1127   SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
1128   addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
1129                                D->parameters());
1130 
1131   SVal SelfVal = getReceiverSVal();
1132   if (!SelfVal.isUnknown()) {
1133     const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
1134     MemRegionManager &MRMgr = SVB.getRegionManager();
1135     Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
1136     Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
1137   }
1138 }
1139 
1140 CallEventRef<>
1141 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
1142                                 const LocationContext *LCtx) {
1143   if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
1144     return create<CXXMemberCall>(MCE, State, LCtx);
1145 
1146   if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
1147     const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
1148     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
1149       if (MD->isInstance())
1150         return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
1151 
1152   } else if (CE->getCallee()->getType()->isBlockPointerType()) {
1153     return create<BlockCall>(CE, State, LCtx);
1154   }
1155 
1156   // Otherwise, it's a normal function call, static member function call, or
1157   // something we can't reason about.
1158   return create<SimpleFunctionCall>(CE, State, LCtx);
1159 }
1160 
1161 
1162 CallEventRef<>
1163 CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
1164                             ProgramStateRef State) {
1165   const LocationContext *ParentCtx = CalleeCtx->getParent();
1166   const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
1167   assert(CallerCtx && "This should not be used for top-level stack frames");
1168 
1169   const Stmt *CallSite = CalleeCtx->getCallSite();
1170 
1171   if (CallSite) {
1172     if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
1173       return getSimpleCall(CE, State, CallerCtx);
1174 
1175     switch (CallSite->getStmtClass()) {
1176     case Stmt::CXXConstructExprClass:
1177     case Stmt::CXXTemporaryObjectExprClass: {
1178       SValBuilder &SVB = State->getStateManager().getSValBuilder();
1179       const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
1180       Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
1181       SVal ThisVal = State->getSVal(ThisPtr);
1182 
1183       return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
1184                                    ThisVal.getAsRegion(), State, CallerCtx);
1185     }
1186     case Stmt::CXXNewExprClass:
1187       return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
1188     case Stmt::ObjCMessageExprClass:
1189       return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
1190                                State, CallerCtx);
1191     default:
1192       llvm_unreachable("This is not an inlineable statement.");
1193     }
1194   }
1195 
1196   // Fall back to the CFG. The only thing we haven't handled yet is
1197   // destructors, though this could change in the future.
1198   const CFGBlock *B = CalleeCtx->getCallSiteBlock();
1199   CFGElement E = (*B)[CalleeCtx->getIndex()];
1200   assert(E.getAs<CFGImplicitDtor>() &&
1201          "All other CFG elements should have exprs");
1202   assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet");
1203 
1204   SValBuilder &SVB = State->getStateManager().getSValBuilder();
1205   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
1206   Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
1207   SVal ThisVal = State->getSVal(ThisPtr);
1208 
1209   const Stmt *Trigger;
1210   if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
1211     Trigger = AutoDtor->getTriggerStmt();
1212   else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
1213     Trigger = cast<Stmt>(DeleteDtor->getDeleteExpr());
1214   else
1215     Trigger = Dtor->getBody();
1216 
1217   return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
1218                               E.getAs<CFGBaseDtor>().hasValue(), State,
1219                               CallerCtx);
1220 }
1221