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