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