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