clang 20.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/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
69using namespace clang;
70using namespace ento;
71
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
80static bool isCallback(QualType T) {
81 // If a parameter is a block or a callback, assume it can modify pointer.
82 if (T->isBlockPointerType() ||
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
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
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
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;
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
139}
140
143}
144
145bool 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
154 const Decl *D = getDecl();
155 if (!D)
156 return nullptr;
157
160
161 return ADC;
162}
163
164const StackFrameContext *
165CallEvent::getCalleeStackFrame(unsigned BlockCount) const {
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.
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
194const 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.
209static 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.
223static 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
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;
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(),
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)
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
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
304 if (IsPreVisit)
305 return PreImplicitCall(D, Loc, getLocationContext(), ElemRef, Tag);
306 return PostImplicitCall(D, Loc, getLocationContext(), ElemRef, Tag);
307}
308
309SVal CallEvent::getArgSVal(unsigned Index) const {
310 const Expr *ArgE = getArgExpr(Index);
311 if (!ArgE)
312 return UnknownVal();
313 return getSVal(ArgE);
314}
315
317 const Expr *ArgE = getArgExpr(Index);
318 if (!ArgE)
319 return {};
320 return ArgE->getSourceRange();
321}
322
324 const Expr *E = getOriginExpr();
325 if (!E)
326 return UndefinedVal();
327 return getSVal(E);
328}
329
330LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
331
332void 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
349 return isa<CallExpr, ObjCMessageExpr, CXXConstructExpr, CXXNewExpr>(S);
350}
351
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
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
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.
401static 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)) {
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.
436static SVal castArgToParamTypeIfNeeded(const CallEvent &Call, unsigned ArgIdx,
437 SVal ArgVal, SValBuilder &SVB) {
438 const auto *CallExprDecl = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
439 if (!CallExprDecl)
440 return ArgVal;
441
442 const FunctionDecl *Definition = CallExprDecl;
443 Definition->hasBody(Definition);
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() || !Definition->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() != Definition->getNumParams())
455 return UnknownVal();
456
457 const Expr *ArgExpr = Call.getArgExpr(ArgIdx);
458 const ParmVarDecl *Param = Definition->getParamDecl(ArgIdx);
459 return SVB.evalCast(ArgVal, Param->getType(), ArgExpr->getType());
460}
461
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
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
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
535 if (const CallEventRef<> Caller = getCaller())
536 return Caller->isInSystemHeader();
537
538 return false;
539}
540
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(
550 getLocationContext(), CC, CallOpts);
551 return RetVal;
552}
553
555 const FunctionDecl *D = getDecl();
556 if (!D)
557 return {};
558 return D->parameters();
559}
560
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).
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();
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
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
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
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
687 if (D)
688 return D;
689
690 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
691}
692
694 const auto *CE = cast_or_null<CallExpr>(getOriginExpr());
695 if (!CE)
697
698 const FunctionDecl *D = CE->getDirectCallee();
699 if (D)
700 return D;
701
702 return getSVal(CE->getCallee()).getAsFunctionDecl();
703}
704
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
715 // Get the record decl for the class of 'This'. D->getParent() may return
716 // a base class decl, rather than the class of the instance which needs to
717 // be checked for mutable fields.
718 const CXXRecordDecl *ParentRecord = getDeclForDynamicType().first;
719 if (!ParentRecord || !ParentRecord->hasDefinition())
720 return;
721
722 if (ParentRecord->hasMutableFields())
723 return;
724
725 // Preserve CXXThis.
726 const MemRegion *ThisRegion = ThisVal.getAsRegion();
727 if (!ThisRegion)
728 return;
729
730 ETraits->setTrait(ThisRegion->getBaseRegion(),
732 }
733}
734
736 const Expr *Base = getCXXThisExpr();
737 // FIXME: This doesn't handle an overloaded ->* operator.
738 SVal ThisVal = Base ? getSVal(Base) : UnknownVal();
739
740 if (isa<NonLoc>(ThisVal)) {
741 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
742 QualType OriginalTy = ThisVal.getType(SVB.getContext());
743 return SVB.evalCast(ThisVal, Base->getType(), OriginalTy);
744 }
745
746 assert(ThisVal.isUnknownOrUndef() || isa<Loc>(ThisVal));
747 return ThisVal;
748}
749
750std::pair<const CXXRecordDecl *, bool>
752 const MemRegion *R = getCXXThisVal().getAsRegion();
753 if (!R)
754 return {};
755
757 if (!DynType.isValid())
758 return {};
759
760 assert(!DynType.getType()->getPointeeType().isNull());
761 return {DynType.getType()->getPointeeCXXRecordDecl(),
762 DynType.canBeASubClass()};
763}
764
766 // Do we have a decl at all?
767 const Decl *D = getDecl();
768 if (!D)
769 return {};
770
771 // If the method is non-virtual, we know we can inline it.
772 const auto *MD = cast<CXXMethodDecl>(D);
773 if (!MD->isVirtual())
775
776 auto [RD, CanBeSubClass] = getDeclForDynamicType();
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?
802 if (!Result->hasBody(Definition)) {
803 if (!CanBeSubClass)
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 (CanBeSubClass)
813 getCXXThisVal().getAsRegion()->StripCasts());
814 return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
815}
816
818 const StackFrameContext *CalleeCtx,
819 BindingsTy &Bindings) const {
821
822 // Handle the binding of 'this' in the new stack frame.
823 SVal ThisVal = getCXXThisVal();
824 if (!ThisVal.isUnknown()) {
825 ProgramStateManager &StateMgr = getState()->getStateManager();
826 SValBuilder &SVB = StateMgr.getSValBuilder();
827
828 const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
829 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
830
831 // If we devirtualized to a different member function, we need to make sure
832 // we have the proper layering of CXXBaseObjectRegions.
833 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
834 ASTContext &Ctx = SVB.getContext();
835 const CXXRecordDecl *Class = MD->getParent();
837
838 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
839 std::optional<SVal> V =
840 StateMgr.getStoreManager().evalBaseToDerived(ThisVal, Ty);
841 if (!V) {
842 // We might have suffered some sort of placement new earlier, so
843 // we're constructing in a completely unexpected storage.
844 // Fall back to a generic pointer cast for this-value.
845 const CXXMethodDecl *StaticMD = cast<CXXMethodDecl>(getDecl());
846 const CXXRecordDecl *StaticClass = StaticMD->getParent();
847 QualType StaticTy = Ctx.getPointerType(Ctx.getRecordType(StaticClass));
848 ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy);
849 } else
850 ThisVal = *V;
851 }
852
853 if (!ThisVal.isUnknown())
854 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
855 }
856}
857
860}
861
863 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
864 // id-expression in the class member access expression is a qualified-id,
865 // that function is called. Otherwise, its final overrider in the dynamic type
866 // of the object expression is called.
867 if (const auto *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
868 if (ME->hasQualifier())
870
872}
873
875 return getOriginExpr()->getArg(0);
876}
877
879 const Expr *Callee = getOriginExpr()->getCallee();
880 const MemRegion *DataReg = getSVal(Callee).getAsRegion();
881
882 return dyn_cast_or_null<BlockDataRegion>(DataReg);
883}
884
886 const BlockDecl *D = getDecl();
887 if (!D)
888 return {};
889 return D->parameters();
890}
891
893 RegionAndSymbolInvalidationTraits *ETraits) const {
894 // FIXME: This also needs to invalidate captured globals.
895 if (const MemRegion *R = getBlockRegion())
896 Values.push_back(loc::MemRegionVal(R));
897}
898
900 BindingsTy &Bindings) const {
901 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
904 auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl());
905 Params = LambdaOperatorDecl->parameters();
906
907 // For blocks converted from a C++ lambda, the callee declaration is the
908 // operator() method on the lambda so we bind "this" to
909 // the lambda captured by the block.
910 const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
911 SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
912 Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx);
913 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
914 } else {
915 Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters();
916 }
917
918 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
919 Params);
920}
921
923 if (Data)
924 return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
925 return UnknownVal();
926}
927
929 RegionAndSymbolInvalidationTraits *ETraits) const {
930 SVal V = getCXXThisVal();
931 if (SymbolRef Sym = V.getAsSymbol(true))
932 ETraits->setTrait(Sym,
934
935 // Standard classes don't reinterpret-cast and modify super regions.
936 const bool IsStdClassCtor = isWithinStdNamespace(getDecl());
937 if (const MemRegion *Obj = V.getAsRegion(); Obj && IsStdClassCtor) {
938 ETraits->setTrait(
940 }
941
942 Values.push_back(V);
943}
944
946 const StackFrameContext *CalleeCtx,
947 BindingsTy &Bindings) const {
949
950 SVal ThisVal = getCXXThisVal();
951 if (!ThisVal.isUnknown()) {
952 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
953 const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
954 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
955 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
956 }
957}
958
959const StackFrameContext *
962 while (isa<CXXInheritedCtorInitExpr>(SFC->getCallSite()))
963 SFC = SFC->getParent()->getStackFrame();
964 return SFC;
965}
966
968 if (Data)
969 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
970 return UnknownVal();
971}
972
974 // Base destructors are always called non-virtually.
975 // Skip CXXInstanceCall's devirtualization logic in this case.
976 if (isBaseDestructor())
978
980}
981
983 const ObjCMethodDecl *D = getDecl();
984 if (!D)
985 return {};
986 return D->parameters();
987}
988
990 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
991
992 // If the method call is a setter for property known to be backed by
993 // an instance variable, don't invalidate the entire receiver, just
994 // the storage for that instance variable.
995 if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
996 if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
997 SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
998 if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) {
999 ETraits->setTrait(
1000 IvarRegion,
1002 ETraits->setTrait(
1003 IvarRegion,
1005 Values.push_back(IvarLVal);
1006 }
1007 return;
1008 }
1009 }
1010
1011 Values.push_back(getReceiverSVal());
1012}
1013
1015 // FIXME: Is this the best way to handle class receivers?
1016 if (!isInstanceMessage())
1017 return UnknownVal();
1018
1019 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
1020 return getSVal(RecE);
1021
1022 // An instance message with no expression means we are sending to super.
1023 // In this case the object reference is the same as 'self'.
1024 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
1025 SVal SelfVal = getState()->getSelfSVal(getLocationContext());
1026 assert(SelfVal.isValid() && "Calling super but not in ObjC method");
1027 return SelfVal;
1028}
1029
1031 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
1032 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
1033 return true;
1034
1035 if (!isInstanceMessage())
1036 return false;
1037
1038 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
1039 SVal SelfVal = getState()->getSelfSVal(getLocationContext());
1040
1041 return (RecVal == SelfVal);
1042}
1043
1045 switch (getMessageKind()) {
1046 case OCM_Message:
1047 return getOriginExpr()->getSourceRange();
1048 case OCM_PropertyAccess:
1049 case OCM_Subscript:
1050 return getContainingPseudoObjectExpr()->getSourceRange();
1051 }
1052 llvm_unreachable("unknown message kind");
1053}
1054
1055using ObjCMessageDataTy = llvm::PointerIntPair<const PseudoObjectExpr *, 2>;
1056
1057const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
1058 assert(Data && "Lazy lookup not yet performed.");
1059 assert(getMessageKind() != OCM_Message && "Explicit message send.");
1060 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
1061}
1062
1063static const Expr *
1065 const Expr *Syntactic = POE->getSyntacticForm()->IgnoreParens();
1066
1067 // This handles the funny case of assigning to the result of a getter.
1068 // This can happen if the getter returns a non-const reference.
1069 if (const auto *BO = dyn_cast<BinaryOperator>(Syntactic))
1070 Syntactic = BO->getLHS()->IgnoreParens();
1071
1072 return Syntactic;
1073}
1074
1076 if (!Data) {
1077 // Find the parent, ignoring implicit casts.
1078 const ParentMap &PM = getLocationContext()->getParentMap();
1080
1081 // Check if parent is a PseudoObjectExpr.
1082 if (const auto *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
1083 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
1084
1086 switch (Syntactic->getStmtClass()) {
1087 case Stmt::ObjCPropertyRefExprClass:
1089 break;
1090 case Stmt::ObjCSubscriptRefExprClass:
1091 K = OCM_Subscript;
1092 break;
1093 default:
1094 // FIXME: Can this ever happen?
1095 K = OCM_Message;
1096 break;
1097 }
1098
1099 if (K != OCM_Message) {
1100 const_cast<ObjCMethodCall *>(this)->Data
1101 = ObjCMessageDataTy(POE, K).getOpaqueValue();
1102 assert(getMessageKind() == K);
1103 return K;
1104 }
1105 }
1106
1107 const_cast<ObjCMethodCall *>(this)->Data
1108 = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
1109 assert(getMessageKind() == OCM_Message);
1110 return OCM_Message;
1111 }
1112
1113 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
1114 if (!Info.getPointer())
1115 return OCM_Message;
1116 return static_cast<ObjCMessageKind>(Info.getInt());
1117}
1118
1120 // Look for properties accessed with property syntax (foo.bar = ...)
1122 const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
1123 assert(POE && "Property access without PseudoObjectExpr?");
1124
1125 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
1126 auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
1127
1128 if (RefExpr->isExplicitProperty())
1129 return RefExpr->getExplicitProperty();
1130 }
1131
1132 // Look for properties accessed with method syntax ([foo setBar:...]).
1133 const ObjCMethodDecl *MD = getDecl();
1134 if (!MD || !MD->isPropertyAccessor())
1135 return nullptr;
1136
1137 // Note: This is potentially quite slow.
1138 return MD->findPropertyDecl();
1139}
1140
1142 Selector Sel) const {
1143 assert(IDecl);
1144 AnalysisManager &AMgr =
1145 getState()->getStateManager().getOwningEngine().getAnalysisManager();
1146 // If the class interface is declared inside the main file, assume it is not
1147 // subcassed.
1148 // TODO: It could actually be subclassed if the subclass is private as well.
1149 // This is probably very rare.
1150 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
1151 if (InterfLoc.isValid() && AMgr.isInCodeFile(InterfLoc))
1152 return false;
1153
1154 // Assume that property accessors are not overridden.
1156 return false;
1157
1158 // We assume that if the method is public (declared outside of main file) or
1159 // has a parent which publicly declares the method, the method could be
1160 // overridden in a subclass.
1161
1162 // Find the first declaration in the class hierarchy that declares
1163 // the selector.
1164 ObjCMethodDecl *D = nullptr;
1165 while (true) {
1166 D = IDecl->lookupMethod(Sel, true);
1167
1168 // Cannot find a public definition.
1169 if (!D)
1170 return false;
1171
1172 // If outside the main file,
1173 if (D->getLocation().isValid() && !AMgr.isInCodeFile(D->getLocation()))
1174 return true;
1175
1176 if (D->isOverriding()) {
1177 // Search in the superclass on the next iteration.
1178 IDecl = D->getClassInterface();
1179 if (!IDecl)
1180 return false;
1181
1182 IDecl = IDecl->getSuperClass();
1183 if (!IDecl)
1184 return false;
1185
1186 continue;
1187 }
1188
1189 return false;
1190 };
1191
1192 llvm_unreachable("The while loop should always terminate.");
1193}
1194
1196 if (!MD)
1197 return MD;
1198
1199 // Find the redeclaration that defines the method.
1200 if (!MD->hasBody()) {
1201 for (auto *I : MD->redecls())
1202 if (I->hasBody())
1203 MD = cast<ObjCMethodDecl>(I);
1204 }
1205 return MD;
1206}
1207
1212};
1213
1214namespace llvm {
1215template <> struct DenseMapInfo<PrivateMethodKey> {
1216 using InterfaceInfo = DenseMapInfo<const ObjCInterfaceDecl *>;
1217 using SelectorInfo = DenseMapInfo<Selector>;
1218
1220 return {InterfaceInfo::getEmptyKey(), SelectorInfo::getEmptyKey(), false};
1221 }
1222
1224 return {InterfaceInfo::getTombstoneKey(), SelectorInfo::getTombstoneKey(),
1225 true};
1226 }
1227
1228 static unsigned getHashValue(const PrivateMethodKey &Key) {
1229 return llvm::hash_combine(
1230 llvm::hash_code(InterfaceInfo::getHashValue(Key.Interface)),
1231 llvm::hash_code(SelectorInfo::getHashValue(Key.LookupSelector)),
1232 Key.IsClassMethod);
1233 }
1234
1235 static bool isEqual(const PrivateMethodKey &LHS,
1236 const PrivateMethodKey &RHS) {
1237 return InterfaceInfo::isEqual(LHS.Interface, RHS.Interface) &&
1238 SelectorInfo::isEqual(LHS.LookupSelector, RHS.LookupSelector) &&
1239 LHS.IsClassMethod == RHS.IsClassMethod;
1240 }
1241};
1242} // end namespace llvm
1243
1244static const ObjCMethodDecl *
1246 Selector LookupSelector, bool InstanceMethod) {
1247 // Repeatedly calling lookupPrivateMethod() is expensive, especially
1248 // when in many cases it returns null. We cache the results so
1249 // that repeated queries on the same ObjCIntefaceDecl and Selector
1250 // don't incur the same cost. On some test cases, we can see the
1251 // same query being issued thousands of times.
1252 //
1253 // NOTE: This cache is essentially a "global" variable, but it
1254 // only gets lazily created when we get here. The value of the
1255 // cache probably comes from it being global across ExprEngines,
1256 // where the same queries may get issued. If we are worried about
1257 // concurrency, or possibly loading/unloading ASTs, etc., we may
1258 // need to revisit this someday. In terms of memory, this table
1259 // stays around until clang quits, which also may be bad if we
1260 // need to release memory.
1261 using PrivateMethodCache =
1262 llvm::DenseMap<PrivateMethodKey, std::optional<const ObjCMethodDecl *>>;
1263
1264 static PrivateMethodCache PMC;
1265 std::optional<const ObjCMethodDecl *> &Val =
1266 PMC[{Interface, LookupSelector, InstanceMethod}];
1267
1268 // Query lookupPrivateMethod() if the cache does not hit.
1269 if (!Val) {
1270 Val = Interface->lookupPrivateMethod(LookupSelector, InstanceMethod);
1271
1272 if (!*Val) {
1273 // Query 'lookupMethod' as a backup.
1274 Val = Interface->lookupMethod(LookupSelector, InstanceMethod);
1275 }
1276 }
1277
1278 return *Val;
1279}
1280
1282 const ObjCMessageExpr *E = getOriginExpr();
1283 assert(E);
1284 Selector Sel = E->getSelector();
1285
1286 if (E->isInstanceMessage()) {
1287 // Find the receiver type.
1288 const ObjCObjectType *ReceiverT = nullptr;
1289 bool CanBeSubClassed = false;
1290 bool LookingForInstanceMethod = true;
1291 QualType SupersType = E->getSuperType();
1292 const MemRegion *Receiver = nullptr;
1293
1294 if (!SupersType.isNull()) {
1295 // The receiver is guaranteed to be 'super' in this case.
1296 // Super always means the type of immediate predecessor to the method
1297 // where the call occurs.
1298 ReceiverT = cast<ObjCObjectPointerType>(SupersType)->getObjectType();
1299 } else {
1300 Receiver = getReceiverSVal().getAsRegion();
1301 if (!Receiver)
1302 return {};
1303
1304 DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
1305 if (!DTI.isValid()) {
1306 assert(isa<AllocaRegion>(Receiver) &&
1307 "Unhandled untyped region class!");
1308 return {};
1309 }
1310
1311 QualType DynType = DTI.getType();
1312 CanBeSubClassed = DTI.canBeASubClass();
1313
1314 const auto *ReceiverDynT =
1315 dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType());
1316
1317 if (ReceiverDynT) {
1318 ReceiverT = ReceiverDynT->getObjectType();
1319
1320 // It can be actually class methods called with Class object as a
1321 // receiver. This type of messages is treated by the compiler as
1322 // instance (not class).
1323 if (ReceiverT->isObjCClass()) {
1324
1325 SVal SelfVal = getState()->getSelfSVal(getLocationContext());
1326 // For [self classMethod], return compiler visible declaration.
1327 if (Receiver == SelfVal.getAsRegion()) {
1328 return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
1329 }
1330
1331 // Otherwise, let's check if we know something about the type
1332 // inside of this class object.
1333 if (SymbolRef ReceiverSym = getReceiverSVal().getAsSymbol()) {
1334 DynamicTypeInfo DTI =
1336 if (DTI.isValid()) {
1337 // Let's use this type for lookup.
1338 ReceiverT =
1339 cast<ObjCObjectType>(DTI.getType().getCanonicalType());
1340
1341 CanBeSubClassed = DTI.canBeASubClass();
1342 // And it should be a class method instead.
1343 LookingForInstanceMethod = false;
1344 }
1345 }
1346 }
1347
1348 if (CanBeSubClassed)
1349 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface())
1350 // Even if `DynamicTypeInfo` told us that it can be
1351 // not necessarily this type, but its descendants, we still want
1352 // to check again if this selector can be actually overridden.
1353 CanBeSubClassed = canBeOverridenInSubclass(IDecl, Sel);
1354 }
1355 }
1356
1357 // Lookup the instance method implementation.
1358 if (ReceiverT)
1359 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface()) {
1360 const ObjCMethodDecl *MD =
1361 lookupRuntimeDefinition(IDecl, Sel, LookingForInstanceMethod);
1362
1363 if (MD && !MD->hasBody())
1364 MD = MD->getCanonicalDecl();
1365
1366 if (CanBeSubClassed)
1367 return RuntimeDefinition(MD, Receiver);
1368 else
1369 return RuntimeDefinition(MD, nullptr);
1370 }
1371 } else {
1372 // This is a class method.
1373 // If we have type info for the receiver class, we are calling via
1374 // class name.
1375 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
1376 // Find/Return the method implementation.
1377 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
1378 }
1379 }
1380
1381 return {};
1382}
1383
1385 if (isInSystemHeader() && !isInstanceMessage()) {
1386 Selector Sel = getSelector();
1387 if (Sel.getNumArgs() == 1 &&
1388 Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
1389 return true;
1390 }
1391
1393}
1394
1396 const StackFrameContext *CalleeCtx,
1397 BindingsTy &Bindings) const {
1398 const auto *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
1399 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
1400 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
1401 D->parameters());
1402
1403 SVal SelfVal = getReceiverSVal();
1404 if (!SelfVal.isUnknown()) {
1405 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
1406 MemRegionManager &MRMgr = SVB.getRegionManager();
1407 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
1408 Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
1409 }
1410}
1411
1414 const LocationContext *LCtx,
1416 if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(CE))
1417 return create<CXXMemberCall>(MCE, State, LCtx, ElemRef);
1418
1419 if (const auto *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
1420 const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
1421 if (const auto *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) {
1422 if (MD->isImplicitObjectMemberFunction())
1423 return create<CXXMemberOperatorCall>(OpCE, State, LCtx, ElemRef);
1424 if (MD->isStatic())
1425 return create<CXXStaticOperatorCall>(OpCE, State, LCtx, ElemRef);
1426 }
1427
1428 } else if (CE->getCallee()->getType()->isBlockPointerType()) {
1429 return create<BlockCall>(CE, State, LCtx, ElemRef);
1430 }
1431
1432 // Otherwise, it's a normal function call, static member function call, or
1433 // something we can't reason about.
1434 return create<SimpleFunctionCall>(CE, State, LCtx, ElemRef);
1435}
1436
1439 ProgramStateRef State) {
1440 const LocationContext *ParentCtx = CalleeCtx->getParent();
1441 const LocationContext *CallerCtx = ParentCtx->getStackFrame();
1442 CFGBlock::ConstCFGElementRef ElemRef = {CalleeCtx->getCallSiteBlock(),
1443 CalleeCtx->getIndex()};
1444 assert(CallerCtx && "This should not be used for top-level stack frames");
1445
1446 const Stmt *CallSite = CalleeCtx->getCallSite();
1447
1448 if (CallSite) {
1449 if (CallEventRef<> Out = getCall(CallSite, State, CallerCtx, ElemRef))
1450 return Out;
1451
1452 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1453 const auto *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
1454 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
1455 SVal ThisVal = State->getSVal(ThisPtr);
1456
1457 if (const auto *CE = dyn_cast<CXXConstructExpr>(CallSite))
1458 return getCXXConstructorCall(CE, ThisVal.getAsRegion(), State, CallerCtx,
1459 ElemRef);
1460 else if (const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(CallSite))
1461 return getCXXInheritedConstructorCall(CIE, ThisVal.getAsRegion(), State,
1462 CallerCtx, ElemRef);
1463 else {
1464 // All other cases are handled by getCall.
1465 llvm_unreachable("This is not an inlineable statement");
1466 }
1467 }
1468
1469 // Fall back to the CFG. The only thing we haven't handled yet is
1470 // destructors, though this could change in the future.
1471 const CFGBlock *B = CalleeCtx->getCallSiteBlock();
1472 CFGElement E = (*B)[CalleeCtx->getIndex()];
1473 assert((E.getAs<CFGImplicitDtor>() || E.getAs<CFGTemporaryDtor>()) &&
1474 "All other CFG elements should have exprs");
1475
1476 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1477 const auto *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
1478 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
1479 SVal ThisVal = State->getSVal(ThisPtr);
1480
1481 const Stmt *Trigger;
1482 if (std::optional<CFGAutomaticObjDtor> AutoDtor =
1483 E.getAs<CFGAutomaticObjDtor>())
1484 Trigger = AutoDtor->getTriggerStmt();
1485 else if (std::optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
1486 Trigger = DeleteDtor->getDeleteExpr();
1487 else
1488 Trigger = Dtor->getBody();
1489
1490 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
1491 E.getAs<CFGBaseDtor>().has_value(), State,
1492 CallerCtx, ElemRef);
1493}
1494
1496 const LocationContext *LC,
1498 if (const auto *CE = dyn_cast<CallExpr>(S)) {
1499 return getSimpleCall(CE, State, LC, ElemRef);
1500 } else if (const auto *NE = dyn_cast<CXXNewExpr>(S)) {
1501 return getCXXAllocatorCall(NE, State, LC, ElemRef);
1502 } else if (const auto *DE = dyn_cast<CXXDeleteExpr>(S)) {
1503 return getCXXDeallocatorCall(DE, State, LC, ElemRef);
1504 } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1505 return getObjCMethodCall(ME, State, LC, ElemRef);
1506 } else {
1507 return nullptr;
1508 }
1509}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
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)
Definition: CallEvent.cpp:104
static const ObjCMethodDecl * findDefiningRedecl(const ObjCMethodDecl *MD)
Definition: CallEvent.cpp:1195
static const ObjCMethodDecl * lookupRuntimeDefinition(const ObjCInterfaceDecl *Interface, Selector LookupSelector, bool InstanceMethod)
Definition: CallEvent.cpp:1245
static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx, CallEvent::BindingsTy &Bindings, SValBuilder &SVB, const CallEvent &Call, ArrayRef< ParmVarDecl * > parameters)
Definition: CallEvent.cpp:462
static const Expr * getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE)
Definition: CallEvent.cpp:1064
static bool isTransparentUnion(QualType T)
Definition: CallEvent.cpp:394
llvm::PointerIntPair< const PseudoObjectExpr *, 2 > ObjCMessageDataTy
Definition: CallEvent.cpp:1055
static bool isCallback(QualType T)
Definition: CallEvent.cpp:80
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.
Definition: CallEvent.cpp:436
static SVal processArgument(SVal Value, const Expr *ArgumentExpr, const ParmVarDecl *Parameter, SValBuilder &SVB)
Definition: CallEvent.cpp:401
static void findPtrToConstParams(llvm::SmallSet< unsigned, 4 > &PreserveArgs, const CallEvent &Call)
Definition: CallEvent.cpp:223
const Decl * D
Expr * E
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.
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:188
QualType getRecordType(const RecordDecl *Decl) const
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:733
CanQualType VoidTy
Definition: ASTContext.h:1160
AnalysisDeclContext * getContext(const Decl *D)
const StackFrameContext * getStackFrame(const Decl *D)
Obtain the beginning context of the analysis.
AnalysisDeclContext contains the context data for the function, method or block under analysis.
const Decl * getDecl() const
const ImplicitParamDecl * getSelfDecl() const
AnalysisDeclContextManager * getManager() const
Stores options for the analyzer from the command line.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4474
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Definition: CFG.h:417
Represents C++ object destructor implicitly generated for base object in destructor.
Definition: CFG.h:468
Represents a single basic block in a source-level CFG.
Definition: CFG.h:604
unsigned size() const
Definition: CFG.h:946
ElementRefImpl< true > ConstCFGElementRef
Definition: CFG.h:915
Represents a function call that returns a C++ object by value.
Definition: CFG.h:185
Represents C++ constructor call.
Definition: CFG.h:156
Represents C++ object destructor generated from a call to delete.
Definition: CFG.h:442
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:109
Represents C++ object destructor implicitly generated by compiler on various occasions.
Definition: CFG.h:366
CFGBlock * getBlock(Stmt *S)
Returns the CFGBlock the specified Stmt* appears in.
Definition: CFGStmtMap.cpp:27
Represents C++ object destructor implicitly generated at the end of full expression for temporary obj...
Definition: CFG.h:510
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition: ExprCXX.cpp:703
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
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:1245
bool hasDefinition() const
Definition: DeclCXX.h:572
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3068
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
Expr * getCallee()
Definition: Expr.h:3024
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:442
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1038
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
bool hasAttr() const
Definition: DeclBase.h:580
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3086
QualType getType() const
Definition: Expr.h:142
Represents a function declaration or definition.
Definition: Decl.h:1935
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
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.
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
const Decl * getDecl() const
const ParentMap & getParentMap() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
const LocationContext * getParent() const
It might return null.
const StackFrameContext * getStackFrame() const
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
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:697
SourceLocation getEndOfDefinitionLoc() const
Definition: DeclObjC.h:1877
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:350
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:941
@ SuperInstance
The receiver is the instance of the superclass object.
Definition: ExprObjC.h:955
@ SuperClass
The receiver is a superclass.
Definition: ExprObjC.h:952
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:523
bool isPropertyAccessor() const
Definition: DeclObjC.h:436
const ObjCPropertyDecl * findPropertyDecl(bool CheckOverrides=true) const
Returns the property associated with this method's selector.
Definition: DeclObjC.cpp:1376
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclObjC.cpp:1010
Represents a class type in Objective C.
Definition: Type.h:7326
bool isObjCClass() const
Definition: Type.h:7394
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:7559
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
Stmt * getParentIgnoreParenCasts(Stmt *) const
Definition: ParentMap.cpp:147
Represents a parameter to a function.
Definition: Decl.h:1725
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
Represents a program point just after an implicit call event.
Definition: ProgramPoint.h:597
Represents a program point just before an implicit call event.
Definition: ProgramPoint.h:579
ProgramPoints can be "tagged" as representing points specific to a given analysis entity.
Definition: ProgramPoint.h:38
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6546
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
Definition: Expr.h:6588
A (possibly-)qualified type.
Definition: Type.h:929
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
QualType getCanonicalType() const
Definition: Type.h:7983
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8004
Represents a struct/union/class.
Definition: Decl.h:4148
field_range fields() const
Definition: Decl.h:4354
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
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.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
It represents a stack frame of the call stack (based on CallEvent).
CFGElement getCallSiteCFGElement() const
const Stmt * getCallSite() const
const CFGBlock * getCallSiteBlock() const
Stmt - This represents one statement.
Definition: Stmt.h:84
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
StmtClass getStmtClass() const
Definition: Stmt.h:1380
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:333
A container of type source information.
Definition: Type.h:7902
bool isBlockPointerType() const
Definition: Type.h:8200
bool isVoidType() const
Definition: Type.h:8510
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isFunctionPointerType() const
Definition: Type.h:8226
bool isObjCSelType() const
Definition: Type.h:8373
bool isReferenceType() const
Definition: Type.h:8204
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:1901
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
const RecordType * getAsStructureType() const
Definition: Type.cpp:754
bool isAnyPointerType() const
Definition: Type.h:8194
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
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.
static bool isInCodeFile(SourceLocation SL, const SourceManager &SM)
void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, BindingsTy &Bindings) const override
Populates the given SmallVector with the bindings in the callee's stack frame at the start of this ca...
Definition: CallEvent.cpp:945
void getExtraInvalidatedValues(ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const override
Used to specify non-argument regions that will be invalidated as a result of this call.
Definition: CallEvent.cpp:928
SVal getCXXThisVal() const
Returns the value of the implicit 'this' object.
Definition: CallEvent.cpp:922
const FunctionDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
Definition: CallEvent.h:514
ArrayRef< ParmVarDecl * > parameters() const override
Return call's formal parameters.
Definition: CallEvent.cpp:554
void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, BindingsTy &Bindings) const override
Populates the given SmallVector with the bindings in the callee's stack frame at the start of this ca...
Definition: CallEvent.cpp:615
bool argumentsMayEscape() const override
Returns true if any of the arguments are known to escape to long- term storage, even if this method w...
Definition: CallEvent.cpp:624
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
Definition: CallEvent.cpp:561
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:605
const BlockDataRegion * getBlockRegion() const
Returns the region associated with this instance of the block.
Definition: CallEvent.cpp:878
bool isConversionFromLambda() const
Definition: CallEvent.h:612
ArrayRef< ParmVarDecl * > parameters() const override
Return call's formal parameters.
Definition: CallEvent.cpp:885
void getExtraInvalidatedValues(ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const override
Used to specify non-argument regions that will be invalidated as a result of this call.
Definition: CallEvent.cpp:892
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:622
void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, BindingsTy &Bindings) const override
Populates the given SmallVector with the bindings in the callee's stack frame at the start of this ca...
Definition: CallEvent.cpp:899
const CallExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:590
BlockDataRegion - A region that represents a block instance.
Definition: MemRegion.h:678
SVal getCXXThisVal() const override
Returns the value of the implicit 'this' object.
Definition: CallEvent.cpp:967
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
Definition: CallEvent.cpp:973
bool isBaseDestructor() const
Returns true if this is a call to a base class destructor.
Definition: CallEvent.h:939
const StackFrameContext * getInheritingStackFrame() const
Obtain the stack frame of the inheriting constructor.
Definition: CallEvent.cpp:960
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...
Definition: CallEvent.cpp:751
void getExtraInvalidatedValues(ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const override
Used to specify non-argument regions that will be invalidated as a result of this call.
Definition: CallEvent.cpp:705
virtual SVal getCXXThisVal() const
Returns the value of the implicit 'this' object.
Definition: CallEvent.cpp:735
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
Definition: CallEvent.cpp:765
virtual const Expr * getCXXThisExpr() const
Returns the expression representing the implicit 'this' object.
Definition: CallEvent.h:700
const FunctionDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
Definition: CallEvent.cpp:693
void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, BindingsTy &Bindings) const override
Populates the given SmallVector with the bindings in the callee's stack frame at the start of this ca...
Definition: CallEvent.cpp:817
const CXXMemberCallExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:805
const Expr * getCXXThisExpr() const override
Returns the expression representing the implicit 'this' object.
Definition: CallEvent.cpp:858
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
Definition: CallEvent.cpp:862
const Expr * getCXXThisExpr() const override
Returns the expression representing the implicit 'this' object.
Definition: CallEvent.cpp:874
const CXXOperatorCallExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:850
Manages the lifetime of CallEvent objects.
Definition: CallEvent.h:1361
CallEventRef< CXXDestructorCall > getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger, const MemRegion *Target, bool IsBase, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1454
CallEventRef getCall(const Stmt *S, ProgramStateRef State, const LocationContext *LC, CFGBlock::ConstCFGElementRef ElemRef)
Gets a call event for a function call, Objective-C method call, a 'new', or a 'delete' call.
Definition: CallEvent.cpp:1495
CallEventRef< CXXDeallocatorCall > getCXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1470
CallEventRef getSimpleCall(const CallExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.cpp:1413
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1432
CallEventRef< CXXAllocatorCall > getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1463
CallEventRef< CXXConstructorCall > getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1439
CallEventRef< CXXInheritedConstructorCall > getCXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *E, const MemRegion *Target, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1446
CallEventRef getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State)
Gets an outside caller given a callee context.
Definition: CallEvent.cpp:1438
Represents an abstract call to a function or method along a particular path.
Definition: CallEvent.h:153
virtual SourceRange getArgSourceRange(unsigned Index) const
Returns the source range for errors associated with this argument.
Definition: CallEvent.cpp:316
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:211
virtual StringRef getKindAsString() const =0
virtual const Expr * getOriginExpr() const
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:250
static bool isCallStmt(const Stmt *S)
Returns true if this is a statement is a function or method call of some kind.
Definition: CallEvent.cpp:348
llvm::mapped_iterator< ArrayRef< ParmVarDecl * >::iterator, GetTypeFn > param_type_iterator
Definition: CallEvent.h:477
const ConstructionContext * getConstructionContext() const
Returns the construction context of the call, if it is a C++ constructor call or a call of a function...
Definition: CallEvent.cpp:504
param_type_iterator param_type_end() const
Definition: CallEvent.h:488
const ParamVarRegion * getParameterLocation(unsigned Index, unsigned BlockCount) const
Returns memory location for a parameter variable within the callee stack frame.
Definition: CallEvent.cpp:195
bool isCalledFromSystemHeader() const
Definition: CallEvent.cpp:534
AnalysisDeclContext * getCalleeAnalysisDeclContext() const
Returns AnalysisDeclContext for the callee stack frame.
Definition: CallEvent.cpp:153
ProgramStateRef invalidateRegions(unsigned BlockCount, ProgramStateRef Orig=nullptr) const
Returns a new state with all argument regions invalidated.
Definition: CallEvent.cpp:234
virtual std::optional< unsigned > getAdjustedParameterIndex(unsigned ASTArgumentIndex) const
Some calls have parameter numbering mismatched from argument numbering.
Definition: CallEvent.h:434
const ProgramStateRef & getState() const
The state in which the call is being evaluated.
Definition: CallEvent.h:235
QualType getResultType() const
Returns the result type, adjusted for references.
Definition: CallEvent.cpp:72
bool isInSystemHeader() const
Returns true if the callee is known to be from a system header.
Definition: CallEvent.h:262
bool isGlobalCFunction(StringRef SpecificName=StringRef()) const
Returns true if the callee is an externally-visible function in the top-level namespace,...
Definition: CallEvent.cpp:145
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:324
param_type_iterator param_type_begin() const
Returns an iterator over the types of the call's formal parameters.
Definition: CallEvent.h:484
const void * Data
Definition: CallEvent.h:166
ProgramPoint getProgramPoint(bool IsPreVisit=false, const ProgramPointTag *Tag=nullptr) const
Returns an appropriate ProgramPoint for this call.
Definition: CallEvent.cpp:289
const StackFrameContext * getCalleeStackFrame(unsigned BlockCount) const
Returns the callee stack frame.
Definition: CallEvent.cpp:165
static QualType getDeclaredResultType(const Decl *D)
Returns the result type of a function or method declaration.
Definition: CallEvent.cpp:352
SVal getSVal(const Stmt *S) const
Get the value of arbitrary expressions at this point in the path.
Definition: CallEvent.h:202
static bool isVariadic(const Decl *D)
Returns true if the given decl is known to be variadic.
Definition: CallEvent.cpp:381
virtual SVal getArgSVal(unsigned Index) const
Returns the value of a given argument at the time of the call.
Definition: CallEvent.cpp:309
bool hasNonNullArgumentsWithType(bool(*Condition)(QualType)) const
Returns true if the type of any of the non-null arguments satisfies the condition.
Definition: CallEvent.cpp:114
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...
Definition: CallEvent.cpp:541
virtual const Expr * getArgExpr(unsigned Index) const
Returns the expression associated with a given argument.
Definition: CallEvent.h:293
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*.
Definition: CallEvent.cpp:141
const CallEventRef getCaller() const
Definition: CallEvent.cpp:521
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:422
SVal getReturnValue() const
Returns the return value of the call.
Definition: CallEvent.cpp:323
virtual const Decl * getDecl() const
Returns the declaration of the function or method that will be called.
Definition: CallEvent.h:224
const LocationContext * getLocationContext() const
The context in which the call is being evaluated.
Definition: CallEvent.h:238
bool hasNonZeroCallbackArg() const
Returns true if any of the arguments appear to represent callbacks.
Definition: CallEvent.cpp:137
virtual Kind getKind() const =0
Returns the kind of call this is.
virtual SourceRange getSourceRange() const
Returns a source range for the entire call, suitable for outputting in diagnostics.
Definition: CallEvent.h:284
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,...
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, const NodeBuilderContext *BldrCtx, const LocationContext *LCtx, const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx=0)
Find location of the object that is being constructed by a given constructor.
const NodeBuilderContext & getBuilderContext()
Definition: ExprEngine.h:217
const VarRegion * getVarRegion(const VarDecl *VD, const LocationContext *LC)
getVarRegion - Retrieve or create the memory region associated with a specified VarDecl and LocationC...
Definition: MemRegion.cpp:1025
const ParamVarRegion * getParamVarRegion(const Expr *OriginExpr, unsigned Index, const LocationContext *LC)
getParamVarRegion - Retrieve or create the memory region associated with a specified CallExpr,...
Definition: MemRegion.cpp:1136
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:97
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
Definition: MemRegion.cpp:1377
Represents any expression that calls an Objective-C method.
Definition: CallEvent.h:1248
const ObjCMethodDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
Definition: CallEvent.h:1278
void getExtraInvalidatedValues(ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const override
Used to specify non-argument regions that will be invalidated as a result of this call.
Definition: CallEvent.cpp:989
bool isInstanceMessage() const
Definition: CallEvent.h:1288
ObjCMessageKind getMessageKind() const
Returns how the message was written in the source (property access, subscript, or explicit message se...
Definition: CallEvent.cpp:1075
const ObjCMessageExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:1274
ArrayRef< ParmVarDecl * > parameters() const override
Return call's formal parameters.
Definition: CallEvent.cpp:982
SourceRange getSourceRange() const override
Returns a source range for the entire call, suitable for outputting in diagnostics.
Definition: CallEvent.cpp:1044
virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, Selector Sel) const
Check if the selector may have multiple definitions (may have overrides).
Definition: CallEvent.cpp:1141
bool argumentsMayEscape() const override
Returns true if any of the arguments are known to escape to long- term storage, even if this method w...
Definition: CallEvent.cpp:1384
SVal getReceiverSVal() const
Returns the value of the receiver at the time of this call.
Definition: CallEvent.cpp:1014
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
Definition: CallEvent.cpp:1281
bool isReceiverSelfOrSuper() const
Checks if the receiver refers to 'self' or 'super'.
Definition: CallEvent.cpp:1030
Selector getSelector() const
Definition: CallEvent.h:1296
const ObjCPropertyDecl * getAccessedProperty() const
Definition: CallEvent.cpp:1119
void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, BindingsTy &Bindings) const override
Populates the given SmallVector with the bindings in the callee's stack frame at the start of this ca...
Definition: CallEvent.cpp:1395
ParamVarRegion - Represents a region for paremters.
Definition: MemRegion.h:1034
Information about invalidation for a particular region/symbol.
Definition: MemRegion.h:1629
@ TK_PreserveContents
Tells that a region's contents is not changed.
Definition: MemRegion.h:1644
@ TK_SuppressEscape
Suppress pointer-escaping of a region.
Definition: MemRegion.h:1647
void setTrait(SymbolRef Sym, InvalidationKinds IK)
Definition: MemRegion.cpp:1802
Defines the runtime definition of the called function.
Definition: CallEvent.h:110
BasicValueFactory & getBasicValueFactory()
Definition: SValBuilder.h:161
NonLoc makeCompoundVal(QualType type, llvm::ImmutableList< SVal > vals)
Definition: SValBuilder.h:260
MemRegionManager & getRegionManager()
Definition: SValBuilder.h:167
ASTContext & getContext()
Definition: SValBuilder.h:148
loc::MemRegionVal makeLoc(SymbolRef sym)
Definition: SValBuilder.h:374
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 StackFrameContext *SFC)
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:56
bool isUnknownOrUndef() const
Definition: SVals.h:109
const FunctionDecl * getAsFunctionDecl() const
getAsFunctionDecl - If this SVal is a MemRegionVal and wraps a CodeTextRegion wrapping a FunctionDecl...
Definition: SVals.cpp:46
QualType getType(const ASTContext &) const
Try to get a reasonable type for the given value.
Definition: SVals.cpp:181
const MemRegion * getAsRegion() const
Definition: SVals.cpp:120
bool isValid() const
Definition: SVals.h:111
bool isUnknown() const
Definition: SVals.h:105
const CallExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:551
const FunctionDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
Definition: CallEvent.cpp:685
std::optional< SVal > evalBaseToDerived(SVal Base, QualType DerivedPtrType)
Attempts to do a down cast.
Definition: Store.cpp:316
Symbolic value.
Definition: SymExpr.h:30
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:535
bool isWithinStdNamespace(const Decl *D)
Returns true if declaration D is in std namespace or any nested namespace or class scope.
DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR)
Get dynamic type information for the region MR.
@ CE_CXXAllocator
Definition: CallEvent.h:72
ObjCMessageKind
Represents the ways an Objective-C message send can occur.
Definition: CallEvent.h:1243
@ OCM_PropertyAccess
Definition: CallEvent.h:1243
DynamicTypeInfo getClassObjectDynamicTypeInfo(ProgramStateRef State, SymbolRef Sym)
Get dynamic type information stored in a class object represented by Sym.
The JSON file list parser is used to communicate input to InstallAPI.
@ Parameter
The parameter type of a method or function.
@ Result
The result type of a method or function.
const FunctionProtoType * T
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
Selector LookupSelector
Definition: CallEvent.cpp:1210
const ObjCInterfaceDecl * Interface
Definition: CallEvent.cpp:1209
Hints for figuring out of a call should be inlined during evalCall().
Definition: ExprEngine.h:97
DenseMapInfo< Selector > SelectorInfo
Definition: CallEvent.cpp:1217
static unsigned getHashValue(const PrivateMethodKey &Key)
Definition: CallEvent.cpp:1228
static PrivateMethodKey getEmptyKey()
Definition: CallEvent.cpp:1219
DenseMapInfo< const ObjCInterfaceDecl * > InterfaceInfo
Definition: CallEvent.cpp:1216
static bool isEqual(const PrivateMethodKey &LHS, const PrivateMethodKey &RHS)
Definition: CallEvent.cpp:1235
static PrivateMethodKey getTombstoneKey()
Definition: CallEvent.cpp:1223