clang 24.0.0git
CallEvent.cpp
Go to the documentation of this file.
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
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"
29#include "clang/Analysis/CFG.h"
34#include "clang/Basic/LLVM.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/Compiler.h"
59#include "llvm/Support/Debug.h"
60#include "llvm/Support/ErrorHandling.h"
61#include "llvm/Support/raw_ostream.h"
62#include <cassert>
63#include <optional>
64#include <utility>
65
66#define DEBUG_TYPE "static-analyzer-call-event"
67
68using namespace clang;
69using namespace ento;
70
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
79static 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()->getDefinitionOrSelf();
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
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
114 const Decl *D = getDecl();
115 if (!D)
116 return false;
117
119 if (Loc.isValid()) {
120 const SourceManager &SM =
121 getState()->getStateManager().getContext().getSourceManager();
122 return SM.isInSystemHeader(D->getLocation());
123 }
124
125 // Special case for implicitly-declared global operator new/delete.
126 // These should be considered system functions.
127 if (const auto *FD = dyn_cast<FunctionDecl>(D))
128 return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
129
130 return false;
131}
132
134 unsigned NumOfArgs = getNumArgs();
135
136 // If calling using a function pointer, assume the function does not
137 // satisfy the callback.
138 // TODO: We could check the types of the arguments here.
139 if (!getDecl())
140 return false;
141
142 unsigned Idx = 0;
144 E = param_type_end();
145 I != E && Idx < NumOfArgs; ++I, ++Idx) {
146 // If the parameter is 0, it's harmless.
147 if (getArgSVal(Idx).isZeroConstant())
148 continue;
149
150 if (Condition(*I))
151 return true;
152 }
153 return false;
154}
155
159
163
164bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
165 const auto *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
166 if (!FD)
167 return false;
168
169 return CheckerContext::isCLibraryFunction(FD, FunctionName);
170}
171
173 const Decl *D = getDecl();
174 if (!D)
175 return nullptr;
176
178 SF->getAnalysisDeclContext()->getManager()->getContext(D);
179
180 return ADC;
181}
182
183const StackFrame *CallEvent::getCalleeStackFrame(unsigned BlockCount) const {
185 if (!ADC)
186 return nullptr;
187
188 const Expr *E = getOriginExpr();
189 if (!E)
190 return nullptr;
191
192 // Recover CFG block via reverse lookup.
193 // TODO: If we were to keep CFG element information as part of the CallEvent
194 // instead of doing this reverse lookup, we would be able to build the stack
195 // frame for non-expression-based calls, and also we wouldn't need the reverse
196 // lookup.
197 const CFGStmtMap *Map = SF->getAnalysisDeclContext()->getCFGStmtMap();
198 const CFGBlock *B = Map->getBlock(E);
199 assert(B);
200
201 // Also recover CFG index by scanning the CFG block.
202 unsigned Idx = 0, Sz = B->size();
203 for (; Idx < Sz; ++Idx)
204 if (auto StmtElem = (*B)[Idx].getAs<CFGStmt>())
205 if (StmtElem->getStmt() == E)
206 break;
207 assert(Idx < Sz);
208
209 return ADC->getStackFrame(SF, nullptr, E, B, BlockCount, Idx);
210}
211
212const ParamVarRegion
213*CallEvent::getParameterLocation(unsigned Index, unsigned BlockCount) const {
214 const StackFrame *SF = getCalleeStackFrame(BlockCount);
215 // We cannot construct a VarRegion without a stack frame.
216 if (!SF)
217 return nullptr;
218
219 const ParamVarRegion *PVR =
220 State->getStateManager().getRegionManager().getParamVarRegion(
221 getOriginExpr(), Index, SF);
222 return PVR;
223}
224
225/// Returns true if a type is a pointer-to-const or reference-to-const
226/// with no further indirection.
227static bool isPointerToConst(QualType Ty) {
228 QualType PointeeTy = Ty->getPointeeType();
229 if (PointeeTy == QualType())
230 return false;
231 if (!PointeeTy.isConstQualified())
232 return false;
233 if (PointeeTy->isAnyPointerType())
234 return false;
235 return true;
236}
237
238// Try to retrieve the function declaration and find the function parameter
239// types which are pointers/references to a non-pointer const.
240// We will not invalidate the corresponding argument regions.
241static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
242 const CallEvent &Call) {
243 unsigned Idx = 0;
244 for (CallEvent::param_type_iterator I = Call.param_type_begin(),
245 E = Call.param_type_end();
246 I != E; ++I, ++Idx) {
247 if (isPointerToConst(*I))
248 PreserveArgs.insert(Idx);
249 }
250}
251
253 if (const auto *CtorCall = dyn_cast<CXXConstructorCall>(&Call)) {
254 if (const MemRegion *R = CtorCall->getCXXThisVal().getAsRegion())
255 return R->getBaseRegion();
256 }
257 return nullptr;
258}
259
261 ProgramStateRef State) const {
262 // Don't invalidate anything if the callee is marked pure/const.
263 if (const Decl *Callee = getDecl())
264 if (Callee->hasAttr<PureAttr>() || Callee->hasAttr<ConstAttr>())
265 return State;
266
267 SmallVector<SVal, 8> ValuesToInvalidate;
269
270 getExtraInvalidatedValues(ValuesToInvalidate, &ETraits);
271
272 // Indexes of arguments whose values will be preserved by the call.
273 llvm::SmallSet<unsigned, 4> PreserveArgs;
274 if (!argumentsMayEscape())
275 findPtrToConstParams(PreserveArgs, *this);
276
277 // We should not preserve the contents of the region pointed by "this" when
278 // constructing the object, even if an argument refers to it.
279 const auto *ThisRegionBaseOrNull = getThisRegionBaseOrNull(*this);
280
281 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
282 // Mark this region for invalidation. We batch invalidate regions
283 // below for efficiency.
284 if (PreserveArgs.count(Idx)) {
285 if (const MemRegion *ArgBaseR = getArgSVal(Idx).getAsRegion()) {
286 ArgBaseR = ArgBaseR->getBaseRegion();
287
288 // Preserve the contents of the pointee of the argument - except if it
289 // refers to the object under construction (ctor call).
290 if (ArgBaseR != ThisRegionBaseOrNull) {
291 ETraits.setTrait(
293 // TODO: Factor this out + handle the lower level const pointers.
294 }
295 }
296 }
297
298 ValuesToInvalidate.push_back(getArgSVal(Idx));
299
300 // If a function accepts an object by argument (which would of course be a
301 // temporary that isn't lifetime-extended), invalidate the object itself,
302 // not only other objects reachable from it. This is necessary because the
303 // destructor has access to the temporary object after the call.
304 // TODO: Support placement arguments once we start
305 // constructing them directly.
306 // TODO: This is unnecessary when there's no destructor, but that's
307 // currently hard to figure out.
308 if (getKind() != CE_CXXAllocator)
310 if (auto AdjIdx = getAdjustedParameterIndex(Idx))
311 if (const TypedValueRegion *TVR =
312 getParameterLocation(*AdjIdx, BlockCount))
313 ValuesToInvalidate.push_back(loc::MemRegionVal(TVR));
314 }
315
316 // Invalidate designated regions using the batch invalidation API.
317 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
318 // global variables.
319 return State->invalidateRegions(ValuesToInvalidate, getCFGElementRef(),
320 BlockCount, getStackFrame(),
321 /*CausedByPointerEscape*/ true,
322 /*Symbols=*/nullptr, this, &ETraits);
323}
324
326 const ProgramPointTag *Tag) const {
327
328 if (const Expr *E = getOriginExpr()) {
329 if (IsPreVisit)
330 return PreStmt(E, getStackFrame(), Tag);
331 return PostStmt(E, getStackFrame(), Tag);
332 }
333
334 const Decl *D = getDecl();
335 assert(D && "Cannot get a program point without a statement or decl");
336 assert(ElemRef.getParent() &&
337 "Cannot get a program point without a CFGElementRef");
338
340 if (IsPreVisit)
341 return PreImplicitCall(D, Loc, getStackFrame(), ElemRef, Tag);
342 return PostImplicitCall(D, Loc, getStackFrame(), ElemRef, Tag);
343}
344
345SVal CallEvent::getArgSVal(unsigned Index) const {
346 const Expr *ArgE = getArgExpr(Index);
347 if (!ArgE)
348 return UnknownVal();
349 return getSVal(ArgE);
350}
351
353 const Expr *ArgE = getArgExpr(Index);
354 if (!ArgE)
355 return {};
356 return ArgE->getSourceRange();
357}
358
360 const Expr *E = getOriginExpr();
361 if (!E)
362 return UndefinedVal();
363 return getSVal(E);
364}
365
366LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
367
368void CallEvent::dump(raw_ostream &Out) const {
369 ASTContext &Ctx = getState()->getStateManager().getContext();
370 if (const Expr *E = getOriginExpr()) {
371 E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
372 return;
373 }
374
375 if (const Decl *D = getDecl()) {
376 Out << "Call to ";
377 D->print(Out, Ctx.getPrintingPolicy());
378 return;
379 }
380
381 Out << "Unknown call (type " << getKindAsString() << ")";
382}
383
387
389 assert(D);
390 if (const auto *FD = dyn_cast<FunctionDecl>(D))
391 return FD->getReturnType();
392 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
393 return MD->getReturnType();
394 if (const auto *BD = dyn_cast<BlockDecl>(D)) {
395 // Blocks are difficult because the return type may not be stored in the
396 // BlockDecl itself. The AST should probably be enhanced, but for now we
397 // just do what we can.
398 // If the block is declared without an explicit argument list, the
399 // signature-as-written just includes the return type, not the entire
400 // function type.
401 // FIXME: All blocks should have signatures-as-written, even if the return
402 // type is inferred. (That's signified with a dependent result type.)
403 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
404 QualType Ty = TSI->getType();
405 if (const FunctionType *FT = Ty->getAs<FunctionType>())
406 Ty = FT->getReturnType();
407 if (!Ty->isDependentType())
408 return Ty;
409 }
410
411 return {};
412 }
413
414 llvm_unreachable("unknown callable kind");
415}
416
418 assert(D);
419
420 if (const auto *FD = dyn_cast<FunctionDecl>(D))
421 return FD->isVariadic();
422 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
423 return MD->isVariadic();
424 if (const auto *BD = dyn_cast<BlockDecl>(D))
425 return BD->isVariadic();
426
427 llvm_unreachable("unknown callable kind");
428}
429
431 const RecordType *UT = T->getAsUnionType();
432 return UT &&
433 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>();
434}
435
436// In some cases, symbolic cases should be transformed before we associate
437// them with parameters. This function incapsulates such cases.
438static SVal processArgument(SVal Value, const Expr *ArgumentExpr,
439 const ParmVarDecl *Parameter, SValBuilder &SVB) {
440 QualType ParamType = Parameter->getType();
441 QualType ArgumentType = ArgumentExpr->getType();
442
443 // Transparent unions allow users to easily convert values of union field
444 // types into union-typed objects.
445 //
446 // Also, more importantly, they allow users to define functions with different
447 // different parameter types, substituting types matching transparent union
448 // field types with the union type itself.
449 //
450 // Here, we check specifically for latter cases and prevent binding
451 // field-typed values to union-typed regions.
452 if (isTransparentUnion(ParamType) &&
453 // Let's check that we indeed trying to bind different types.
454 !isTransparentUnion(ArgumentType)) {
456
457 llvm::ImmutableList<SVal> CompoundSVals = BVF.getEmptySValList();
458 CompoundSVals = BVF.prependSVal(Value, CompoundSVals);
459
460 // Wrap it with compound value.
461 return SVB.makeCompoundVal(ParamType, CompoundSVals);
462 }
463
464 return Value;
465}
466
467/// Cast the argument value to the type of the parameter at the function
468/// declaration.
469/// Returns the argument value if it didn't need a cast.
470/// Or returns the cast argument if it needed a cast.
471/// Or returns 'Unknown' if it would need a cast but the callsite and the
472/// runtime definition don't match in terms of argument and parameter count.
473static SVal castArgToParamTypeIfNeeded(const CallEvent &Call, unsigned ArgIdx,
474 SVal ArgVal, SValBuilder &SVB) {
475 const auto *CallExprDecl = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
476 if (!CallExprDecl)
477 return ArgVal;
478
479 const FunctionDecl *Definition = CallExprDecl;
480 Definition->hasBody(Definition);
481
482 // The function decl of the Call (in the AST) will not have any parameter
483 // declarations, if it was 'only' declared without a prototype. However, the
484 // engine will find the appropriate runtime definition - basically a
485 // redeclaration, which has a function body (and a function prototype).
486 if (CallExprDecl->hasPrototype() || !Definition->hasPrototype())
487 return ArgVal;
488
489 // Only do this cast if the number arguments at the callsite matches with
490 // the parameters at the runtime definition.
491 if (Call.getNumArgs() != Definition->getNumParams())
492 return UnknownVal();
493
494 const Expr *ArgExpr = Call.getArgExpr(ArgIdx);
495 const ParmVarDecl *Param = Definition->getParamDecl(ArgIdx);
496 return SVB.evalCast(ArgVal, Param->getType(), ArgExpr->getType());
497}
498
499static void addParameterValuesToBindings(const StackFrame *CalleeSF,
501 SValBuilder &SVB,
502 const CallEvent &Call,
503 ArrayRef<ParmVarDecl *> parameters) {
504 MemRegionManager &MRMgr = SVB.getRegionManager();
505
506 // If the function has fewer parameters than the call has arguments, we simply
507 // do not bind any values to them.
508 unsigned NumArgs = Call.getNumArgs();
509 unsigned Idx = 0;
510 ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end();
511 for (; I != E && Idx < NumArgs; ++I, ++Idx) {
512 assert(*I && "Formal parameter has no decl?");
513
514 // TODO: Support allocator calls.
515 if (Call.getKind() != CE_CXXAllocator)
516 if (Call.isArgumentConstructedDirectly(Call.getASTArgumentIndex(Idx)))
517 continue;
518
519 // TODO: Allocators should receive the correct size and possibly alignment,
520 // determined in compile-time but not represented as arg-expressions,
521 // which makes getArgSVal() fail and return UnknownVal.
522 SVal ArgVal = Call.getArgSVal(Idx);
523 const Expr *ArgExpr = Call.getArgExpr(Idx);
524
525 if (ArgVal.isUnknown())
526 continue;
527
528 // Cast the argument value to match the type of the parameter in some
529 // edge-cases.
530 ArgVal = castArgToParamTypeIfNeeded(Call, Idx, ArgVal, SVB);
531
532 Loc ParamLoc = SVB.makeLoc(
533 MRMgr.getParamVarRegion(Call.getOriginExpr(), Idx, CalleeSF));
534 Bindings.push_back(
535 std::make_pair(ParamLoc, processArgument(ArgVal, ArgExpr, *I, SVB)));
536 }
537
538 // FIXME: Variadic arguments are not handled at all right now.
539}
540
543 if (!StackFrame)
544 return nullptr;
545
547 if (const auto Ctor = Element.getAs<CFGConstructor>()) {
548 return Ctor->getConstructionContext();
549 }
550
551 if (const auto RecCall = Element.getAs<CFGCXXRecordTypedCall>()) {
552 return RecCall->getConstructionContext();
553 }
554
555 return nullptr;
556}
557
559 const auto *CallSF = this->getStackFrame();
560 if (!CallSF || CallSF->inTopFrame())
561 return nullptr;
562
563 CallEventManager &CEMgr = State->getStateManager().getCallEventManager();
564 return CEMgr.getCaller(CallSF, State);
565}
566
568 if (const CallEventRef<> Caller = getCaller())
569 return Caller->isInSystemHeader();
570
571 return false;
572}
573
575 const auto *CC = getConstructionContext();
576 if (!CC)
577 return std::nullopt;
578
579 EvalCallOptions CallOpts;
580 ExprEngine &Engine = getState()->getStateManager().getOwningEngine();
581 unsigned NumVisitedCall =
582 Engine.getNumVisited(getStackFrame(), getCFGElementRef().getParent());
583 SVal RetVal = Engine.computeObjectUnderConstruction(
584 getOriginExpr(), getState(), NumVisitedCall, getStackFrame(), CC,
585 CallOpts);
586 return RetVal;
587}
588
590 const FunctionDecl *D = getDecl();
591 if (!D)
592 return {};
593 return D->parameters();
594}
595
597 const FunctionDecl *FD = getDecl();
598 if (!FD)
599 return {};
600
601 // Note that the AnalysisDeclContext will have the FunctionDecl with
602 // the definition (if one exists).
605 bool IsAutosynthesized;
606 Stmt* Body = AD->getBody(IsAutosynthesized);
607 LLVM_DEBUG({
608 if (IsAutosynthesized)
609 llvm::dbgs() << "Using autosynthesized body for " << FD->getName()
610 << "\n";
611 });
612
613 ExprEngine &Engine = getState()->getStateManager().getOwningEngine();
615 *Engine.getCrossTranslationUnitContext();
616
617 AnalyzerOptions &Opts = Engine.getAnalysisManager().options;
618
619 if (Body) {
620 const Decl* Decl = AD->getDecl();
621 if (Opts.IsNaiveCTUEnabled && CTUCtx.isImportedAsNew(Decl)) {
622 // A newly created definition, but we had error(s) during the import.
623 if (CTUCtx.hasError(Decl))
624 return {};
625 return RuntimeDefinition(Decl, /*Foreign=*/true);
626 }
627 return RuntimeDefinition(Decl, /*Foreign=*/false);
628 }
629
630 // Try to get CTU definition only if CTUDir is provided.
631 if (!Opts.IsNaiveCTUEnabled)
632 return {};
633
635 CTUCtx.getCrossTUDefinition(FD, Opts.CTUDir, Opts.CTUIndexName,
636 Opts.DisplayCTUProgress);
637
638 if (!CTUDeclOrError) {
639 handleAllErrors(CTUDeclOrError.takeError(),
640 [&](const cross_tu::IndexError &IE) {
641 auto Loc = getOriginExpr() ? getOriginExpr()->getExprLoc()
642 : FD->getLocation();
643 CTUCtx.emitCrossTUDiagnostics(IE, Loc);
644 });
645 return {};
646 }
647
648 return RuntimeDefinition(*CTUDeclOrError, /*Foreign=*/true);
649}
650
652 BindingsTy &Bindings) const {
653 const auto *D = cast<FunctionDecl>(CalleeSF->getDecl());
654 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
655 addParameterValuesToBindings(CalleeSF, Bindings, SVB, *this, D->parameters());
656}
657
660 return true;
661
662 const FunctionDecl *D = getDecl();
663 if (!D)
664 return true;
665
666 const IdentifierInfo *II = D->getIdentifier();
667 if (!II)
668 return false;
669
670 // This set of "escaping" APIs is
671
672 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
673 // value into thread local storage. The value can later be retrieved with
674 // 'void *ptheread_getspecific(pthread_key)'. So even thought the
675 // parameter is 'const void *', the region escapes through the call.
676 if (II->isStr("pthread_setspecific"))
677 return true;
678
679 // - xpc_connection_set_context stores a value which can be retrieved later
680 // with xpc_connection_get_context.
681 if (II->isStr("xpc_connection_set_context"))
682 return true;
683
684 // - funopen - sets a buffer for future IO calls.
685 if (II->isStr("funopen"))
686 return true;
687
688 // - __cxa_demangle - can reallocate memory and can return the pointer to
689 // the input buffer.
690 if (II->isStr("__cxa_demangle"))
691 return true;
692
693 StringRef FName = II->getName();
694
695 // - CoreFoundation functions that end with "NoCopy" can free a passed-in
696 // buffer even if it is const.
697 if (FName.ends_with("NoCopy"))
698 return true;
699
700 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
701 // be deallocated by NSMapRemove.
702 if (FName.starts_with("NS") && FName.contains("Insert"))
703 return true;
704
705 // - Many CF containers allow objects to escape through custom
706 // allocators/deallocators upon container construction. (PR12101)
707 if (FName.starts_with("CF") || FName.starts_with("CG")) {
708 return FName.contains_insensitive("InsertValue") ||
709 FName.contains_insensitive("AddValue") ||
710 FName.contains_insensitive("SetValue") ||
711 FName.contains_insensitive("WithData") ||
712 FName.contains_insensitive("AppendValue") ||
713 FName.contains_insensitive("SetAttribute");
714 }
715
716 return false;
717}
718
721 if (D)
722 return D;
723
725}
726
728 // Clang converts lambdas to function pointers using an implicit conversion
729 // operator, which returns the lambda's '__invoke' method. However, Sema
730 // leaves the body of '__invoke' empty (it is generated later in CodeGen), so
731 // we need to skip '__invoke' and access the lambda's operator() directly.
732 if (const auto *CMD = dyn_cast_if_present<CXXMethodDecl>(getDecl());
733 CMD && CMD->isLambdaStaticInvoker())
734 return RuntimeDefinition{CMD->getParent()->getLambdaCallOperator()};
735
737}
738
740 const auto *CE = cast_or_null<CallExpr>(getOriginExpr());
741 if (!CE)
743
744 const FunctionDecl *D = CE->getDirectCallee();
745 if (D)
746 return D;
747
748 return getSVal(CE->getCallee()).getAsFunctionDecl();
749}
750
752 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
753 SVal ThisVal = getCXXThisVal();
754 Values.push_back(ThisVal);
755
756 // Don't invalidate if the method is const and there are no mutable fields.
757 if (const auto *D = cast_or_null<CXXMethodDecl>(getDecl())) {
758 if (!D->isConst())
759 return;
760
761 // Get the record decl for the class of 'This'. D->getParent() may return
762 // a base class decl, rather than the class of the instance which needs to
763 // be checked for mutable fields.
764 const CXXRecordDecl *ParentRecord = getDeclForDynamicType().first;
765 if (!ParentRecord || !ParentRecord->hasDefinition())
766 return;
767
768 if (ParentRecord->hasMutableFields())
769 return;
770
771 // Preserve CXXThis.
772 const MemRegion *ThisRegion = ThisVal.getAsRegion();
773 if (!ThisRegion)
774 return;
775
776 ETraits->setTrait(ThisRegion->getBaseRegion(),
778 }
779}
780
782 const Expr *Base = getCXXThisExpr();
783 // FIXME: This doesn't handle an overloaded ->* operator.
784 SVal ThisVal = Base ? getSVal(Base) : UnknownVal();
785
786 if (isa<NonLoc>(ThisVal)) {
787 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
788 QualType OriginalTy = ThisVal.getType(SVB.getContext());
789 return SVB.evalCast(ThisVal, Base->getType(), OriginalTy);
790 }
791
792 assert(ThisVal.isUnknownOrUndef() || isa<Loc>(ThisVal));
793 return ThisVal;
794}
795
796std::pair<const CXXRecordDecl *, bool>
798 const MemRegion *R = getCXXThisVal().getAsRegion();
799 if (!R)
800 return {};
801
803 if (!DynType.isValid())
804 return {};
805
806 assert(!DynType.getType()->getPointeeType().isNull());
807 return {DynType.getType()->getPointeeCXXRecordDecl(),
808 DynType.canBeASubClass()};
809}
810
812 // Do we have a decl at all?
813 const Decl *D = getDecl();
814 if (!D)
815 return {};
816
817 // If the method is non-virtual, we know we can inline it.
818 const auto *MD = cast<CXXMethodDecl>(D);
819 if (!MD->isVirtual())
821
822 // If the method is final or declared in a final class, we can inline it.
823 if (MD->hasAttr<FinalAttr>() || MD->getParent()->hasAttr<FinalAttr>())
825
826 auto [RD, CanBeSubClass] = getDeclForDynamicType();
827 if (!RD || !RD->hasDefinition())
828 return {};
829
830 // We can confidently inline a method called on an object with final type.
831 if (RD->hasAttr<FinalAttr>())
832 CanBeSubClass = false;
833
834 // Find the decl for this method in that class.
835 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
836 if (!Result) {
837 // We might not even get the original statically-resolved method due to
838 // some particularly nasty casting (e.g. casts to sister classes).
839 // However, we should at least be able to search up and down our own class
840 // hierarchy, and some real bugs have been caught by checking this.
841 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
842
843 // FIXME: This is checking that our DynamicTypeInfo is at least as good as
844 // the static type. However, because we currently don't update
845 // DynamicTypeInfo when an object is cast, we can't actually be sure the
846 // DynamicTypeInfo is up to date. This assert should be re-enabled once
847 // this is fixed.
848 //
849 // assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
850
851 return {};
852 }
853
854 // A final method cannot be overriden in a subclass.
855 if (Result->hasAttr<FinalAttr>())
856 CanBeSubClass = false;
857
858 // Does the decl that we found have an implementation?
860 if (!Result->hasBody(Definition)) {
861 if (!CanBeSubClass)
863 return {};
864 }
865
866 // We found a definition. If we're not sure that this devirtualization is
867 // actually what will happen at runtime, make sure to provide the region so
868 // that ExprEngine can decide what to do with it.
869 if (CanBeSubClass)
871 getCXXThisVal().getAsRegion()->StripCasts());
872 return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
873}
874
876 BindingsTy &Bindings) const {
878
879 // Handle the binding of 'this' in the new stack frame.
880 SVal ThisVal = getCXXThisVal();
881 if (!ThisVal.isUnknown()) {
882 ProgramStateManager &StateMgr = getState()->getStateManager();
883 SValBuilder &SVB = StateMgr.getSValBuilder();
884
885 const auto *MD = cast<CXXMethodDecl>(CalleeSF->getDecl());
886 Loc ThisLoc = SVB.getCXXThis(MD, CalleeSF);
887
888 // If we devirtualized to a different member function, we need to make sure
889 // we have the proper layering of CXXBaseObjectRegions.
890 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
891 ASTContext &Ctx = SVB.getContext();
892 const CXXRecordDecl *Class = MD->getParent();
894
895 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
896 std::optional<SVal> V =
897 StateMgr.getStoreManager().evalBaseToDerived(ThisVal, Ty);
898 if (!V) {
899 // We might have suffered some sort of placement new earlier, so
900 // we're constructing in a completely unexpected storage.
901 // Fall back to a generic pointer cast for this-value.
902 const CXXMethodDecl *StaticMD = cast<CXXMethodDecl>(getDecl());
903 const CXXRecordDecl *StaticClass = StaticMD->getParent();
904 CanQualType StaticTy =
905 Ctx.getPointerType(Ctx.getCanonicalTagType(StaticClass));
906 ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy);
907 } else
908 ThisVal = *V;
909 }
910
911 if (!ThisVal.isUnknown())
912 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
913 }
914}
915
919
921 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
922 // id-expression in the class member access expression is a qualified-id,
923 // that function is called. Otherwise, its final overrider in the dynamic type
924 // of the object expression is called.
925 if (const auto *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
926 if (ME->hasQualifier())
928
930}
931
933 return getOriginExpr()->getArg(0);
934}
935
937 const Expr *Callee = getOriginExpr()->getCallee();
938 const MemRegion *DataReg = getSVal(Callee).getAsRegion();
939
940 return dyn_cast_or_null<BlockDataRegion>(DataReg);
941}
942
944 const BlockDecl *D = getDecl();
945 if (!D)
946 return {};
947 return D->parameters();
948}
949
951 RegionAndSymbolInvalidationTraits *ETraits) const {
952 // FIXME: This also needs to invalidate captured globals.
953 if (const MemRegion *R = getBlockRegion())
954 Values.push_back(loc::MemRegionVal(R));
955}
956
958 BindingsTy &Bindings) const {
959 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
962 auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeSF->getDecl());
963 Params = LambdaOperatorDecl->parameters();
964
965 // For blocks converted from a C++ lambda, the callee declaration is the
966 // operator() method on the lambda so we bind "this" to
967 // the lambda captured by the block.
968 const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
969 SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
970 Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeSF);
971 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
972 } else {
973 Params = cast<BlockDecl>(CalleeSF->getDecl())->parameters();
974 }
975
976 addParameterValuesToBindings(CalleeSF, Bindings, SVB, *this, Params);
977}
978
980 if (Data)
981 return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
982 return UnknownVal();
983}
984
986 RegionAndSymbolInvalidationTraits *ETraits) const {
987 SVal V = getCXXThisVal();
988 if (SymbolRef Sym = V.getAsSymbol(true))
989 ETraits->setTrait(Sym,
991
992 // Standard classes don't reinterpret-cast and modify super regions.
993 const bool IsStdClassCtor = isWithinStdNamespace(getDecl());
994 if (const MemRegion *Obj = V.getAsRegion(); Obj && IsStdClassCtor) {
995 ETraits->setTrait(
997 }
998
999 Values.push_back(V);
1000}
1001
1003 const StackFrame *CalleeSF, BindingsTy &Bindings) const {
1005
1006 SVal ThisVal = getCXXThisVal();
1007 if (!ThisVal.isUnknown()) {
1008 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
1009 const auto *MD = cast<CXXMethodDecl>(CalleeSF->getDecl());
1010 Loc ThisLoc = SVB.getCXXThis(MD, CalleeSF);
1011 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
1012 }
1013}
1014
1016 const StackFrame *SF = getStackFrame();
1017 while (isa<CXXInheritedCtorInitExpr>(SF->getCallSite()))
1018 SF = SF->getParent();
1019 return SF;
1020}
1021
1023 if (Data)
1024 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
1025 return UnknownVal();
1026}
1027
1029 // Base destructors are always called non-virtually.
1030 // Skip CXXInstanceCall's devirtualization logic in this case.
1031 if (isBaseDestructor())
1033
1035}
1036
1038 const ObjCMethodDecl *D = getDecl();
1039 if (!D)
1040 return {};
1041 return D->parameters();
1042}
1043
1045 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
1046
1047 // If the method call is a setter for property known to be backed by
1048 // an instance variable, don't invalidate the entire receiver, just
1049 // the storage for that instance variable.
1050 if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
1051 if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
1052 SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
1053 if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) {
1054 ETraits->setTrait(
1055 IvarRegion,
1057 ETraits->setTrait(
1058 IvarRegion,
1060 Values.push_back(IvarLVal);
1061 }
1062 return;
1063 }
1064 }
1065
1066 Values.push_back(getReceiverSVal());
1067}
1068
1070 // FIXME: Is this the best way to handle class receivers?
1071 if (!isInstanceMessage())
1072 return UnknownVal();
1073
1074 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
1075 return getSVal(RecE);
1076
1077 // An instance message with no expression means we are sending to super.
1078 // In this case the object reference is the same as 'self'.
1079 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
1080 SVal SelfVal = getState()->getSelfSVal(getStackFrame());
1081 assert(SelfVal.isValid() && "Calling super but not in ObjC method");
1082 return SelfVal;
1083}
1084
1086 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
1087 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
1088 return true;
1089
1090 if (!isInstanceMessage())
1091 return false;
1092
1093 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
1094 SVal SelfVal = getState()->getSelfSVal(getStackFrame());
1095
1096 return (RecVal == SelfVal);
1097}
1098
1100 switch (getMessageKind()) {
1101 case OCM_Message:
1102 return getOriginExpr()->getSourceRange();
1103 case OCM_PropertyAccess:
1104 case OCM_Subscript:
1105 return getContainingPseudoObjectExpr()->getSourceRange();
1106 }
1107 llvm_unreachable("unknown message kind");
1108}
1109
1110using ObjCMessageDataTy = llvm::PointerIntPair<const PseudoObjectExpr *, 2>;
1111
1112const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
1113 assert(Data && "Lazy lookup not yet performed.");
1114 assert(getMessageKind() != OCM_Message && "Explicit message send.");
1115 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
1116}
1117
1118static const Expr *
1120 const Expr *Syntactic = POE->getSyntacticForm()->IgnoreParens();
1121
1122 // This handles the funny case of assigning to the result of a getter.
1123 // This can happen if the getter returns a non-const reference.
1124 if (const auto *BO = dyn_cast<BinaryOperator>(Syntactic))
1125 Syntactic = BO->getLHS()->IgnoreParens();
1126
1127 return Syntactic;
1128}
1129
1131 if (!Data) {
1132 // Find the parent, ignoring implicit casts.
1133 const ParentMap &PM = getStackFrame()->getParentMap();
1135
1136 // Check if parent is a PseudoObjectExpr.
1137 if (const auto *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
1138 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
1139
1141 switch (Syntactic->getStmtClass()) {
1142 case Stmt::ObjCPropertyRefExprClass:
1144 break;
1145 case Stmt::ObjCSubscriptRefExprClass:
1146 K = OCM_Subscript;
1147 break;
1148 default:
1149 // FIXME: Can this ever happen?
1150 K = OCM_Message;
1151 break;
1152 }
1153
1154 if (K != OCM_Message) {
1155 const_cast<ObjCMethodCall *>(this)->Data
1156 = ObjCMessageDataTy(POE, K).getOpaqueValue();
1157 assert(getMessageKind() == K);
1158 return K;
1159 }
1160 }
1161
1162 const_cast<ObjCMethodCall *>(this)->Data
1163 = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
1164 assert(getMessageKind() == OCM_Message);
1165 return OCM_Message;
1166 }
1167
1168 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
1169 if (!Info.getPointer())
1170 return OCM_Message;
1171 return static_cast<ObjCMessageKind>(Info.getInt());
1172}
1173
1175 // Look for properties accessed with property syntax (foo.bar = ...)
1177 const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
1178 assert(POE && "Property access without PseudoObjectExpr?");
1179
1180 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
1181 auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
1182
1183 if (RefExpr->isExplicitProperty())
1184 return RefExpr->getExplicitProperty();
1185 }
1186
1187 // Look for properties accessed with method syntax ([foo setBar:...]).
1188 const ObjCMethodDecl *MD = getDecl();
1189 if (!MD || !MD->isPropertyAccessor())
1190 return nullptr;
1191
1192 // Note: This is potentially quite slow.
1193 return MD->findPropertyDecl();
1194}
1195
1197 Selector Sel) const {
1198 assert(IDecl);
1199 AnalysisManager &AMgr =
1200 getState()->getStateManager().getOwningEngine().getAnalysisManager();
1201 // If the class interface is declared inside the main file, assume it is not
1202 // subcassed.
1203 // TODO: It could actually be subclassed if the subclass is private as well.
1204 // This is probably very rare.
1205 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
1206 if (InterfLoc.isValid() && AMgr.isInCodeFile(InterfLoc))
1207 return false;
1208
1209 // Assume that property accessors are not overridden.
1211 return false;
1212
1213 // We assume that if the method is public (declared outside of main file) or
1214 // has a parent which publicly declares the method, the method could be
1215 // overridden in a subclass.
1216
1217 // Find the first declaration in the class hierarchy that declares
1218 // the selector.
1219 ObjCMethodDecl *D = nullptr;
1220 while (true) {
1221 D = IDecl->lookupMethod(Sel, true);
1222
1223 // Cannot find a public definition.
1224 if (!D)
1225 return false;
1226
1227 // If outside the main file,
1228 if (D->getLocation().isValid() && !AMgr.isInCodeFile(D->getLocation()))
1229 return true;
1230
1231 if (D->isOverriding()) {
1232 // Search in the superclass on the next iteration.
1233 IDecl = D->getClassInterface();
1234 if (!IDecl)
1235 return false;
1236
1237 IDecl = IDecl->getSuperClass();
1238 if (!IDecl)
1239 return false;
1240
1241 continue;
1242 }
1243
1244 return false;
1245 };
1246
1247 llvm_unreachable("The while loop should always terminate.");
1248}
1249
1251 if (!MD)
1252 return MD;
1253
1254 // Find the redeclaration that defines the method.
1255 if (!MD->hasBody()) {
1256 for (auto *I : MD->redecls())
1257 if (I->hasBody())
1258 MD = cast<ObjCMethodDecl>(I);
1259 }
1260 return MD;
1261}
1262
1268
1269namespace llvm {
1270template <> struct DenseMapInfo<PrivateMethodKey> {
1271 using InterfaceInfo = DenseMapInfo<const ObjCInterfaceDecl *>;
1272 using SelectorInfo = DenseMapInfo<Selector>;
1273
1274 static unsigned getHashValue(const PrivateMethodKey &Key) {
1275 return llvm::hash_combine(
1276 llvm::hash_code(InterfaceInfo::getHashValue(Key.Interface)),
1277 llvm::hash_code(SelectorInfo::getHashValue(Key.LookupSelector)),
1278 Key.IsClassMethod);
1279 }
1280
1281 static bool isEqual(const PrivateMethodKey &LHS,
1282 const PrivateMethodKey &RHS) {
1283 return InterfaceInfo::isEqual(LHS.Interface, RHS.Interface) &&
1284 SelectorInfo::isEqual(LHS.LookupSelector, RHS.LookupSelector) &&
1285 LHS.IsClassMethod == RHS.IsClassMethod;
1286 }
1287};
1288} // end namespace llvm
1289
1290// NOTE: This cache is a "global" variable, and it is cleared by
1291// CallEventManager's constructor so we do not keep old entries when
1292// loading/unloading ASTs. If we are worried about concurrency, we may need to
1293// revisit this someday. In terms of memory, this table stays around until clang
1294// quits, which also may be bad if we need to release memory.
1296 llvm::DenseMap<PrivateMethodKey, std::optional<const ObjCMethodDecl *>>;
1298
1299static const ObjCMethodDecl *
1301 Selector LookupSelector, bool InstanceMethod) {
1302 // Repeatedly calling lookupPrivateMethod() is expensive, especially
1303 // when in many cases it returns null. We cache the results so
1304 // that repeated queries on the same ObjCIntefaceDecl and Selector
1305 // don't incur the same cost. On some test cases, we can see the
1306 // same query being issued thousands of times.
1307 std::optional<const ObjCMethodDecl *> &Val =
1308 PrivateMethodCache[{Interface, LookupSelector, InstanceMethod}];
1309
1310 // Query lookupPrivateMethod() if the cache does not hit.
1311 if (!Val) {
1312 Val = Interface->lookupPrivateMethod(LookupSelector, InstanceMethod);
1313
1314 if (!*Val) {
1315 // Query 'lookupMethod' as a backup.
1316 Val = Interface->lookupMethod(LookupSelector, InstanceMethod);
1317 }
1318 }
1319
1320 return *Val;
1321}
1322
1324 const ObjCMessageExpr *E = getOriginExpr();
1325 assert(E);
1326 Selector Sel = E->getSelector();
1327
1328 if (E->isInstanceMessage()) {
1329 // Find the receiver type.
1330 const ObjCObjectType *ReceiverT = nullptr;
1331 bool CanBeSubClassed = false;
1332 bool LookingForInstanceMethod = true;
1333 QualType SupersType = E->getSuperType();
1334 const MemRegion *Receiver = nullptr;
1335
1336 if (!SupersType.isNull()) {
1337 // The receiver is guaranteed to be 'super' in this case.
1338 // Super always means the type of immediate predecessor to the method
1339 // where the call occurs.
1340 ReceiverT = cast<ObjCObjectPointerType>(SupersType)->getObjectType();
1341 } else {
1342 Receiver = getReceiverSVal().getAsRegion();
1343 if (!Receiver)
1344 return {};
1345
1346 DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
1347 if (!DTI.isValid()) {
1348 assert(isa<AllocaRegion>(Receiver) &&
1349 "Unhandled untyped region class!");
1350 return {};
1351 }
1352
1353 QualType DynType = DTI.getType();
1354 CanBeSubClassed = DTI.canBeASubClass();
1355
1356 const auto *ReceiverDynT =
1357 dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType());
1358
1359 if (ReceiverDynT) {
1360 ReceiverT = ReceiverDynT->getObjectType();
1361
1362 // It can be actually class methods called with Class object as a
1363 // receiver. This type of messages is treated by the compiler as
1364 // instance (not class).
1365 if (ReceiverT->isObjCClass()) {
1366
1367 SVal SelfVal = getState()->getSelfSVal(getStackFrame());
1368 // For [self classMethod], return compiler visible declaration.
1369 if (Receiver == SelfVal.getAsRegion()) {
1371 }
1372
1373 // Otherwise, let's check if we know something about the type
1374 // inside of this class object.
1375 if (SymbolRef ReceiverSym = getReceiverSVal().getAsSymbol()) {
1376 DynamicTypeInfo DTI =
1378 if (DTI.isValid()) {
1379 // Let's use this type for lookup.
1380 ReceiverT =
1382
1383 CanBeSubClassed = DTI.canBeASubClass();
1384 // And it should be a class method instead.
1385 LookingForInstanceMethod = false;
1386 }
1387 }
1388 }
1389
1390 if (CanBeSubClassed)
1391 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface())
1392 // Even if `DynamicTypeInfo` told us that it can be
1393 // not necessarily this type, but its descendants, we still want
1394 // to check again if this selector can be actually overridden.
1395 CanBeSubClassed = canBeOverridenInSubclass(IDecl, Sel);
1396 }
1397 }
1398
1399 // Lookup the instance method implementation.
1400 if (ReceiverT)
1401 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface()) {
1402 const ObjCMethodDecl *MD =
1403 lookupRuntimeDefinition(IDecl, Sel, LookingForInstanceMethod);
1404
1405 if (MD && !MD->hasBody())
1406 MD = MD->getCanonicalDecl();
1407
1408 if (CanBeSubClassed)
1409 return RuntimeDefinition(MD, Receiver);
1410 else
1411 return RuntimeDefinition(MD, nullptr);
1412 }
1413 } else {
1414 // This is a class method.
1415 // If we have type info for the receiver class, we are calling via
1416 // class name.
1417 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
1418 // Find/Return the method implementation.
1419 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
1420 }
1421 }
1422
1423 return {};
1424}
1425
1427 if (isInSystemHeader() && !isInstanceMessage()) {
1428 Selector Sel = getSelector();
1429 if (Sel.getNumArgs() == 1 &&
1430 Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
1431 return true;
1432 }
1433
1435}
1436
1438 BindingsTy &Bindings) const {
1439 const auto *D = cast<ObjCMethodDecl>(CalleeSF->getDecl());
1440 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
1441 addParameterValuesToBindings(CalleeSF, Bindings, SVB, *this, D->parameters());
1442
1443 SVal SelfVal = getReceiverSVal();
1444 if (!SelfVal.isUnknown()) {
1445 const VarDecl *SelfD = CalleeSF->getAnalysisDeclContext()->getSelfDecl();
1446 MemRegionManager &MRMgr = SVB.getRegionManager();
1447 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeSF));
1448 Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
1449 }
1450}
1451
1452CallEventManager::CallEventManager(llvm::BumpPtrAllocator &alloc)
1453 : Alloc(alloc) {
1454 // Clear the method cache to avoid hits when multiple AST are loaded/unloaded
1455 // within a single process. This can happen with unit tests, for instance.
1456 PrivateMethodCache.clear();
1457}
1458
1461 const StackFrame *SF,
1463 if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(CE))
1464 return create<CXXMemberCall>(MCE, State, SF, ElemRef);
1465
1466 if (const auto *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
1467 const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
1468 if (const auto *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) {
1469 if (MD->isImplicitObjectMemberFunction())
1470 return create<CXXMemberOperatorCall>(OpCE, State, SF, ElemRef);
1471 if (MD->isStatic())
1472 return create<CXXStaticOperatorCall>(OpCE, State, SF, ElemRef);
1473 }
1474
1475 } else if (CE->getCallee()->getType()->isBlockPointerType()) {
1476 return create<BlockCall>(CE, State, SF, ElemRef);
1477 }
1478
1479 // Otherwise, it's a normal function call, static member function call, or
1480 // something we can't reason about.
1481 return create<SimpleFunctionCall>(CE, State, SF, ElemRef);
1482}
1483
1485 ProgramStateRef State) {
1486 const StackFrame *ParentSF = CalleeSF->getParent();
1487 const StackFrame *CallerSF = ParentSF;
1488 CFGBlock::ConstCFGElementRef ElemRef = {CalleeSF->getCallSiteBlock(),
1489 CalleeSF->getIndex()};
1490 assert(CallerSF && "This should not be used for top-level stack frames");
1491
1492 const Expr *CallSite = CalleeSF->getCallSite();
1493
1494 if (CallSite) {
1495 if (CallEventRef<> Out = getCall(CallSite, State, CallerSF, ElemRef))
1496 return Out;
1497
1498 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1499 const auto *Ctor = cast<CXXMethodDecl>(CalleeSF->getDecl());
1500 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeSF);
1501 SVal ThisVal = State->getSVal(ThisPtr);
1502
1503 if (const auto *CE = dyn_cast<CXXConstructExpr>(CallSite))
1504 return getCXXConstructorCall(CE, ThisVal.getAsRegion(), State, CallerSF,
1505 ElemRef);
1506 if (const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(CallSite))
1507 return getCXXInheritedConstructorCall(CIE, ThisVal.getAsRegion(), State,
1508 CallerSF, ElemRef);
1509 // All other cases are handled by getCall.
1510 llvm_unreachable("This is not an inlineable statement");
1511 }
1512
1513 // Fall back to the CFG. The only thing we haven't handled yet is
1514 // destructors, though this could change in the future.
1515 const CFGBlock *B = CalleeSF->getCallSiteBlock();
1516 CFGElement E = (*B)[CalleeSF->getIndex()];
1517 assert((E.getAs<CFGImplicitDtor>() || E.getAs<CFGTemporaryDtor>()) &&
1518 "All other CFG elements should have exprs");
1519
1520 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1521 const auto *Dtor = cast<CXXDestructorDecl>(CalleeSF->getDecl());
1522 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeSF);
1523 SVal ThisVal = State->getSVal(ThisPtr);
1524
1525 const Stmt *Trigger;
1526 if (std::optional<CFGAutomaticObjDtor> AutoDtor =
1528 Trigger = AutoDtor->getTriggerStmt();
1529 else if (std::optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
1530 Trigger = DeleteDtor->getDeleteExpr();
1531 else
1532 Trigger = Dtor->getBody();
1533
1534 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
1535 E.getAs<CFGBaseDtor>().has_value(), State,
1536 CallerSF, ElemRef);
1537}
1538
1540 const StackFrame *SF,
1542 if (const auto *CE = dyn_cast<CallExpr>(S)) {
1543 return getSimpleCall(CE, State, SF, ElemRef);
1544 } else if (const auto *NE = dyn_cast<CXXNewExpr>(S)) {
1545 return getCXXAllocatorCall(NE, State, SF, ElemRef);
1546 } else if (const auto *DE = dyn_cast<CXXDeleteExpr>(S)) {
1547 return getCXXDeallocatorCall(DE, State, SF, ElemRef);
1548 } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1549 return getObjCMethodCall(ME, State, SF, ElemRef);
1550 } else {
1551 return nullptr;
1552 }
1553}
Defines the clang::ASTContext interface.
#define V(N, I)
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static bool isZeroConstant(const llvm::Value *Value)
static bool isVoidPointerToNonConst(QualType T)
static const ObjCMethodDecl * findDefiningRedecl(const ObjCMethodDecl *MD)
static const ObjCMethodDecl * lookupRuntimeDefinition(const ObjCInterfaceDecl *Interface, Selector LookupSelector, bool InstanceMethod)
static const MemRegion * getThisRegionBaseOrNull(const CallEvent &Call)
static const Expr * getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE)
static bool isTransparentUnion(QualType T)
llvm::PointerIntPair< const PseudoObjectExpr *, 2 > ObjCMessageDataTy
static bool isCallback(QualType T)
Definition CallEvent.cpp:79
static SVal castArgToParamTypeIfNeeded(const CallEvent &Call, unsigned ArgIdx, SVal ArgVal, SValBuilder &SVB)
Cast the argument value to the type of the parameter at the function declaration.
llvm::DenseMap< PrivateMethodKey, std::optional< const ObjCMethodDecl * > > PrivateMethodCacheTy
static SVal processArgument(SVal Value, const Expr *ArgumentExpr, const ParmVarDecl *Parameter, SValBuilder &SVB)
static PrivateMethodCacheTy PrivateMethodCache
static void findPtrToConstParams(llvm::SmallSet< unsigned, 4 > &PreserveArgs, const CallEvent &Call)
static void addParameterValuesToBindings(const StackFrame *CalleeSF, CallEvent::BindingsTy &Bindings, SValBuilder &SVB, const CallEvent &Call, ArrayRef< ParmVarDecl * > parameters)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
C Language Family Type Representation.
static bool isPointerToConst(const QualType &QT)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:915
CanQualType VoidTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
AnalysisDeclContext * getContext(const Decl *D)
AnalysisDeclContext contains the context data for the function, method or block under analysis.
const ImplicitParamDecl * getSelfDecl() const
AnalysisDeclContextManager * getManager() const
const StackFrame * getStackFrame(const StackFrame *ParentSF, const void *Data, const Expr *E, const CFGBlock *Blk, unsigned BlockCount, unsigned Index)
Obtain a context of the call stack using its parent context.
Stores options for the analyzer from the command line.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4862
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4951
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Definition CFG.h:464
Represents C++ object destructor implicitly generated for base object in destructor.
Definition CFG.h:515
Represents a single basic block in a source-level CFG.
Definition CFG.h:651
unsigned size() const
Definition CFG.h:1007
ElementRefImpl< true > ConstCFGElementRef
Definition CFG.h:976
Represents a function call that returns a C++ object by value.
Definition CFG.h:190
Represents C++ constructor call.
Definition CFG.h:161
Represents C++ object destructor generated from a call to delete.
Definition CFG.h:489
Represents a top-level expression in a basic block.
Definition CFG.h:55
std::optional< T > getAs() const
Convert to the specified CFGElement type, returning std::nullopt if this CFGElement is not of the des...
Definition CFG.h:113
Represents C++ object destructor implicitly generated by compiler on various occasions.
Definition CFG.h:414
const CFGBlock * getBlock(const Stmt *S) const
Returns the CFGBlock the specified Stmt* appears in.
Represents C++ object destructor implicitly generated at the end of full expression for temporary obj...
Definition CFG.h:557
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:754
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition DeclCXX.h:1243
bool hasDefinition() const
Definition DeclCXX.h:562
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
Expr * getCallee()
Definition Expr.h:3159
ConstructionContext's subclasses describe different ways of constructing an object in C++.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
SourceLocation getLocation() const
Definition DeclBase.h:449
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1068
This represents one expression.
Definition Expr.h:114
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3126
QualType getType() const
Definition Expr.h:146
Represents a function declaration or definition.
Definition Decl.h:2082
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2952
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4846
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
ObjCMethodDecl * lookupMethod(Selector Sel, bool isInstance, bool shallowCategoryLookup=false, bool followSuper=true, const ObjCCategoryDecl *C=nullptr) const
lookupMethod - This method returns an instance/class method by looking in the class,...
Definition DeclObjC.cpp:705
SourceLocation getEndOfDefinitionLoc() const
Definition DeclObjC.h:1884
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:358
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:972
Selector getSelector() const
Definition ExprObjC.cpp:301
@ SuperInstance
The receiver is the instance of the superclass object.
Definition ExprObjC.h:986
@ SuperClass
The receiver is a superclass.
Definition ExprObjC.h:983
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition ExprObjC.h:1288
ObjCInterfaceDecl * getReceiverInterface() const
Retrieve the Objective-C interface to which this message is being directed, if known.
Definition ExprObjC.cpp:322
QualType getSuperType() const
Retrieve the type referred to by 'super'.
Definition ExprObjC.h:1376
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1396
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
bool hasBody() const override
Determine whether this method has a body.
Definition DeclObjC.h:526
bool isOverriding() const
Whether this method overrides any other in the class hierarchy.
Definition DeclObjC.h:465
ArrayRef< ParmVarDecl * > parameters() const
Definition DeclObjC.h:376
bool isPropertyAccessor() const
Definition DeclObjC.h:439
const ObjCPropertyDecl * findPropertyDecl(bool CheckOverrides=true) const
Returns the property associated with this method's selector.
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
ObjCInterfaceDecl * getClassInterface()
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
Stmt * getParentIgnoreParenCasts(Stmt *) const
Represents a parameter to a function.
Definition Decl.h:1832
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3404
Represents a program point just after an implicit call event.
Represents a program point just before an implicit call event.
ProgramPoints can be "tagged" as representing points specific to a given analysis entity.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6890
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
Definition Expr.h:6927
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
QualType getCanonicalType() const
Definition TypeBase.h:8732
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8753
Represents a struct/union/class.
Definition Decl.h:4512
field_range fields() const
Definition Decl.h:4715
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4700
Smart pointer class that efficiently represents Objective-C method names.
const IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
unsigned getNumArgs() const
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
It represents a stack frame of the call stack.
const ParentMap & getParentMap() const
unsigned getIndex() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
const Expr * getCallSite() const
CFGElement getCallSiteCFGElement() const
const Decl * getDecl() const
const StackFrame * getParent() const
It might return null.
const CFGBlock * getCallSiteBlock() const
Stmt - This represents one statement.
Definition Stmt.h:85
StmtClass getStmtClass() const
Definition Stmt.h:1504
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
A container of type source information.
Definition TypeBase.h:8651
bool isBlockPointerType() const
Definition TypeBase.h:8937
bool isVoidType() const
Definition TypeBase.h:9306
bool isFunctionPointerType() const
Definition TypeBase.h:8984
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:2092
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2864
bool isAnyPointerType() const
Definition TypeBase.h:8925
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
Represents a variable declaration or definition.
Definition Decl.h:934
This class is used for tools that requires cross translation unit capability.
llvm::Expected< const FunctionDecl * > getCrossTUDefinition(const FunctionDecl *FD, StringRef CrossTUDir, StringRef IndexName, bool DisplayCTUProgress=false)
This function loads a function or variable definition from an external AST file and merges it into th...
bool hasError(const Decl *ToDecl) const
Returns true if the given Decl is mapped (or created) during an import but there was an unrecoverable...
bool isImportedAsNew(const Decl *ToDecl) const
Returns true if the given Decl is newly created during the import.
bool isInCodeFile(SourceLocation SL) const
void getExtraInvalidatedValues(ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const override
Used to specify non-argument regions that will be invalidated as a result of this call.
SVal getCXXThisVal() const
Returns the value of the implicit 'this' object.
void getInitialStackFrameContents(const StackFrame *CalleeSF, BindingsTy &Bindings) const override
Populates the given SmallVector with the bindings in the callee's stack frame at the start of this ca...
void getInitialStackFrameContents(const StackFrame *CalleeSF, BindingsTy &Bindings) const override
Populates the given SmallVector with the bindings in the callee's stack frame at the start of this ca...
const FunctionDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
Definition CallEvent.h:502
ArrayRef< ParmVarDecl * > parameters() const override
Return call's formal parameters.
bool argumentsMayEscape() const override
Returns true if any of the arguments are known to escape to long- term storage, even if this method w...
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
llvm::ImmutableList< SVal > getEmptySValList()
llvm::ImmutableList< SVal > prependSVal(SVal X, llvm::ImmutableList< SVal > L)
const BlockDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
Definition CallEvent.h:596
void getInitialStackFrameContents(const StackFrame *CalleeSF, BindingsTy &Bindings) const override
Populates the given SmallVector with the bindings in the callee's stack frame at the start of this ca...
const BlockDataRegion * getBlockRegion() const
Returns the region associated with this instance of the block.
bool isConversionFromLambda() const
Definition CallEvent.h:603
ArrayRef< ParmVarDecl * > parameters() const override
Return call's formal parameters.
void getExtraInvalidatedValues(ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const override
Used to specify non-argument regions that will be invalidated as a result of this call.
const VarRegion * getRegionStoringCapturedLambda() const
For a block converted from a C++ lambda, returns the block VarRegion for the variable holding the cap...
Definition CallEvent.h:613
const CallExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition CallEvent.h:581
BlockDataRegion - A region that represents a block instance.
Definition MemRegion.h:713
SVal getCXXThisVal() const override
Returns the value of the implicit 'this' object.
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
bool isBaseDestructor() const
Returns true if this is a call to a base class destructor.
Definition CallEvent.h:923
const StackFrame * getInheritingStackFrame() const
Obtain the stack frame of the inheriting constructor.
std::pair< const CXXRecordDecl *, bool > getDeclForDynamicType() const
Returns the decl refered to by the "dynamic type" of the current object and if the class can be a sub...
void getExtraInvalidatedValues(ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const override
Used to specify non-argument regions that will be invalidated as a result of this call.
virtual SVal getCXXThisVal() const
Returns the value of the implicit 'this' object.
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
virtual const Expr * getCXXThisExpr() const
Returns the expression representing the implicit 'this' object.
Definition CallEvent.h:688
const FunctionDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
void getInitialStackFrameContents(const StackFrame *CalleeSF, BindingsTy &Bindings) const override
Populates the given SmallVector with the bindings in the callee's stack frame at the start of this ca...
const CXXMemberCallExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition CallEvent.h:791
const Expr * getCXXThisExpr() const override
Returns the expression representing the implicit 'this' object.
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
const Expr * getCXXThisExpr() const override
Returns the expression representing the implicit 'this' object.
const CXXOperatorCallExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition CallEvent.h:835
CallEventRef getCaller(const StackFrame *CalleeSF, ProgramStateRef State)
Gets an outside caller given a callee context.
CallEventRef< CXXConstructorCall > getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1412
CallEventRef< CXXAllocatorCall > getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1436
CallEventRef< CXXInheritedConstructorCall > getCXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *E, const MemRegion *Target, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1419
CallEventManager(llvm::BumpPtrAllocator &alloc)
CallEventRef< CXXDeallocatorCall > getCXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1443
CallEventRef< CXXDestructorCall > getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger, const MemRegion *Target, bool IsBase, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1427
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1405
CallEventRef getCall(const Stmt *S, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Gets a call event for a function call, Objective-C method call, a 'new', or a 'delete' call.
CallEventRef getSimpleCall(const CallExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:151
SourceRange getArgSourceRange(unsigned Index) const
Returns the source range for errors associated with this argument.
virtual void getExtraInvalidatedValues(ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const
Used to specify non-argument regions that will be invalidated as a result of this call.
Definition CallEvent.h:210
virtual StringRef getKindAsString() const =0
SVal getSVal(const Expr *E) const
Get the value of arbitrary expressions at this point in the path.
Definition CallEvent.h:201
virtual const Expr * getOriginExpr() const
Returns the expression whose value will be the result of this call.
Definition CallEvent.h:260
ProgramStateRef getState() const
A state for looking up relevant Environment entries (arguments, return value), dynamic type informati...
Definition CallEvent.h:221
static bool isCallStmt(const Stmt *S)
Returns true if this is a statement is a function or method call of some kind.
const ConstructionContext * getConstructionContext() const
Returns the construction context of the call, if it is a C++ constructor call or a call of a function...
param_type_iterator param_type_end() const
Definition CallEvent.h:478
const ParamVarRegion * getParameterLocation(unsigned Index, unsigned BlockCount) const
Returns memory location for a parameter variable within the callee stack frame.
bool isCalledFromSystemHeader() const
AnalysisDeclContext * getCalleeAnalysisDeclContext() const
Returns AnalysisDeclContext for the callee stack frame.
virtual std::optional< unsigned > getAdjustedParameterIndex(unsigned ASTArgumentIndex) const
Some calls have parameter numbering mismatched from argument numbering.
Definition CallEvent.h:424
QualType getResultType() const
Returns the result type, adjusted for references.
Definition CallEvent.cpp:71
ProgramStateRef invalidateRegions(unsigned BlockCount, ProgramStateRef State) const
Invalidates the regions (arguments, globals, special regions like 'this') that may have been written ...
friend class CallEventManager
Definition CallEvent.h:181
llvm::mapped_iterator< ArrayRef< ParmVarDecl * >::iterator, GetTypeFn > param_type_iterator
Definition CallEvent.h:466
const StackFrame * getCalleeStackFrame(unsigned BlockCount) const
Returns the callee stack frame.
bool isGlobalCFunction(StringRef SpecificName=StringRef()) const
Returns true if the callee is an externally-visible function in the top-level namespace,...
virtual bool argumentsMayEscape() const
Returns true if any of the arguments are known to escape to long- term storage, even if this method w...
Definition CallEvent.h:316
param_type_iterator param_type_begin() const
Returns an iterator over the types of the call's formal parameters.
Definition CallEvent.h:474
const StackFrame * getStackFrame() const
The stack frame in which the call is being evaluated.
Definition CallEvent.h:248
ProgramPoint getProgramPoint(bool IsPreVisit=false, const ProgramPointTag *Tag=nullptr) const
Returns an appropriate ProgramPoint for this call.
static QualType getDeclaredResultType(const Decl *D)
Returns the result type of a function or method declaration.
static bool isVariadic(const Decl *D)
Returns true if the given decl is known to be variadic.
virtual SVal getArgSVal(unsigned Index) const
Returns the value of a given argument at the time of the call.
bool hasNonNullArgumentsWithType(bool(*Condition)(QualType)) const
Returns true if the type of any of the non-null arguments satisfies the condition.
std::optional< SVal > getReturnValueUnderConstruction() const
If the call returns a C++ record type then the region of its return value can be retrieved from its c...
virtual const Expr * getArgExpr(unsigned Index) const
Returns the expression associated with a given argument.
Definition CallEvent.h:285
virtual unsigned getNumArgs() const =0
Returns the number of arguments (explicit and implicit).
bool hasVoidPointerToNonConstArg() const
Returns true if any of the arguments is void*.
const CallEventRef getCaller() const
bool isInSystemHeader() const
Returns true if the callee is known to be from a system header.
bool isArgumentConstructedDirectly(unsigned Index) const
Returns true if on the current path, the argument was constructed by calling a C++ constructor over i...
Definition CallEvent.h:412
SmallVectorImpl< FrameBindingTy > BindingsTy
Definition CallEvent.h:360
SVal getReturnValue() const
Returns the return value of the call.
virtual const Decl * getDecl() const
Returns the declaration of the function or method that will be called.
Definition CallEvent.h:233
const CFGBlock::ConstCFGElementRef & getCFGElementRef() const
Definition CallEvent.h:250
bool hasNonZeroCallbackArg() const
Returns true if any of the arguments appear to represent callbacks.
Kind getKind() const
Returns the kind of call this is.
Definition CallEvent.h:228
SmallVectorImpl< SVal > ValueList
Definition CallEvent.h:205
virtual SourceRange getSourceRange() const
Returns a source range for the entire call, suitable for outputting in diagnostics.
Definition CallEvent.h:276
static bool isCLibraryFunction(const FunctionDecl *FD, StringRef Name=StringRef())
Returns true if the given function is an externally-visible function in the top-level namespace,...
bool isValid() const =delete
Stores the currently inferred strictest bound on the runtime type of a region in a given state along ...
bool canBeASubClass() const
Returns false if the type information is precise (the type 'DynTy' is the only type in the lattice),...
QualType getType() const
Returns the currently inferred upper bound on the runtime type.
bool isValid() const
Returns true if the dynamic type info is available.
SVal computeObjectUnderConstruction(const Expr *E, ProgramStateRef State, unsigned NumVisitedCaller, const StackFrame *SF, const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx=0)
Find location of the object that is being constructed by a given constructor.
unsigned getNumVisited(const StackFrame *SF, const CFGBlock *Block) const
Definition ExprEngine.h:266
const ParamVarRegion * getParamVarRegion(const Expr *OriginExpr, unsigned Index, const StackFrame *SF)
getParamVarRegion - Retrieve or create the memory region associated with a specified CallExpr,...
const VarRegion * getVarRegion(const VarDecl *VD, const StackFrame *SF)
getVarRegion - Retrieve or create the memory region associated with a specified VarDecl and StackFram...
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
const ObjCMethodDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
Definition CallEvent.h:1253
void getExtraInvalidatedValues(ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const override
Used to specify non-argument regions that will be invalidated as a result of this call.
ObjCMessageKind getMessageKind() const
Returns how the message was written in the source (property access, subscript, or explicit message se...
const ObjCMessageExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition CallEvent.h:1249
ArrayRef< ParmVarDecl * > parameters() const override
Return call's formal parameters.
void getInitialStackFrameContents(const StackFrame *CalleeSF, BindingsTy &Bindings) const override
Populates the given SmallVector with the bindings in the callee's stack frame at the start of this ca...
SourceRange getSourceRange() const override
Returns a source range for the entire call, suitable for outputting in diagnostics.
bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, Selector Sel) const
Check if the selector may have multiple definitions (may have overrides).
bool argumentsMayEscape() const override
Returns true if any of the arguments are known to escape to long- term storage, even if this method w...
SVal getReceiverSVal() const
Returns the value of the receiver at the time of this call.
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1231
bool isReceiverSelfOrSuper() const
Checks if the receiver refers to 'self' or 'super'.
Selector getSelector() const
Definition CallEvent.h:1271
const ObjCPropertyDecl * getAccessedProperty() const
ParamVarRegion - Represents a region for parameters.
Definition MemRegion.h:1073
Information about invalidation for a particular region/symbol.
Definition MemRegion.h:1664
@ TK_PreserveContents
Tells that a region's contents is not changed.
Definition MemRegion.h:1679
@ TK_SuppressEscape
Suppress pointer-escaping of a region.
Definition MemRegion.h:1682
void setTrait(SymbolRef Sym, InvalidationKinds IK)
Defines the runtime definition of the called function.
Definition CallEvent.h:108
BasicValueFactory & getBasicValueFactory()
NonLoc makeCompoundVal(QualType type, llvm::ImmutableList< SVal > vals)
MemRegionManager & getRegionManager()
ProgramStateManager & getStateManager()
ASTContext & getContext()
loc::MemRegionVal makeLoc(SymbolRef sym)
SVal evalCast(SVal V, QualType CastTy, QualType OriginalTy)
Cast a given SVal to another SVal using given QualType's.
loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrame *SF)
Return a memory region for the 'this' object reference.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
bool isUnknownOrUndef() const
Definition SVals.h:115
const FunctionDecl * getAsFunctionDecl() const
getAsFunctionDecl - If this SVal is a MemRegionVal and wraps a CodeTextRegion wrapping a FunctionDecl...
Definition SVals.cpp:45
QualType getType(const ASTContext &) const
Try to get a reasonable type for the given value.
Definition SVals.cpp:180
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
bool isValid() const
Definition SVals.h:117
bool isUnknown() const
Definition SVals.h:111
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
const CallExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition CallEvent.h:541
const FunctionDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
std::optional< SVal > evalBaseToDerived(SVal Base, QualType DerivedPtrType)
Attempts to do a down cast.
Definition Store.cpp:318
TypedValueRegion - An abstract class representing regions having a typed value.
Definition MemRegion.h:570
static const FunctionDecl * getCallee(const CXXConstructExpr &D)
bool isWithinStdNamespace(const Decl *D)
Returns true if declaration D is in std namespace or any nested namespace or class scope.
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:166
DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR)
Get dynamic type information for the region MR.
@ CE_CXXAllocator
Definition CallEvent.h:70
ObjCMessageKind
Represents the ways an Objective-C message send can occur.
Definition CallEvent.h:1220
DynamicTypeInfo getClassObjectDynamicTypeInfo(ProgramStateRef State, SymbolRef Sym)
Get dynamic type information stored in a class object represented by Sym.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:909
@ Result
The result type of a method or function.
Definition TypeBase.h:906
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6253
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6259
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
Selector LookupSelector
const ObjCInterfaceDecl * Interface
Hints for figuring out if a call should be inlined during evalCall().
Definition ExprEngine.h:93
DenseMapInfo< Selector > SelectorInfo
static unsigned getHashValue(const PrivateMethodKey &Key)
DenseMapInfo< const ObjCInterfaceDecl * > InterfaceInfo
static bool isEqual(const PrivateMethodKey &LHS, const PrivateMethodKey &RHS)