clang 22.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/Compiler.h"
58#include "llvm/Support/Debug.h"
59#include "llvm/Support/ErrorHandling.h"
60#include "llvm/Support/raw_ostream.h"
61#include <cassert>
62#include <optional>
63#include <utility>
64
65#define DEBUG_TYPE "static-analyzer-call-event"
66
67using namespace clang;
68using namespace ento;
69
71 ASTContext &Ctx = getState()->getStateManager().getContext();
72 const Expr *E = getOriginExpr();
73 if (!E)
74 return Ctx.VoidTy;
75 return Ctx.getReferenceQualifiedType(E);
76}
77
78static bool isCallback(QualType T) {
79 // If a parameter is a block or a callback, assume it can modify pointer.
80 if (T->isBlockPointerType() ||
83 return true;
84
85 // Check if a callback is passed inside a struct (for both, struct passed by
86 // reference and by value). Dig just one level into the struct for now.
87
89 T = T->getPointeeType();
90
91 if (const RecordType *RT = T->getAsStructureType()) {
92 const RecordDecl *RD = RT->getOriginalDecl()->getDefinitionOrSelf();
93 for (const auto *I : RD->fields()) {
94 QualType FieldT = I->getType();
95 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
96 return true;
97 }
98 }
99 return false;
100}
101
103 if (const auto *PT = T->getAs<PointerType>()) {
104 QualType PointeeTy = PT->getPointeeType();
105 if (PointeeTy.isConstQualified())
106 return false;
107 return PointeeTy->isVoidType();
108 } else
109 return false;
110}
111
113 unsigned NumOfArgs = getNumArgs();
114
115 // If calling using a function pointer, assume the function does not
116 // satisfy the callback.
117 // TODO: We could check the types of the arguments here.
118 if (!getDecl())
119 return false;
120
121 unsigned Idx = 0;
123 E = param_type_end();
124 I != E && Idx < NumOfArgs; ++I, ++Idx) {
125 // If the parameter is 0, it's harmless.
126 if (getArgSVal(Idx).isZeroConstant())
127 continue;
128
129 if (Condition(*I))
130 return true;
131 }
132 return false;
133}
134
137}
138
141}
142
143bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
144 const auto *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
145 if (!FD)
146 return false;
147
148 return CheckerContext::isCLibraryFunction(FD, FunctionName);
149}
150
152 const Decl *D = getDecl();
153 if (!D)
154 return nullptr;
155
158
159 return ADC;
160}
161
162const StackFrameContext *
163CallEvent::getCalleeStackFrame(unsigned BlockCount) const {
165 if (!ADC)
166 return nullptr;
167
168 const Expr *E = getOriginExpr();
169 if (!E)
170 return nullptr;
171
172 // Recover CFG block via reverse lookup.
173 // TODO: If we were to keep CFG element information as part of the CallEvent
174 // instead of doing this reverse lookup, we would be able to build the stack
175 // frame for non-expression-based calls, and also we wouldn't need the reverse
176 // lookup.
178 const CFGBlock *B = Map->getBlock(E);
179 assert(B);
180
181 // Also recover CFG index by scanning the CFG block.
182 unsigned Idx = 0, Sz = B->size();
183 for (; Idx < Sz; ++Idx)
184 if (auto StmtElem = (*B)[Idx].getAs<CFGStmt>())
185 if (StmtElem->getStmt() == E)
186 break;
187 assert(Idx < Sz);
188
189 return ADC->getManager()->getStackFrame(ADC, LCtx, E, B, BlockCount, Idx);
190}
191
192const ParamVarRegion
193*CallEvent::getParameterLocation(unsigned Index, unsigned BlockCount) const {
194 const StackFrameContext *SFC = getCalleeStackFrame(BlockCount);
195 // We cannot construct a VarRegion without a stack frame.
196 if (!SFC)
197 return nullptr;
198
199 const ParamVarRegion *PVR =
200 State->getStateManager().getRegionManager().getParamVarRegion(
201 getOriginExpr(), Index, SFC);
202 return PVR;
203}
204
205/// Returns true if a type is a pointer-to-const or reference-to-const
206/// with no further indirection.
207static bool isPointerToConst(QualType Ty) {
208 QualType PointeeTy = Ty->getPointeeType();
209 if (PointeeTy == QualType())
210 return false;
211 if (!PointeeTy.isConstQualified())
212 return false;
213 if (PointeeTy->isAnyPointerType())
214 return false;
215 return true;
216}
217
218// Try to retrieve the function declaration and find the function parameter
219// types which are pointers/references to a non-pointer const.
220// We will not invalidate the corresponding argument regions.
221static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
222 const CallEvent &Call) {
223 unsigned Idx = 0;
224 for (CallEvent::param_type_iterator I = Call.param_type_begin(),
225 E = Call.param_type_end();
226 I != E; ++I, ++Idx) {
227 if (isPointerToConst(*I))
228 PreserveArgs.insert(Idx);
229 }
230}
231
233 ProgramStateRef Orig) const {
234 ProgramStateRef Result = (Orig ? Orig : getState());
235
236 // Don't invalidate anything if the callee is marked pure/const.
237 if (const Decl *callee = getDecl())
238 if (callee->hasAttr<PureAttr>() || callee->hasAttr<ConstAttr>())
239 return Result;
240
241 SmallVector<SVal, 8> ValuesToInvalidate;
243
244 getExtraInvalidatedValues(ValuesToInvalidate, &ETraits);
245
246 // Indexes of arguments whose values will be preserved by the call.
247 llvm::SmallSet<unsigned, 4> PreserveArgs;
248 if (!argumentsMayEscape())
249 findPtrToConstParams(PreserveArgs, *this);
250
251 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
252 // Mark this region for invalidation. We batch invalidate regions
253 // below for efficiency.
254 if (PreserveArgs.count(Idx))
255 if (const MemRegion *MR = getArgSVal(Idx).getAsRegion())
256 ETraits.setTrait(MR->getBaseRegion(),
258 // TODO: Factor this out + handle the lower level const pointers.
259
260 ValuesToInvalidate.push_back(getArgSVal(Idx));
261
262 // If a function accepts an object by argument (which would of course be a
263 // temporary that isn't lifetime-extended), invalidate the object itself,
264 // not only other objects reachable from it. This is necessary because the
265 // destructor has access to the temporary object after the call.
266 // TODO: Support placement arguments once we start
267 // constructing them directly.
268 // TODO: This is unnecessary when there's no destructor, but that's
269 // currently hard to figure out.
270 if (getKind() != CE_CXXAllocator)
272 if (auto AdjIdx = getAdjustedParameterIndex(Idx))
273 if (const TypedValueRegion *TVR =
274 getParameterLocation(*AdjIdx, BlockCount))
275 ValuesToInvalidate.push_back(loc::MemRegionVal(TVR));
276 }
277
278 // Invalidate designated regions using the batch invalidation API.
279 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
280 // global variables.
281 return Result->invalidateRegions(ValuesToInvalidate, getCFGElementRef(),
282 BlockCount, getLocationContext(),
283 /*CausedByPointerEscape*/ true,
284 /*Symbols=*/nullptr, this, &ETraits);
285}
286
288 const ProgramPointTag *Tag) const {
289
290 if (const Expr *E = getOriginExpr()) {
291 if (IsPreVisit)
292 return PreStmt(E, getLocationContext(), Tag);
293 return PostStmt(E, getLocationContext(), Tag);
294 }
295
296 const Decl *D = getDecl();
297 assert(D && "Cannot get a program point without a statement or decl");
298 assert(ElemRef.getParent() &&
299 "Cannot get a program point without a CFGElementRef");
300
302 if (IsPreVisit)
303 return PreImplicitCall(D, Loc, getLocationContext(), ElemRef, Tag);
304 return PostImplicitCall(D, Loc, getLocationContext(), ElemRef, Tag);
305}
306
307SVal CallEvent::getArgSVal(unsigned Index) const {
308 const Expr *ArgE = getArgExpr(Index);
309 if (!ArgE)
310 return UnknownVal();
311 return getSVal(ArgE);
312}
313
315 const Expr *ArgE = getArgExpr(Index);
316 if (!ArgE)
317 return {};
318 return ArgE->getSourceRange();
319}
320
322 const Expr *E = getOriginExpr();
323 if (!E)
324 return UndefinedVal();
325 return getSVal(E);
326}
327
328LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
329
330void CallEvent::dump(raw_ostream &Out) const {
331 ASTContext &Ctx = getState()->getStateManager().getContext();
332 if (const Expr *E = getOriginExpr()) {
333 E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
334 return;
335 }
336
337 if (const Decl *D = getDecl()) {
338 Out << "Call to ";
339 D->print(Out, Ctx.getPrintingPolicy());
340 return;
341 }
342
343 Out << "Unknown call (type " << getKindAsString() << ")";
344}
345
347 return isa<CallExpr, ObjCMessageExpr, CXXConstructExpr, CXXNewExpr>(S);
348}
349
351 assert(D);
352 if (const auto *FD = dyn_cast<FunctionDecl>(D))
353 return FD->getReturnType();
354 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
355 return MD->getReturnType();
356 if (const auto *BD = dyn_cast<BlockDecl>(D)) {
357 // Blocks are difficult because the return type may not be stored in the
358 // BlockDecl itself. The AST should probably be enhanced, but for now we
359 // just do what we can.
360 // If the block is declared without an explicit argument list, the
361 // signature-as-written just includes the return type, not the entire
362 // function type.
363 // FIXME: All blocks should have signatures-as-written, even if the return
364 // type is inferred. (That's signified with a dependent result type.)
365 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
366 QualType Ty = TSI->getType();
367 if (const FunctionType *FT = Ty->getAs<FunctionType>())
368 Ty = FT->getReturnType();
369 if (!Ty->isDependentType())
370 return Ty;
371 }
372
373 return {};
374 }
375
376 llvm_unreachable("unknown callable kind");
377}
378
380 assert(D);
381
382 if (const auto *FD = dyn_cast<FunctionDecl>(D))
383 return FD->isVariadic();
384 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
385 return MD->isVariadic();
386 if (const auto *BD = dyn_cast<BlockDecl>(D))
387 return BD->isVariadic();
388
389 llvm_unreachable("unknown callable kind");
390}
391
393 const RecordType *UT = T->getAsUnionType();
394 return UT && UT->getOriginalDecl()
396 ->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
691}
692
694 // Clang converts lambdas to function pointers using an implicit conversion
695 // operator, which returns the lambda's '__invoke' method. However, Sema
696 // leaves the body of '__invoke' empty (it is generated later in CodeGen), so
697 // we need to skip '__invoke' and access the lambda's operator() directly.
698 if (const auto *CMD = dyn_cast_if_present<CXXMethodDecl>(getDecl());
699 CMD && CMD->isLambdaStaticInvoker())
700 return RuntimeDefinition{CMD->getParent()->getLambdaCallOperator()};
701
703}
704
706 const auto *CE = cast_or_null<CallExpr>(getOriginExpr());
707 if (!CE)
709
710 const FunctionDecl *D = CE->getDirectCallee();
711 if (D)
712 return D;
713
714 return getSVal(CE->getCallee()).getAsFunctionDecl();
715}
716
718 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
719 SVal ThisVal = getCXXThisVal();
720 Values.push_back(ThisVal);
721
722 // Don't invalidate if the method is const and there are no mutable fields.
723 if (const auto *D = cast_or_null<CXXMethodDecl>(getDecl())) {
724 if (!D->isConst())
725 return;
726
727 // Get the record decl for the class of 'This'. D->getParent() may return
728 // a base class decl, rather than the class of the instance which needs to
729 // be checked for mutable fields.
730 const CXXRecordDecl *ParentRecord = getDeclForDynamicType().first;
731 if (!ParentRecord || !ParentRecord->hasDefinition())
732 return;
733
734 if (ParentRecord->hasMutableFields())
735 return;
736
737 // Preserve CXXThis.
738 const MemRegion *ThisRegion = ThisVal.getAsRegion();
739 if (!ThisRegion)
740 return;
741
742 ETraits->setTrait(ThisRegion->getBaseRegion(),
744 }
745}
746
748 const Expr *Base = getCXXThisExpr();
749 // FIXME: This doesn't handle an overloaded ->* operator.
750 SVal ThisVal = Base ? getSVal(Base) : UnknownVal();
751
752 if (isa<NonLoc>(ThisVal)) {
753 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
754 QualType OriginalTy = ThisVal.getType(SVB.getContext());
755 return SVB.evalCast(ThisVal, Base->getType(), OriginalTy);
756 }
757
758 assert(ThisVal.isUnknownOrUndef() || isa<Loc>(ThisVal));
759 return ThisVal;
760}
761
762std::pair<const CXXRecordDecl *, bool>
764 const MemRegion *R = getCXXThisVal().getAsRegion();
765 if (!R)
766 return {};
767
769 if (!DynType.isValid())
770 return {};
771
772 assert(!DynType.getType()->getPointeeType().isNull());
773 return {DynType.getType()->getPointeeCXXRecordDecl(),
774 DynType.canBeASubClass()};
775}
776
778 // Do we have a decl at all?
779 const Decl *D = getDecl();
780 if (!D)
781 return {};
782
783 // If the method is non-virtual, we know we can inline it.
784 const auto *MD = cast<CXXMethodDecl>(D);
785 if (!MD->isVirtual())
787
788 auto [RD, CanBeSubClass] = getDeclForDynamicType();
789 if (!RD || !RD->hasDefinition())
790 return {};
791
792 // Find the decl for this method in that class.
793 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
794 if (!Result) {
795 // We might not even get the original statically-resolved method due to
796 // some particularly nasty casting (e.g. casts to sister classes).
797 // However, we should at least be able to search up and down our own class
798 // hierarchy, and some real bugs have been caught by checking this.
799 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
800
801 // FIXME: This is checking that our DynamicTypeInfo is at least as good as
802 // the static type. However, because we currently don't update
803 // DynamicTypeInfo when an object is cast, we can't actually be sure the
804 // DynamicTypeInfo is up to date. This assert should be re-enabled once
805 // this is fixed.
806 //
807 // assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
808
809 return {};
810 }
811
812 // Does the decl that we found have an implementation?
814 if (!Result->hasBody(Definition)) {
815 if (!CanBeSubClass)
817 return {};
818 }
819
820 // We found a definition. If we're not sure that this devirtualization is
821 // actually what will happen at runtime, make sure to provide the region so
822 // that ExprEngine can decide what to do with it.
823 if (CanBeSubClass)
825 getCXXThisVal().getAsRegion()->StripCasts());
826 return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
827}
828
830 const StackFrameContext *CalleeCtx,
831 BindingsTy &Bindings) const {
833
834 // Handle the binding of 'this' in the new stack frame.
835 SVal ThisVal = getCXXThisVal();
836 if (!ThisVal.isUnknown()) {
837 ProgramStateManager &StateMgr = getState()->getStateManager();
838 SValBuilder &SVB = StateMgr.getSValBuilder();
839
840 const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
841 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
842
843 // If we devirtualized to a different member function, we need to make sure
844 // we have the proper layering of CXXBaseObjectRegions.
845 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
846 ASTContext &Ctx = SVB.getContext();
847 const CXXRecordDecl *Class = MD->getParent();
849
850 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
851 std::optional<SVal> V =
852 StateMgr.getStoreManager().evalBaseToDerived(ThisVal, Ty);
853 if (!V) {
854 // We might have suffered some sort of placement new earlier, so
855 // we're constructing in a completely unexpected storage.
856 // Fall back to a generic pointer cast for this-value.
857 const CXXMethodDecl *StaticMD = cast<CXXMethodDecl>(getDecl());
858 const CXXRecordDecl *StaticClass = StaticMD->getParent();
859 CanQualType StaticTy =
860 Ctx.getPointerType(Ctx.getCanonicalTagType(StaticClass));
861 ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy);
862 } else
863 ThisVal = *V;
864 }
865
866 if (!ThisVal.isUnknown())
867 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
868 }
869}
870
873}
874
876 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
877 // id-expression in the class member access expression is a qualified-id,
878 // that function is called. Otherwise, its final overrider in the dynamic type
879 // of the object expression is called.
880 if (const auto *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
881 if (ME->hasQualifier())
883
885}
886
888 return getOriginExpr()->getArg(0);
889}
890
892 const Expr *Callee = getOriginExpr()->getCallee();
893 const MemRegion *DataReg = getSVal(Callee).getAsRegion();
894
895 return dyn_cast_or_null<BlockDataRegion>(DataReg);
896}
897
899 const BlockDecl *D = getDecl();
900 if (!D)
901 return {};
902 return D->parameters();
903}
904
906 RegionAndSymbolInvalidationTraits *ETraits) const {
907 // FIXME: This also needs to invalidate captured globals.
908 if (const MemRegion *R = getBlockRegion())
909 Values.push_back(loc::MemRegionVal(R));
910}
911
913 BindingsTy &Bindings) const {
914 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
917 auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl());
918 Params = LambdaOperatorDecl->parameters();
919
920 // For blocks converted from a C++ lambda, the callee declaration is the
921 // operator() method on the lambda so we bind "this" to
922 // the lambda captured by the block.
923 const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
924 SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
925 Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx);
926 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
927 } else {
928 Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters();
929 }
930
931 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
932 Params);
933}
934
936 if (Data)
937 return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
938 return UnknownVal();
939}
940
942 RegionAndSymbolInvalidationTraits *ETraits) const {
943 SVal V = getCXXThisVal();
944 if (SymbolRef Sym = V.getAsSymbol(true))
945 ETraits->setTrait(Sym,
947
948 // Standard classes don't reinterpret-cast and modify super regions.
949 const bool IsStdClassCtor = isWithinStdNamespace(getDecl());
950 if (const MemRegion *Obj = V.getAsRegion(); Obj && IsStdClassCtor) {
951 ETraits->setTrait(
953 }
954
955 Values.push_back(V);
956}
957
959 const StackFrameContext *CalleeCtx,
960 BindingsTy &Bindings) const {
962
963 SVal ThisVal = getCXXThisVal();
964 if (!ThisVal.isUnknown()) {
965 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
966 const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
967 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
968 Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
969 }
970}
971
972const StackFrameContext *
975 while (isa<CXXInheritedCtorInitExpr>(SFC->getCallSite()))
976 SFC = SFC->getParent()->getStackFrame();
977 return SFC;
978}
979
981 if (Data)
982 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
983 return UnknownVal();
984}
985
987 // Base destructors are always called non-virtually.
988 // Skip CXXInstanceCall's devirtualization logic in this case.
989 if (isBaseDestructor())
991
993}
994
996 const ObjCMethodDecl *D = getDecl();
997 if (!D)
998 return {};
999 return D->parameters();
1000}
1001
1003 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
1004
1005 // If the method call is a setter for property known to be backed by
1006 // an instance variable, don't invalidate the entire receiver, just
1007 // the storage for that instance variable.
1008 if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
1009 if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
1010 SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
1011 if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) {
1012 ETraits->setTrait(
1013 IvarRegion,
1015 ETraits->setTrait(
1016 IvarRegion,
1018 Values.push_back(IvarLVal);
1019 }
1020 return;
1021 }
1022 }
1023
1024 Values.push_back(getReceiverSVal());
1025}
1026
1028 // FIXME: Is this the best way to handle class receivers?
1029 if (!isInstanceMessage())
1030 return UnknownVal();
1031
1032 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
1033 return getSVal(RecE);
1034
1035 // An instance message with no expression means we are sending to super.
1036 // In this case the object reference is the same as 'self'.
1037 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
1038 SVal SelfVal = getState()->getSelfSVal(getLocationContext());
1039 assert(SelfVal.isValid() && "Calling super but not in ObjC method");
1040 return SelfVal;
1041}
1042
1044 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
1045 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
1046 return true;
1047
1048 if (!isInstanceMessage())
1049 return false;
1050
1051 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
1052 SVal SelfVal = getState()->getSelfSVal(getLocationContext());
1053
1054 return (RecVal == SelfVal);
1055}
1056
1058 switch (getMessageKind()) {
1059 case OCM_Message:
1060 return getOriginExpr()->getSourceRange();
1061 case OCM_PropertyAccess:
1062 case OCM_Subscript:
1063 return getContainingPseudoObjectExpr()->getSourceRange();
1064 }
1065 llvm_unreachable("unknown message kind");
1066}
1067
1068using ObjCMessageDataTy = llvm::PointerIntPair<const PseudoObjectExpr *, 2>;
1069
1070const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
1071 assert(Data && "Lazy lookup not yet performed.");
1072 assert(getMessageKind() != OCM_Message && "Explicit message send.");
1073 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
1074}
1075
1076static const Expr *
1078 const Expr *Syntactic = POE->getSyntacticForm()->IgnoreParens();
1079
1080 // This handles the funny case of assigning to the result of a getter.
1081 // This can happen if the getter returns a non-const reference.
1082 if (const auto *BO = dyn_cast<BinaryOperator>(Syntactic))
1083 Syntactic = BO->getLHS()->IgnoreParens();
1084
1085 return Syntactic;
1086}
1087
1089 if (!Data) {
1090 // Find the parent, ignoring implicit casts.
1091 const ParentMap &PM = getLocationContext()->getParentMap();
1093
1094 // Check if parent is a PseudoObjectExpr.
1095 if (const auto *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
1096 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
1097
1099 switch (Syntactic->getStmtClass()) {
1100 case Stmt::ObjCPropertyRefExprClass:
1102 break;
1103 case Stmt::ObjCSubscriptRefExprClass:
1104 K = OCM_Subscript;
1105 break;
1106 default:
1107 // FIXME: Can this ever happen?
1108 K = OCM_Message;
1109 break;
1110 }
1111
1112 if (K != OCM_Message) {
1113 const_cast<ObjCMethodCall *>(this)->Data
1114 = ObjCMessageDataTy(POE, K).getOpaqueValue();
1115 assert(getMessageKind() == K);
1116 return K;
1117 }
1118 }
1119
1120 const_cast<ObjCMethodCall *>(this)->Data
1121 = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
1122 assert(getMessageKind() == OCM_Message);
1123 return OCM_Message;
1124 }
1125
1126 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
1127 if (!Info.getPointer())
1128 return OCM_Message;
1129 return static_cast<ObjCMessageKind>(Info.getInt());
1130}
1131
1133 // Look for properties accessed with property syntax (foo.bar = ...)
1135 const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
1136 assert(POE && "Property access without PseudoObjectExpr?");
1137
1138 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
1139 auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
1140
1141 if (RefExpr->isExplicitProperty())
1142 return RefExpr->getExplicitProperty();
1143 }
1144
1145 // Look for properties accessed with method syntax ([foo setBar:...]).
1146 const ObjCMethodDecl *MD = getDecl();
1147 if (!MD || !MD->isPropertyAccessor())
1148 return nullptr;
1149
1150 // Note: This is potentially quite slow.
1151 return MD->findPropertyDecl();
1152}
1153
1155 Selector Sel) const {
1156 assert(IDecl);
1157 AnalysisManager &AMgr =
1158 getState()->getStateManager().getOwningEngine().getAnalysisManager();
1159 // If the class interface is declared inside the main file, assume it is not
1160 // subcassed.
1161 // TODO: It could actually be subclassed if the subclass is private as well.
1162 // This is probably very rare.
1163 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
1164 if (InterfLoc.isValid() && AMgr.isInCodeFile(InterfLoc))
1165 return false;
1166
1167 // Assume that property accessors are not overridden.
1169 return false;
1170
1171 // We assume that if the method is public (declared outside of main file) or
1172 // has a parent which publicly declares the method, the method could be
1173 // overridden in a subclass.
1174
1175 // Find the first declaration in the class hierarchy that declares
1176 // the selector.
1177 ObjCMethodDecl *D = nullptr;
1178 while (true) {
1179 D = IDecl->lookupMethod(Sel, true);
1180
1181 // Cannot find a public definition.
1182 if (!D)
1183 return false;
1184
1185 // If outside the main file,
1186 if (D->getLocation().isValid() && !AMgr.isInCodeFile(D->getLocation()))
1187 return true;
1188
1189 if (D->isOverriding()) {
1190 // Search in the superclass on the next iteration.
1191 IDecl = D->getClassInterface();
1192 if (!IDecl)
1193 return false;
1194
1195 IDecl = IDecl->getSuperClass();
1196 if (!IDecl)
1197 return false;
1198
1199 continue;
1200 }
1201
1202 return false;
1203 };
1204
1205 llvm_unreachable("The while loop should always terminate.");
1206}
1207
1209 if (!MD)
1210 return MD;
1211
1212 // Find the redeclaration that defines the method.
1213 if (!MD->hasBody()) {
1214 for (auto *I : MD->redecls())
1215 if (I->hasBody())
1216 MD = cast<ObjCMethodDecl>(I);
1217 }
1218 return MD;
1219}
1220
1225};
1226
1227namespace llvm {
1228template <> struct DenseMapInfo<PrivateMethodKey> {
1229 using InterfaceInfo = DenseMapInfo<const ObjCInterfaceDecl *>;
1230 using SelectorInfo = DenseMapInfo<Selector>;
1231
1233 return {InterfaceInfo::getEmptyKey(), SelectorInfo::getEmptyKey(), false};
1234 }
1235
1237 return {InterfaceInfo::getTombstoneKey(), SelectorInfo::getTombstoneKey(),
1238 true};
1239 }
1240
1241 static unsigned getHashValue(const PrivateMethodKey &Key) {
1242 return llvm::hash_combine(
1243 llvm::hash_code(InterfaceInfo::getHashValue(Key.Interface)),
1244 llvm::hash_code(SelectorInfo::getHashValue(Key.LookupSelector)),
1245 Key.IsClassMethod);
1246 }
1247
1248 static bool isEqual(const PrivateMethodKey &LHS,
1249 const PrivateMethodKey &RHS) {
1250 return InterfaceInfo::isEqual(LHS.Interface, RHS.Interface) &&
1251 SelectorInfo::isEqual(LHS.LookupSelector, RHS.LookupSelector) &&
1252 LHS.IsClassMethod == RHS.IsClassMethod;
1253 }
1254};
1255} // end namespace llvm
1256
1257static const ObjCMethodDecl *
1259 Selector LookupSelector, bool InstanceMethod) {
1260 // Repeatedly calling lookupPrivateMethod() is expensive, especially
1261 // when in many cases it returns null. We cache the results so
1262 // that repeated queries on the same ObjCIntefaceDecl and Selector
1263 // don't incur the same cost. On some test cases, we can see the
1264 // same query being issued thousands of times.
1265 //
1266 // NOTE: This cache is essentially a "global" variable, but it
1267 // only gets lazily created when we get here. The value of the
1268 // cache probably comes from it being global across ExprEngines,
1269 // where the same queries may get issued. If we are worried about
1270 // concurrency, or possibly loading/unloading ASTs, etc., we may
1271 // need to revisit this someday. In terms of memory, this table
1272 // stays around until clang quits, which also may be bad if we
1273 // need to release memory.
1274 using PrivateMethodCache =
1275 llvm::DenseMap<PrivateMethodKey, std::optional<const ObjCMethodDecl *>>;
1276
1277 static PrivateMethodCache PMC;
1278 std::optional<const ObjCMethodDecl *> &Val =
1279 PMC[{Interface, LookupSelector, InstanceMethod}];
1280
1281 // Query lookupPrivateMethod() if the cache does not hit.
1282 if (!Val) {
1283 Val = Interface->lookupPrivateMethod(LookupSelector, InstanceMethod);
1284
1285 if (!*Val) {
1286 // Query 'lookupMethod' as a backup.
1287 Val = Interface->lookupMethod(LookupSelector, InstanceMethod);
1288 }
1289 }
1290
1291 return *Val;
1292}
1293
1295 const ObjCMessageExpr *E = getOriginExpr();
1296 assert(E);
1297 Selector Sel = E->getSelector();
1298
1299 if (E->isInstanceMessage()) {
1300 // Find the receiver type.
1301 const ObjCObjectType *ReceiverT = nullptr;
1302 bool CanBeSubClassed = false;
1303 bool LookingForInstanceMethod = true;
1304 QualType SupersType = E->getSuperType();
1305 const MemRegion *Receiver = nullptr;
1306
1307 if (!SupersType.isNull()) {
1308 // The receiver is guaranteed to be 'super' in this case.
1309 // Super always means the type of immediate predecessor to the method
1310 // where the call occurs.
1311 ReceiverT = cast<ObjCObjectPointerType>(SupersType)->getObjectType();
1312 } else {
1313 Receiver = getReceiverSVal().getAsRegion();
1314 if (!Receiver)
1315 return {};
1316
1317 DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
1318 if (!DTI.isValid()) {
1319 assert(isa<AllocaRegion>(Receiver) &&
1320 "Unhandled untyped region class!");
1321 return {};
1322 }
1323
1324 QualType DynType = DTI.getType();
1325 CanBeSubClassed = DTI.canBeASubClass();
1326
1327 const auto *ReceiverDynT =
1328 dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType());
1329
1330 if (ReceiverDynT) {
1331 ReceiverT = ReceiverDynT->getObjectType();
1332
1333 // It can be actually class methods called with Class object as a
1334 // receiver. This type of messages is treated by the compiler as
1335 // instance (not class).
1336 if (ReceiverT->isObjCClass()) {
1337
1338 SVal SelfVal = getState()->getSelfSVal(getLocationContext());
1339 // For [self classMethod], return compiler visible declaration.
1340 if (Receiver == SelfVal.getAsRegion()) {
1341 return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
1342 }
1343
1344 // Otherwise, let's check if we know something about the type
1345 // inside of this class object.
1346 if (SymbolRef ReceiverSym = getReceiverSVal().getAsSymbol()) {
1347 DynamicTypeInfo DTI =
1349 if (DTI.isValid()) {
1350 // Let's use this type for lookup.
1351 ReceiverT =
1352 cast<ObjCObjectType>(DTI.getType().getCanonicalType());
1353
1354 CanBeSubClassed = DTI.canBeASubClass();
1355 // And it should be a class method instead.
1356 LookingForInstanceMethod = false;
1357 }
1358 }
1359 }
1360
1361 if (CanBeSubClassed)
1362 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface())
1363 // Even if `DynamicTypeInfo` told us that it can be
1364 // not necessarily this type, but its descendants, we still want
1365 // to check again if this selector can be actually overridden.
1366 CanBeSubClassed = canBeOverridenInSubclass(IDecl, Sel);
1367 }
1368 }
1369
1370 // Lookup the instance method implementation.
1371 if (ReceiverT)
1372 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface()) {
1373 const ObjCMethodDecl *MD =
1374 lookupRuntimeDefinition(IDecl, Sel, LookingForInstanceMethod);
1375
1376 if (MD && !MD->hasBody())
1377 MD = MD->getCanonicalDecl();
1378
1379 if (CanBeSubClassed)
1380 return RuntimeDefinition(MD, Receiver);
1381 else
1382 return RuntimeDefinition(MD, nullptr);
1383 }
1384 } else {
1385 // This is a class method.
1386 // If we have type info for the receiver class, we are calling via
1387 // class name.
1388 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
1389 // Find/Return the method implementation.
1390 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
1391 }
1392 }
1393
1394 return {};
1395}
1396
1398 if (isInSystemHeader() && !isInstanceMessage()) {
1399 Selector Sel = getSelector();
1400 if (Sel.getNumArgs() == 1 &&
1401 Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
1402 return true;
1403 }
1404
1406}
1407
1409 const StackFrameContext *CalleeCtx,
1410 BindingsTy &Bindings) const {
1411 const auto *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
1412 SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
1413 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
1414 D->parameters());
1415
1416 SVal SelfVal = getReceiverSVal();
1417 if (!SelfVal.isUnknown()) {
1418 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
1419 MemRegionManager &MRMgr = SVB.getRegionManager();
1420 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
1421 Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
1422 }
1423}
1424
1427 const LocationContext *LCtx,
1429 if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(CE))
1430 return create<CXXMemberCall>(MCE, State, LCtx, ElemRef);
1431
1432 if (const auto *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
1433 const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
1434 if (const auto *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) {
1435 if (MD->isImplicitObjectMemberFunction())
1436 return create<CXXMemberOperatorCall>(OpCE, State, LCtx, ElemRef);
1437 if (MD->isStatic())
1438 return create<CXXStaticOperatorCall>(OpCE, State, LCtx, ElemRef);
1439 }
1440
1441 } else if (CE->getCallee()->getType()->isBlockPointerType()) {
1442 return create<BlockCall>(CE, State, LCtx, ElemRef);
1443 }
1444
1445 // Otherwise, it's a normal function call, static member function call, or
1446 // something we can't reason about.
1447 return create<SimpleFunctionCall>(CE, State, LCtx, ElemRef);
1448}
1449
1452 ProgramStateRef State) {
1453 const LocationContext *ParentCtx = CalleeCtx->getParent();
1454 const LocationContext *CallerCtx = ParentCtx->getStackFrame();
1455 CFGBlock::ConstCFGElementRef ElemRef = {CalleeCtx->getCallSiteBlock(),
1456 CalleeCtx->getIndex()};
1457 assert(CallerCtx && "This should not be used for top-level stack frames");
1458
1459 const Stmt *CallSite = CalleeCtx->getCallSite();
1460
1461 if (CallSite) {
1462 if (CallEventRef<> Out = getCall(CallSite, State, CallerCtx, ElemRef))
1463 return Out;
1464
1465 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1466 const auto *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
1467 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
1468 SVal ThisVal = State->getSVal(ThisPtr);
1469
1470 if (const auto *CE = dyn_cast<CXXConstructExpr>(CallSite))
1471 return getCXXConstructorCall(CE, ThisVal.getAsRegion(), State, CallerCtx,
1472 ElemRef);
1473 else if (const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(CallSite))
1474 return getCXXInheritedConstructorCall(CIE, ThisVal.getAsRegion(), State,
1475 CallerCtx, ElemRef);
1476 else {
1477 // All other cases are handled by getCall.
1478 llvm_unreachable("This is not an inlineable statement");
1479 }
1480 }
1481
1482 // Fall back to the CFG. The only thing we haven't handled yet is
1483 // destructors, though this could change in the future.
1484 const CFGBlock *B = CalleeCtx->getCallSiteBlock();
1485 CFGElement E = (*B)[CalleeCtx->getIndex()];
1486 assert((E.getAs<CFGImplicitDtor>() || E.getAs<CFGTemporaryDtor>()) &&
1487 "All other CFG elements should have exprs");
1488
1489 SValBuilder &SVB = State->getStateManager().getSValBuilder();
1490 const auto *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
1491 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
1492 SVal ThisVal = State->getSVal(ThisPtr);
1493
1494 const Stmt *Trigger;
1495 if (std::optional<CFGAutomaticObjDtor> AutoDtor =
1496 E.getAs<CFGAutomaticObjDtor>())
1497 Trigger = AutoDtor->getTriggerStmt();
1498 else if (std::optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
1499 Trigger = DeleteDtor->getDeleteExpr();
1500 else
1501 Trigger = Dtor->getBody();
1502
1503 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
1504 E.getAs<CFGBaseDtor>().has_value(), State,
1505 CallerCtx, ElemRef);
1506}
1507
1509 const LocationContext *LC,
1511 if (const auto *CE = dyn_cast<CallExpr>(S)) {
1512 return getSimpleCall(CE, State, LC, ElemRef);
1513 } else if (const auto *NE = dyn_cast<CXXNewExpr>(S)) {
1514 return getCXXAllocatorCall(NE, State, LC, ElemRef);
1515 } else if (const auto *DE = dyn_cast<CXXDeleteExpr>(S)) {
1516 return getCXXDeallocatorCall(DE, State, LC, ElemRef);
1517 } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1518 return getObjCMethodCall(ME, State, LC, ElemRef);
1519 } else {
1520 return nullptr;
1521 }
1522}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3597
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:102
static const ObjCMethodDecl * findDefiningRedecl(const ObjCMethodDecl *MD)
Definition: CallEvent.cpp:1208
static const ObjCMethodDecl * lookupRuntimeDefinition(const ObjCInterfaceDecl *Interface, Selector LookupSelector, bool InstanceMethod)
Definition: CallEvent.cpp:1258
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:1077
static bool isTransparentUnion(QualType T)
Definition: CallEvent.cpp:392
llvm::PointerIntPair< const PseudoObjectExpr *, 2 > ObjCMessageDataTy
Definition: CallEvent.cpp:1068
static bool isCallback(QualType T)
Definition: CallEvent.cpp:78
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:221
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 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 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:793
CanQualType VoidTy
Definition: ASTContext.h:1222
CanQualType getCanonicalTagType(const TagDecl *TD) const
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:4634
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Definition: CFG.h:418
Represents C++ object destructor implicitly generated for base object in destructor.
Definition: CFG.h:469
Represents a single basic block in a source-level CFG.
Definition: CFG.h:605
unsigned size() const
Definition: CFG.h:952
ElementRefImpl< true > ConstCFGElementRef
Definition: CFG.h:921
Represents a function call that returns a C++ object by value.
Definition: CFG.h:186
Represents C++ constructor call.
Definition: CFG.h:157
Represents C++ object destructor generated from a call to delete.
Definition: CFG.h:443
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:367
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:511
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition: ExprCXX.cpp:722
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2129
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2255
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:1233
bool hasDefinition() const
Definition: DeclCXX.h:561
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2879
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3083
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3062
Expr * getCallee()
Definition: Expr.h:3026
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:439
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1049
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
bool hasAttr() const
Definition: DeclBase.h:577
This represents one expression.
Definition: Expr.h:112
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3069
QualType getType() const
Definition: Expr.h:144
Represents a function declaration or definition.
Definition: Decl.h:1999
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: TypeBase.h:4478
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:300
Represents an ObjC class declaration.
Definition: DeclObjC.h:1154
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:696
SourceLocation getEndOfDefinitionLoc() const
Definition: DeclObjC.h:1878
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:349
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1952
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:940
@ SuperInstance
The receiver is the instance of the superclass object.
Definition: ExprObjC.h:954
@ SuperClass
The receiver is a superclass.
Definition: ExprObjC.h:951
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:1375
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclObjC.cpp:1009
Represents a class type in Objective C.
Definition: TypeBase.h:7707
bool isObjCClass() const
Definition: TypeBase.h:7775
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: TypeBase.h:7940
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:731
Stmt * getParentIgnoreParenCasts(Stmt *) const
Definition: ParentMap.cpp:154
Represents a parameter to a function.
Definition: Decl.h:1789
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: TypeBase.h:3346
Represents a program point just after an implicit call event.
Definition: ProgramPoint.h:607
Represents a program point just before an implicit call event.
Definition: ProgramPoint.h:589
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:6692
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
Definition: Expr.h:6729
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
QualType getCanonicalType() const
Definition: TypeBase.h:8395
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: TypeBase.h:8416
Represents a struct/union/class.
Definition: Decl.h:4309
field_range fields() const
Definition: Decl.h:4512
RecordDecl * getMostRecentDecl()
Definition: Decl.h:4335
RecordDecl * getDefinitionOrSelf() const
Definition: Decl.h:4497
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
RecordDecl * getOriginalDecl() const
Definition: TypeBase.h:6509
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:85
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:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
A container of type source information.
Definition: TypeBase.h:8314
bool isBlockPointerType() const
Definition: TypeBase.h:8600
bool isVoidType() const
Definition: TypeBase.h:8936
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:787
bool isFunctionPointerType() const
Definition: TypeBase.h:8647
bool isObjCSelType() const
Definition: TypeBase.h:8794
bool isReferenceType() const
Definition: TypeBase.h:8604
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:1909
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
const RecordType * getAsStructureType() const
Definition: Type.cpp:768
bool isAnyPointerType() const
Definition: TypeBase.h:8588
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
QualType getType() const
Definition: Decl.h:722
Represents a variable declaration or definition.
Definition: Decl.h:925
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:958
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:941
SVal getCXXThisVal() const
Returns the value of the implicit 'this' object.
Definition: CallEvent.cpp:935
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:607
const BlockDataRegion * getBlockRegion() const
Returns the region associated with this instance of the block.
Definition: CallEvent.cpp:891
bool isConversionFromLambda() const
Definition: CallEvent.h:614
ArrayRef< ParmVarDecl * > parameters() const override
Return call's formal parameters.
Definition: CallEvent.cpp:898
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:905
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:624
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:912
const CallExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:592
BlockDataRegion - A region that represents a block instance.
Definition: MemRegion.h:706
SVal getCXXThisVal() const override
Returns the value of the implicit 'this' object.
Definition: CallEvent.cpp:980
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
Definition: CallEvent.cpp:986
bool isBaseDestructor() const
Returns true if this is a call to a base class destructor.
Definition: CallEvent.h:941
const StackFrameContext * getInheritingStackFrame() const
Obtain the stack frame of the inheriting constructor.
Definition: CallEvent.cpp:973
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:763
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:717
virtual SVal getCXXThisVal() const
Returns the value of the implicit 'this' object.
Definition: CallEvent.cpp:747
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
Definition: CallEvent.cpp:777
virtual const Expr * getCXXThisExpr() const
Returns the expression representing the implicit 'this' object.
Definition: CallEvent.h:702
const FunctionDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
Definition: CallEvent.cpp:705
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:829
const CXXMemberCallExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:807
const Expr * getCXXThisExpr() const override
Returns the expression representing the implicit 'this' object.
Definition: CallEvent.cpp:871
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
Definition: CallEvent.cpp:875
const Expr * getCXXThisExpr() const override
Returns the expression representing the implicit 'this' object.
Definition: CallEvent.cpp:887
const CXXOperatorCallExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:852
Manages the lifetime of CallEvent objects.
Definition: CallEvent.h:1363
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:1456
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:1508
CallEventRef< CXXDeallocatorCall > getCXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1472
CallEventRef getSimpleCall(const CallExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.cpp:1426
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1434
CallEventRef< CXXAllocatorCall > getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1465
CallEventRef< CXXConstructorCall > getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1441
CallEventRef< CXXInheritedConstructorCall > getCXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *E, const MemRegion *Target, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1448
CallEventRef getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State)
Gets an outside caller given a callee context.
Definition: CallEvent.cpp:1451
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:314
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:346
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:193
bool isCalledFromSystemHeader() const
Definition: CallEvent.cpp:534
AnalysisDeclContext * getCalleeAnalysisDeclContext() const
Returns AnalysisDeclContext for the callee stack frame.
Definition: CallEvent.cpp:151
ProgramStateRef invalidateRegions(unsigned BlockCount, ProgramStateRef Orig=nullptr) const
Returns a new state with all argument regions invalidated.
Definition: CallEvent.cpp:232
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:70
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:143
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:287
const StackFrameContext * getCalleeStackFrame(unsigned BlockCount) const
Returns the callee stack frame.
Definition: CallEvent.cpp:163
static QualType getDeclaredResultType(const Decl *D)
Returns the result type of a function or method declaration.
Definition: CallEvent.cpp:350
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:379
virtual SVal getArgSVal(unsigned Index) const
Returns the value of a given argument at the time of the call.
Definition: CallEvent.cpp:307
bool hasNonNullArgumentsWithType(bool(*Condition)(QualType)) const
Returns true if the type of any of the non-null arguments satisfies the condition.
Definition: CallEvent.cpp:112
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:139
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:321
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
const CFGBlock::ConstCFGElementRef & getCFGElementRef() const
Definition: CallEvent.h:240
bool hasNonZeroCallbackArg() const
Returns true if any of the arguments appear to represent callbacks.
Definition: CallEvent.cpp:135
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:220
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:1041
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:1160
MemRegion - The root abstract class for all memory regions.
Definition: MemRegion.h:98
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
Definition: MemRegion.cpp:1422
Represents any expression that calls an Objective-C method.
Definition: CallEvent.h:1250
const ObjCMethodDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
Definition: CallEvent.h:1280
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:1002
bool isInstanceMessage() const
Definition: CallEvent.h:1290
ObjCMessageKind getMessageKind() const
Returns how the message was written in the source (property access, subscript, or explicit message se...
Definition: CallEvent.cpp:1088
const ObjCMessageExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition: CallEvent.h:1276
ArrayRef< ParmVarDecl * > parameters() const override
Return call's formal parameters.
Definition: CallEvent.cpp:995
SourceRange getSourceRange() const override
Returns a source range for the entire call, suitable for outputting in diagnostics.
Definition: CallEvent.cpp:1057
virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, Selector Sel) const
Check if the selector may have multiple definitions (may have overrides).
Definition: CallEvent.cpp:1154
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:1397
SVal getReceiverSVal() const
Returns the value of the receiver at the time of this call.
Definition: CallEvent.cpp:1027
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
Definition: CallEvent.cpp:1294
bool isReceiverSelfOrSuper() const
Checks if the receiver refers to 'self' or 'super'.
Definition: CallEvent.cpp:1043
Selector getSelector() const
Definition: CallEvent.h:1298
const ObjCPropertyDecl * getAccessedProperty() const
Definition: CallEvent.cpp:1132
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:1408
ParamVarRegion - Represents a region for parameters.
Definition: MemRegion.h:1062
Information about invalidation for a particular region/symbol.
Definition: MemRegion.h:1657
@ TK_PreserveContents
Tells that a region's contents is not changed.
Definition: MemRegion.h:1672
@ TK_SuppressEscape
Suppress pointer-escaping of a region.
Definition: MemRegion.h:1675
void setTrait(SymbolRef Sym, InvalidationKinds IK)
Definition: MemRegion.cpp:1847
Defines the runtime definition of the called function.
Definition: CallEvent.h:110
BasicValueFactory & getBasicValueFactory()
Definition: SValBuilder.h:162
NonLoc makeCompoundVal(QualType type, llvm::ImmutableList< SVal > vals)
Definition: SValBuilder.h:249
MemRegionManager & getRegionManager()
Definition: SValBuilder.h:168
ASTContext & getContext()
Definition: SValBuilder.h:149
loc::MemRegionVal makeLoc(SymbolRef sym)
Definition: SValBuilder.h:363
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:45
QualType getType(const ASTContext &) const
Try to get a reasonable type for the given value.
Definition: SVals.cpp:180
const MemRegion * getAsRegion() const
Definition: SVals.cpp:119
bool isValid() const
Definition: SVals.h:111
bool isUnknown() const
Definition: SVals.h:105
RuntimeDefinition getRuntimeDefinition() const override
Returns the definition of the function or method that will be called.
Definition: CallEvent.cpp:693
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:318
Symbolic value.
Definition: SymExpr.h:32
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:563
static const FunctionDecl * getCallee(const CXXConstructExpr &D)
bool isWithinStdNamespace(const Decl *D)
Returns true if declaration D is in std namespace or any nested namespace or class scope.
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:1245
@ OCM_PropertyAccess
Definition: CallEvent.h:1245
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:1223
const ObjCInterfaceDecl * Interface
Definition: CallEvent.cpp:1222
Hints for figuring out of a call should be inlined during evalCall().
Definition: ExprEngine.h:97
DenseMapInfo< Selector > SelectorInfo
Definition: CallEvent.cpp:1230
static unsigned getHashValue(const PrivateMethodKey &Key)
Definition: CallEvent.cpp:1241
static PrivateMethodKey getEmptyKey()
Definition: CallEvent.cpp:1232
DenseMapInfo< const ObjCInterfaceDecl * > InterfaceInfo
Definition: CallEvent.cpp:1229
static bool isEqual(const PrivateMethodKey &LHS, const PrivateMethodKey &RHS)
Definition: CallEvent.cpp:1248
static PrivateMethodKey getTombstoneKey()
Definition: CallEvent.cpp:1236