Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.0.0git
ExprEngine.cpp
Go to the documentation of this file.
1//===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
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// This file defines a meta-engine for path-sensitive dataflow analysis that
10// is built on CoreEngine, but provides the boilerplate to execute transfer
11// functions and build the ExplodedGraph at the expression level.
12//
13//===----------------------------------------------------------------------===//
14
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"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/StmtObjC.h"
30#include "clang/AST/Type.h"
32#include "clang/Analysis/CFG.h"
37#include "clang/Basic/LLVM.h"
64#include "llvm/ADT/APSInt.h"
65#include "llvm/ADT/DenseMap.h"
66#include "llvm/ADT/ImmutableMap.h"
67#include "llvm/ADT/ImmutableSet.h"
68#include "llvm/ADT/STLExtras.h"
69#include "llvm/ADT/SmallVector.h"
70#include "llvm/Support/Casting.h"
71#include "llvm/Support/Compiler.h"
72#include "llvm/Support/DOTGraphTraits.h"
73#include "llvm/Support/ErrorHandling.h"
74#include "llvm/Support/GraphWriter.h"
75#include "llvm/Support/TimeProfiler.h"
76#include "llvm/Support/raw_ostream.h"
77#include <cassert>
78#include <cstdint>
79#include <memory>
80#include <optional>
81#include <string>
82#include <tuple>
83#include <utility>
84#include <vector>
85
86using namespace clang;
87using namespace ento;
88
89#define DEBUG_TYPE "ExprEngine"
90
91STAT_COUNTER(NumRemoveDeadBindings,
92 "The # of times RemoveDeadBindings is called");
94 NumMaxBlockCountReached,
95 "The # of aborted paths due to reaching the maximum block count in "
96 "a top level function");
98 NumMaxBlockCountReachedInInlined,
99 "The # of aborted paths due to reaching the maximum block count in "
100 "an inlined function");
101STAT_COUNTER(NumTimesRetriedWithoutInlining,
102 "The # of times we re-evaluated a call without inlining");
103
104//===----------------------------------------------------------------------===//
105// Internal program state traits.
106//===----------------------------------------------------------------------===//
107
108namespace {
109
110// When modeling a C++ constructor, for a variety of reasons we need to track
111// the location of the object for the duration of its ConstructionContext.
112// ObjectsUnderConstruction maps statements within the construction context
113// to the object's location, so that on every such statement the location
114// could have been retrieved.
115
116/// ConstructedObjectKey is used for being able to find the path-sensitive
117/// memory region of a freshly constructed object while modeling the AST node
118/// that syntactically represents the object that is being constructed.
119/// Semantics of such nodes may sometimes require access to the region that's
120/// not otherwise present in the program state, or to the very fact that
121/// the construction context was present and contained references to these
122/// AST nodes.
123class ConstructedObjectKey {
124 using ConstructedObjectKeyImpl =
125 std::pair<ConstructionContextItem, const LocationContext *>;
126 const ConstructedObjectKeyImpl Impl;
127
128public:
129 explicit ConstructedObjectKey(const ConstructionContextItem &Item,
130 const LocationContext *LC)
131 : Impl(Item, LC) {}
132
133 const ConstructionContextItem &getItem() const { return Impl.first; }
134 const LocationContext *getLocationContext() const { return Impl.second; }
135
136 ASTContext &getASTContext() const {
137 return getLocationContext()->getDecl()->getASTContext();
138 }
139
140 void printJson(llvm::raw_ostream &Out, PrinterHelper *Helper,
141 PrintingPolicy &PP) const {
142 const Stmt *S = getItem().getStmtOrNull();
143 const CXXCtorInitializer *I = nullptr;
144 if (!S)
145 I = getItem().getCXXCtorInitializer();
146
147 if (S)
148 Out << "\"stmt_id\": " << S->getID(getASTContext());
149 else
150 Out << "\"init_id\": " << I->getID(getASTContext());
151
152 // Kind
153 Out << ", \"kind\": \"" << getItem().getKindAsString()
154 << "\", \"argument_index\": ";
155
157 Out << getItem().getIndex();
158 else
159 Out << "null";
160
161 // Pretty-print
162 Out << ", \"pretty\": ";
163
164 if (S) {
165 S->printJson(Out, Helper, PP, /*AddQuotes=*/true);
166 } else {
167 Out << '\"' << I->getAnyMember()->getDeclName() << '\"';
168 }
169 }
170
171 void Profile(llvm::FoldingSetNodeID &ID) const {
172 ID.Add(Impl.first);
173 ID.AddPointer(Impl.second);
174 }
175
176 bool operator==(const ConstructedObjectKey &RHS) const {
177 return Impl == RHS.Impl;
178 }
179
180 bool operator<(const ConstructedObjectKey &RHS) const {
181 return Impl < RHS.Impl;
182 }
183};
184} // namespace
185
186typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
188REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
190
191// This trait is responsible for storing the index of the element that is to be
192// constructed in the next iteration. As a result a CXXConstructExpr is only
193// stored if it is array type. Also the index is the index of the continuous
194// memory region, which is important for multi-dimensional arrays. E.g:: int
195// arr[2][2]; assume arr[1][1] will be the next element under construction, so
196// the index is 3.
197typedef llvm::ImmutableMap<
198 std::pair<const CXXConstructExpr *, const LocationContext *>, unsigned>
199 IndexOfElementToConstructMap;
200REGISTER_TRAIT_WITH_PROGRAMSTATE(IndexOfElementToConstruct,
201 IndexOfElementToConstructMap)
202
203// This trait is responsible for holding our pending ArrayInitLoopExprs.
204// It pairs the LocationContext and the initializer CXXConstructExpr with
205// the size of the array that's being copy initialized.
206typedef llvm::ImmutableMap<
207 std::pair<const CXXConstructExpr *, const LocationContext *>, unsigned>
208 PendingInitLoopMap;
209REGISTER_TRAIT_WITH_PROGRAMSTATE(PendingInitLoop, PendingInitLoopMap)
210
211typedef llvm::ImmutableMap<const LocationContext *, unsigned>
213REGISTER_TRAIT_WITH_PROGRAMSTATE(PendingArrayDestruction,
215
216//===----------------------------------------------------------------------===//
217// Engine construction and deletion.
218//===----------------------------------------------------------------------===//
219
220static const char* TagProviderName = "ExprEngine";
221
223 AnalysisManager &mgr, SetOfConstDecls *VisitedCalleesIn,
224 FunctionSummariesTy *FS, InliningModes HowToInlineIn)
225 : CTU(CTU), IsCTUEnabled(mgr.getAnalyzerOptions().IsNaiveCTUEnabled),
226 AMgr(mgr), AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
227 Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()),
228 StateMgr(getContext(), mgr.getStoreManagerCreator(),
229 mgr.getConstraintManagerCreator(), G.getAllocator(), this),
230 SymMgr(StateMgr.getSymbolManager()), MRMgr(StateMgr.getRegionManager()),
231 svalBuilder(StateMgr.getSValBuilder()), ObjCNoRet(mgr.getASTContext()),
232 BR(mgr, *this), VisitedCallees(VisitedCalleesIn),
233 HowToInline(HowToInlineIn) {
234 unsigned TrimInterval = mgr.options.GraphTrimInterval;
235 if (TrimInterval != 0) {
236 // Enable eager node reclamation when constructing the ExplodedGraph.
237 G.enableNodeReclamation(TrimInterval);
238 }
239}
240
241//===----------------------------------------------------------------------===//
242// Utility methods.
243//===----------------------------------------------------------------------===//
244
246 ProgramStateRef state = StateMgr.getInitialState(InitLoc);
247 const Decl *D = InitLoc->getDecl();
248
249 // Preconditions.
250 // FIXME: It would be nice if we had a more general mechanism to add
251 // such preconditions. Some day.
252 do {
253 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
254 // Precondition: the first argument of 'main' is an integer guaranteed
255 // to be > 0.
256 const IdentifierInfo *II = FD->getIdentifier();
257 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
258 break;
259
260 const ParmVarDecl *PD = FD->getParamDecl(0);
261 QualType T = PD->getType();
262 const auto *BT = dyn_cast<BuiltinType>(T);
263 if (!BT || !BT->isInteger())
264 break;
265
266 const MemRegion *R = state->getRegion(PD, InitLoc);
267 if (!R)
268 break;
269
270 SVal V = state->getSVal(loc::MemRegionVal(R));
271 SVal Constraint_untested = evalBinOp(state, BO_GT, V,
272 svalBuilder.makeZeroVal(T),
273 svalBuilder.getConditionType());
274
275 std::optional<DefinedOrUnknownSVal> Constraint =
276 Constraint_untested.getAs<DefinedOrUnknownSVal>();
277
278 if (!Constraint)
279 break;
280
281 if (ProgramStateRef newState = state->assume(*Constraint, true))
282 state = newState;
283 }
284 break;
285 }
286 while (false);
287
288 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
289 // Precondition: 'self' is always non-null upon entry to an Objective-C
290 // method.
291 const ImplicitParamDecl *SelfD = MD->getSelfDecl();
292 const MemRegion *R = state->getRegion(SelfD, InitLoc);
293 SVal V = state->getSVal(loc::MemRegionVal(R));
294
295 if (std::optional<Loc> LV = V.getAs<Loc>()) {
296 // Assume that the pointer value in 'self' is non-null.
297 state = state->assume(*LV, true);
298 assert(state && "'self' cannot be null");
299 }
300 }
301
302 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
303 if (MD->isImplicitObjectMemberFunction()) {
304 // Precondition: 'this' is always non-null upon entry to the
305 // top-level function. This is our starting assumption for
306 // analyzing an "open" program.
307 const StackFrameContext *SFC = InitLoc->getStackFrame();
308 if (SFC->getParent() == nullptr) {
309 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
310 SVal V = state->getSVal(L);
311 if (std::optional<Loc> LV = V.getAs<Loc>()) {
312 state = state->assume(*LV, true);
313 assert(state && "'this' cannot be null");
314 }
315 }
316 }
317 }
318
319 return state;
320}
321
322ProgramStateRef ExprEngine::createTemporaryRegionIfNeeded(
323 ProgramStateRef State, const LocationContext *LC,
324 const Expr *InitWithAdjustments, const Expr *Result,
325 const SubRegion **OutRegionWithAdjustments) {
326 // FIXME: This function is a hack that works around the quirky AST
327 // we're often having with respect to C++ temporaries. If only we modelled
328 // the actual execution order of statements properly in the CFG,
329 // all the hassle with adjustments would not be necessary,
330 // and perhaps the whole function would be removed.
331 SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
332 if (!Result) {
333 // If we don't have an explicit result expression, we're in "if needed"
334 // mode. Only create a region if the current value is a NonLoc.
335 if (!isa<NonLoc>(InitValWithAdjustments)) {
336 if (OutRegionWithAdjustments)
337 *OutRegionWithAdjustments = nullptr;
338 return State;
339 }
340 Result = InitWithAdjustments;
341 } else {
342 // We need to create a region no matter what. Make sure we don't try to
343 // stuff a Loc into a non-pointer temporary region.
344 assert(!isa<Loc>(InitValWithAdjustments) ||
345 Loc::isLocType(Result->getType()) ||
346 Result->getType()->isMemberPointerType());
347 }
348
349 ProgramStateManager &StateMgr = State->getStateManager();
350 MemRegionManager &MRMgr = StateMgr.getRegionManager();
351 StoreManager &StoreMgr = StateMgr.getStoreManager();
352
353 // MaterializeTemporaryExpr may appear out of place, after a few field and
354 // base-class accesses have been made to the object, even though semantically
355 // it is the whole object that gets materialized and lifetime-extended.
356 //
357 // For example:
358 //
359 // `-MaterializeTemporaryExpr
360 // `-MemberExpr
361 // `-CXXTemporaryObjectExpr
362 //
363 // instead of the more natural
364 //
365 // `-MemberExpr
366 // `-MaterializeTemporaryExpr
367 // `-CXXTemporaryObjectExpr
368 //
369 // Use the usual methods for obtaining the expression of the base object,
370 // and record the adjustments that we need to make to obtain the sub-object
371 // that the whole expression 'Ex' refers to. This trick is usual,
372 // in the sense that CodeGen takes a similar route.
373
374 SmallVector<const Expr *, 2> CommaLHSs;
375 SmallVector<SubobjectAdjustment, 2> Adjustments;
376
377 const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
378 CommaLHSs, Adjustments);
379
380 // Take the region for Init, i.e. for the whole object. If we do not remember
381 // the region in which the object originally was constructed, come up with
382 // a new temporary region out of thin air and copy the contents of the object
383 // (which are currently present in the Environment, because Init is an rvalue)
384 // into that region. This is not correct, but it is better than nothing.
385 const TypedValueRegion *TR = nullptr;
386 if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
387 if (std::optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
388 State = finishObjectConstruction(State, MT, LC);
389 State = State->BindExpr(Result, LC, *V);
390 return State;
391 } else if (const ValueDecl *VD = MT->getExtendingDecl()) {
392 StorageDuration SD = MT->getStorageDuration();
393 assert(SD != SD_FullExpression);
394 // If this object is bound to a reference with static storage duration, we
395 // put it in a different region to prevent "address leakage" warnings.
396 if (SD == SD_Static || SD == SD_Thread) {
397 TR = MRMgr.getCXXStaticLifetimeExtendedObjectRegion(Init, VD);
398 } else {
399 TR = MRMgr.getCXXLifetimeExtendedObjectRegion(Init, VD, LC);
400 }
401 } else {
402 assert(MT->getStorageDuration() == SD_FullExpression);
403 TR = MRMgr.getCXXTempObjectRegion(Init, LC);
404 }
405 } else {
406 TR = MRMgr.getCXXTempObjectRegion(Init, LC);
407 }
408
409 SVal Reg = loc::MemRegionVal(TR);
410 SVal BaseReg = Reg;
411
412 // Make the necessary adjustments to obtain the sub-object.
413 for (const SubobjectAdjustment &Adj : llvm::reverse(Adjustments)) {
414 switch (Adj.Kind) {
416 Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
417 break;
419 Reg = StoreMgr.getLValueField(Adj.Field, Reg);
420 break;
422 // FIXME: Unimplemented.
423 State = State->invalidateRegions(Reg, getCFGElementRef(),
424 currBldrCtx->blockCount(), LC, true,
425 nullptr, nullptr, nullptr);
426 return State;
427 }
428 }
429
430 // What remains is to copy the value of the object to the new region.
431 // FIXME: In other words, what we should always do is copy value of the
432 // Init expression (which corresponds to the bigger object) to the whole
433 // temporary region TR. However, this value is often no longer present
434 // in the Environment. If it has disappeared, we instead invalidate TR.
435 // Still, what we can do is assign the value of expression Ex (which
436 // corresponds to the sub-object) to the TR's sub-region Reg. At least,
437 // values inside Reg would be correct.
438 SVal InitVal = State->getSVal(Init, LC);
439 if (InitVal.isUnknown()) {
441 getCFGElementRef(), LC, Init->getType(), currBldrCtx->blockCount());
442 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
443
444 // Then we'd need to take the value that certainly exists and bind it
445 // over.
446 if (InitValWithAdjustments.isUnknown()) {
447 // Try to recover some path sensitivity in case we couldn't
448 // compute the value.
449 InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
450 getCFGElementRef(), LC, InitWithAdjustments->getType(),
451 currBldrCtx->blockCount());
452 }
453 State =
454 State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
455 } else {
456 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
457 }
458
459 // The result expression would now point to the correct sub-region of the
460 // newly created temporary region. Do this last in order to getSVal of Init
461 // correctly in case (Result == Init).
462 if (Result->isGLValue()) {
463 State = State->BindExpr(Result, LC, Reg);
464 } else {
465 State = State->BindExpr(Result, LC, InitValWithAdjustments);
466 }
467
468 // Notify checkers once for two bindLoc()s.
469 State = processRegionChange(State, TR, LC);
470
471 if (OutRegionWithAdjustments)
472 *OutRegionWithAdjustments = cast<SubRegion>(Reg.getAsRegion());
473 return State;
474}
475
476ProgramStateRef ExprEngine::setIndexOfElementToConstruct(
477 ProgramStateRef State, const CXXConstructExpr *E,
478 const LocationContext *LCtx, unsigned Idx) {
479 auto Key = std::make_pair(E, LCtx->getStackFrame());
480
481 assert(!State->contains<IndexOfElementToConstruct>(Key) || Idx > 0);
482
483 return State->set<IndexOfElementToConstruct>(Key, Idx);
484}
485
486std::optional<unsigned>
488 const LocationContext *LCtx) {
489 const unsigned *V = State->get<PendingInitLoop>({E, LCtx->getStackFrame()});
490 return V ? std::make_optional(*V) : std::nullopt;
491}
492
493ProgramStateRef ExprEngine::removePendingInitLoop(ProgramStateRef State,
494 const CXXConstructExpr *E,
495 const LocationContext *LCtx) {
496 auto Key = std::make_pair(E, LCtx->getStackFrame());
497
498 assert(E && State->contains<PendingInitLoop>(Key));
499 return State->remove<PendingInitLoop>(Key);
500}
501
502ProgramStateRef ExprEngine::setPendingInitLoop(ProgramStateRef State,
503 const CXXConstructExpr *E,
504 const LocationContext *LCtx,
505 unsigned Size) {
506 auto Key = std::make_pair(E, LCtx->getStackFrame());
507
508 assert(!State->contains<PendingInitLoop>(Key) && Size > 0);
509
510 return State->set<PendingInitLoop>(Key, Size);
511}
512
513std::optional<unsigned>
515 const CXXConstructExpr *E,
516 const LocationContext *LCtx) {
517 const unsigned *V =
518 State->get<IndexOfElementToConstruct>({E, LCtx->getStackFrame()});
519 return V ? std::make_optional(*V) : std::nullopt;
520}
521
523ExprEngine::removeIndexOfElementToConstruct(ProgramStateRef State,
524 const CXXConstructExpr *E,
525 const LocationContext *LCtx) {
526 auto Key = std::make_pair(E, LCtx->getStackFrame());
527
528 assert(E && State->contains<IndexOfElementToConstruct>(Key));
529 return State->remove<IndexOfElementToConstruct>(Key);
530}
531
532std::optional<unsigned>
534 const LocationContext *LCtx) {
535 assert(LCtx && "LocationContext shouldn't be null!");
536
537 const unsigned *V =
538 State->get<PendingArrayDestruction>(LCtx->getStackFrame());
539 return V ? std::make_optional(*V) : std::nullopt;
540}
541
542ProgramStateRef ExprEngine::setPendingArrayDestruction(
543 ProgramStateRef State, const LocationContext *LCtx, unsigned Idx) {
544 assert(LCtx && "LocationContext shouldn't be null!");
545
546 auto Key = LCtx->getStackFrame();
547
548 return State->set<PendingArrayDestruction>(Key, Idx);
549}
550
552ExprEngine::removePendingArrayDestruction(ProgramStateRef State,
553 const LocationContext *LCtx) {
554 assert(LCtx && "LocationContext shouldn't be null!");
555
556 auto Key = LCtx->getStackFrame();
557
558 assert(LCtx && State->contains<PendingArrayDestruction>(Key));
559 return State->remove<PendingArrayDestruction>(Key);
560}
561
563ExprEngine::addObjectUnderConstruction(ProgramStateRef State,
564 const ConstructionContextItem &Item,
565 const LocationContext *LC, SVal V) {
566 ConstructedObjectKey Key(Item, LC->getStackFrame());
567
568 const Expr *Init = nullptr;
569
570 if (auto DS = dyn_cast_or_null<DeclStmt>(Item.getStmtOrNull())) {
571 if (auto VD = dyn_cast_or_null<VarDecl>(DS->getSingleDecl()))
572 Init = VD->getInit();
573 }
574
575 if (auto LE = dyn_cast_or_null<LambdaExpr>(Item.getStmtOrNull()))
576 Init = *(LE->capture_init_begin() + Item.getIndex());
577
578 if (!Init && !Item.getStmtOrNull())
580
581 // In an ArrayInitLoopExpr the real initializer is returned by
582 // getSubExpr(). Note that AILEs can be nested in case of
583 // multidimesnional arrays.
584 if (const auto *AILE = dyn_cast_or_null<ArrayInitLoopExpr>(Init))
586
587 // FIXME: Currently the state might already contain the marker due to
588 // incorrect handling of temporaries bound to default parameters.
589 // The state will already contain the marker if we construct elements
590 // in an array, as we visit the same statement multiple times before
591 // the array declaration. The marker is removed when we exit the
592 // constructor call.
593 assert((!State->get<ObjectsUnderConstruction>(Key) ||
594 Key.getItem().getKind() ==
596 State->contains<IndexOfElementToConstruct>(
597 {dyn_cast_or_null<CXXConstructExpr>(Init), LC})) &&
598 "The object is already marked as `UnderConstruction`, when it's not "
599 "supposed to!");
600 return State->set<ObjectsUnderConstruction>(Key, V);
601}
602
603std::optional<SVal>
605 const ConstructionContextItem &Item,
606 const LocationContext *LC) {
607 ConstructedObjectKey Key(Item, LC->getStackFrame());
608 const SVal *V = State->get<ObjectsUnderConstruction>(Key);
609 return V ? std::make_optional(*V) : std::nullopt;
610}
611
613ExprEngine::finishObjectConstruction(ProgramStateRef State,
614 const ConstructionContextItem &Item,
615 const LocationContext *LC) {
616 ConstructedObjectKey Key(Item, LC->getStackFrame());
617 assert(State->contains<ObjectsUnderConstruction>(Key));
618 return State->remove<ObjectsUnderConstruction>(Key);
619}
620
621ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
622 const CXXBindTemporaryExpr *BTE,
623 const LocationContext *LC) {
624 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
625 // FIXME: Currently the state might already contain the marker due to
626 // incorrect handling of temporaries bound to default parameters.
627 return State->set<ObjectsUnderConstruction>(Key, UnknownVal());
628}
629
631ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
632 const CXXBindTemporaryExpr *BTE,
633 const LocationContext *LC) {
634 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
635 assert(State->contains<ObjectsUnderConstruction>(Key));
636 return State->remove<ObjectsUnderConstruction>(Key);
637}
638
639bool ExprEngine::isDestructorElided(ProgramStateRef State,
640 const CXXBindTemporaryExpr *BTE,
641 const LocationContext *LC) {
642 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
643 return State->contains<ObjectsUnderConstruction>(Key);
644}
645
646bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
647 const LocationContext *FromLC,
648 const LocationContext *ToLC) {
649 const LocationContext *LC = FromLC;
650 while (LC != ToLC) {
651 assert(LC && "ToLC must be a parent of FromLC!");
652 for (auto I : State->get<ObjectsUnderConstruction>())
653 if (I.first.getLocationContext() == LC)
654 return false;
655
656 LC = LC->getParent();
657 }
658 return true;
659}
660
661
662//===----------------------------------------------------------------------===//
663// Top-level transfer function logic (Dispatcher).
664//===----------------------------------------------------------------------===//
665
666/// evalAssume - Called by ConstraintManager. Used to call checker-specific
667/// logic for handling assumptions on symbolic values.
669 SVal cond, bool assumption) {
670 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
671}
672
675 const InvalidatedSymbols *invalidated,
678 const LocationContext *LCtx,
679 const CallEvent *Call) {
680 return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
681 Explicits, Regions,
682 LCtx, Call);
683}
684
685static void
687 const char *NL, const LocationContext *LCtx,
688 unsigned int Space = 0, bool IsDot = false) {
689 PrintingPolicy PP =
691
692 ++Space;
693 bool HasItem = false;
694
695 // Store the last key.
696 const ConstructedObjectKey *LastKey = nullptr;
697 for (const auto &I : State->get<ObjectsUnderConstruction>()) {
698 const ConstructedObjectKey &Key = I.first;
699 if (Key.getLocationContext() != LCtx)
700 continue;
701
702 if (!HasItem) {
703 Out << '[' << NL;
704 HasItem = true;
705 }
706
707 LastKey = &Key;
708 }
709
710 for (const auto &I : State->get<ObjectsUnderConstruction>()) {
711 const ConstructedObjectKey &Key = I.first;
712 SVal Value = I.second;
713 if (Key.getLocationContext() != LCtx)
714 continue;
715
716 Indent(Out, Space, IsDot) << "{ ";
717 Key.printJson(Out, nullptr, PP);
718 Out << ", \"value\": \"" << Value << "\" }";
719
720 if (&Key != LastKey)
721 Out << ',';
722 Out << NL;
723 }
724
725 if (HasItem)
726 Indent(Out, --Space, IsDot) << ']'; // End of "location_context".
727 else {
728 Out << "null ";
729 }
730}
731
733 raw_ostream &Out, ProgramStateRef State, const char *NL,
734 const LocationContext *LCtx, unsigned int Space = 0, bool IsDot = false) {
735 using KeyT = std::pair<const Expr *, const LocationContext *>;
736
737 const auto &Context = LCtx->getAnalysisDeclContext()->getASTContext();
738 PrintingPolicy PP = Context.getPrintingPolicy();
739
740 ++Space;
741 bool HasItem = false;
742
743 // Store the last key.
744 KeyT LastKey;
745 for (const auto &I : State->get<IndexOfElementToConstruct>()) {
746 const KeyT &Key = I.first;
747 if (Key.second != LCtx)
748 continue;
749
750 if (!HasItem) {
751 Out << '[' << NL;
752 HasItem = true;
753 }
754
755 LastKey = Key;
756 }
757
758 for (const auto &I : State->get<IndexOfElementToConstruct>()) {
759 const KeyT &Key = I.first;
760 unsigned Value = I.second;
761 if (Key.second != LCtx)
762 continue;
763
764 Indent(Out, Space, IsDot) << "{ ";
765
766 // Expr
767 const Expr *E = Key.first;
768 Out << "\"stmt_id\": " << E->getID(Context);
769
770 // Kind
771 Out << ", \"kind\": null";
772
773 // Pretty-print
774 Out << ", \"pretty\": ";
775 Out << "\"" << E->getStmtClassName() << ' '
776 << E->getSourceRange().printToString(Context.getSourceManager()) << " '"
777 << QualType::getAsString(E->getType().split(), PP);
778 Out << "'\"";
779
780 Out << ", \"value\": \"Current index: " << Value - 1 << "\" }";
781
782 if (Key != LastKey)
783 Out << ',';
784 Out << NL;
785 }
786
787 if (HasItem)
788 Indent(Out, --Space, IsDot) << ']'; // End of "location_context".
789 else {
790 Out << "null ";
791 }
792}
793
794static void printPendingInitLoopJson(raw_ostream &Out, ProgramStateRef State,
795 const char *NL,
796 const LocationContext *LCtx,
797 unsigned int Space = 0,
798 bool IsDot = false) {
799 using KeyT = std::pair<const CXXConstructExpr *, const LocationContext *>;
800
801 const auto &Context = LCtx->getAnalysisDeclContext()->getASTContext();
802 PrintingPolicy PP = Context.getPrintingPolicy();
803
804 ++Space;
805 bool HasItem = false;
806
807 // Store the last key.
808 KeyT LastKey;
809 for (const auto &I : State->get<PendingInitLoop>()) {
810 const KeyT &Key = I.first;
811 if (Key.second != LCtx)
812 continue;
813
814 if (!HasItem) {
815 Out << '[' << NL;
816 HasItem = true;
817 }
818
819 LastKey = Key;
820 }
821
822 for (const auto &I : State->get<PendingInitLoop>()) {
823 const KeyT &Key = I.first;
824 unsigned Value = I.second;
825 if (Key.second != LCtx)
826 continue;
827
828 Indent(Out, Space, IsDot) << "{ ";
829
830 const CXXConstructExpr *E = Key.first;
831 Out << "\"stmt_id\": " << E->getID(Context);
832
833 Out << ", \"kind\": null";
834 Out << ", \"pretty\": ";
835 Out << '\"' << E->getStmtClassName() << ' '
836 << E->getSourceRange().printToString(Context.getSourceManager()) << " '"
837 << QualType::getAsString(E->getType().split(), PP);
838 Out << "'\"";
839
840 Out << ", \"value\": \"Flattened size: " << Value << "\"}";
841
842 if (Key != LastKey)
843 Out << ',';
844 Out << NL;
845 }
846
847 if (HasItem)
848 Indent(Out, --Space, IsDot) << ']'; // End of "location_context".
849 else {
850 Out << "null ";
851 }
852}
853
854static void
856 const char *NL, const LocationContext *LCtx,
857 unsigned int Space = 0, bool IsDot = false) {
858 using KeyT = const LocationContext *;
859
860 ++Space;
861 bool HasItem = false;
862
863 // Store the last key.
864 KeyT LastKey = nullptr;
865 for (const auto &I : State->get<PendingArrayDestruction>()) {
866 const KeyT &Key = I.first;
867 if (Key != LCtx)
868 continue;
869
870 if (!HasItem) {
871 Out << '[' << NL;
872 HasItem = true;
873 }
874
875 LastKey = Key;
876 }
877
878 for (const auto &I : State->get<PendingArrayDestruction>()) {
879 const KeyT &Key = I.first;
880 if (Key != LCtx)
881 continue;
882
883 Indent(Out, Space, IsDot) << "{ ";
884
885 Out << "\"stmt_id\": null";
886 Out << ", \"kind\": null";
887 Out << ", \"pretty\": \"Current index: \"";
888 Out << ", \"value\": \"" << I.second << "\" }";
889
890 if (Key != LastKey)
891 Out << ',';
892 Out << NL;
893 }
894
895 if (HasItem)
896 Indent(Out, --Space, IsDot) << ']'; // End of "location_context".
897 else {
898 Out << "null ";
899 }
900}
901
902/// A helper function to generalize program state trait printing.
903/// The function invokes Printer as 'Printer(Out, State, NL, LC, Space, IsDot,
904/// std::forward<Args>(args)...)'. \n One possible type for Printer is
905/// 'void()(raw_ostream &, ProgramStateRef, const char *, const LocationContext
906/// *, unsigned int, bool, ...)' \n \param Trait The state trait to be printed.
907/// \param Printer A void function that prints Trait.
908/// \param Args An additional parameter pack that is passed to Print upon
909/// invocation.
910template <typename Trait, typename Printer, typename... Args>
912 raw_ostream &Out, ProgramStateRef State, const LocationContext *LCtx,
913 const char *NL, unsigned int Space, bool IsDot,
914 const char *jsonPropertyName, Printer printer, Args &&...args) {
915
916 using RequiredType =
917 void (*)(raw_ostream &, ProgramStateRef, const char *,
918 const LocationContext *, unsigned int, bool, Args &&...);
919
920 // Try to do as much compile time checking as possible.
921 // FIXME: check for invocable instead of function?
922 static_assert(std::is_function_v<std::remove_pointer_t<Printer>>,
923 "Printer is not a function!");
924 static_assert(std::is_convertible_v<Printer, RequiredType>,
925 "Printer doesn't have the required type!");
926
927 if (LCtx && !State->get<Trait>().isEmpty()) {
928 Indent(Out, Space, IsDot) << '\"' << jsonPropertyName << "\": ";
929 ++Space;
930 Out << '[' << NL;
931 LCtx->printJson(Out, NL, Space, IsDot, [&](const LocationContext *LC) {
932 printer(Out, State, NL, LC, Space, IsDot, std::forward<Args>(args)...);
933 });
934
935 --Space;
936 Indent(Out, Space, IsDot) << "]," << NL; // End of "jsonPropertyName".
937 }
938}
939
940void ExprEngine::printJson(raw_ostream &Out, ProgramStateRef State,
941 const LocationContext *LCtx, const char *NL,
942 unsigned int Space, bool IsDot) const {
943
945 Out, State, LCtx, NL, Space, IsDot, "constructing_objects",
948 Out, State, LCtx, NL, Space, IsDot, "index_of_element",
951 Out, State, LCtx, NL, Space, IsDot, "pending_init_loops",
954 Out, State, LCtx, NL, Space, IsDot, "pending_destructors",
956
957 getCheckerManager().runCheckersForPrintStateJson(Out, State, NL, Space,
958 IsDot);
959}
960
962 // This prints the name of the top-level function if we crash.
965}
966
968 unsigned StmtIdx, NodeBuilderContext *Ctx) {
969 currStmtIdx = StmtIdx;
970 currBldrCtx = Ctx;
971
972 switch (E.getKind()) {
976 ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
977 return;
980 return;
983 Pred);
984 return;
991 return;
994 return;
999 return;
1000 }
1001}
1002
1004 const Stmt *S,
1005 const ExplodedNode *Pred,
1006 const LocationContext *LC) {
1007 // Are we never purging state values?
1008 if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
1009 return false;
1010
1011 // Is this the beginning of a basic block?
1012 if (Pred->getLocation().getAs<BlockEntrance>())
1013 return true;
1014
1015 // Is this on a non-expression?
1016 if (!isa<Expr>(S))
1017 return true;
1018
1019 // Run before processing a call.
1020 if (CallEvent::isCallStmt(S))
1021 return true;
1022
1023 // Is this an expression that is consumed by another expression? If so,
1024 // postpone cleaning out the state.
1026 return !PM.isConsumedExpr(cast<Expr>(S));
1027}
1028
1030 const Stmt *ReferenceStmt,
1031 const LocationContext *LC,
1032 const Stmt *DiagnosticStmt,
1034 llvm::TimeTraceScope TimeScope("ExprEngine::removeDead");
1036 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
1037 && "PostStmt is not generally supported by the SymbolReaper yet");
1038 assert(LC && "Must pass the current (or expiring) LocationContext");
1039
1040 if (!DiagnosticStmt) {
1041 DiagnosticStmt = ReferenceStmt;
1042 assert(DiagnosticStmt && "Required for clearing a LocationContext");
1043 }
1044
1045 NumRemoveDeadBindings++;
1046 ProgramStateRef CleanedState = Pred->getState();
1047
1048 // LC is the location context being destroyed, but SymbolReaper wants a
1049 // location context that is still live. (If this is the top-level stack
1050 // frame, this will be null.)
1051 if (!ReferenceStmt) {
1053 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
1054 LC = LC->getParent();
1055 }
1056
1057 const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
1058 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
1059
1060 for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
1061 if (SymbolRef Sym = I.second.getAsSymbol())
1062 SymReaper.markLive(Sym);
1063 if (const MemRegion *MR = I.second.getAsRegion())
1064 SymReaper.markLive(MR);
1065 }
1066
1067 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
1068
1069 // Create a state in which dead bindings are removed from the environment
1070 // and the store. TODO: The function should just return new env and store,
1071 // not a new state.
1072 CleanedState = StateMgr.removeDeadBindingsFromEnvironmentAndStore(
1073 CleanedState, SFC, SymReaper);
1074
1075 // Process any special transfer function for dead symbols.
1076 // Call checkers with the non-cleaned state so that they could query the
1077 // values of the soon to be dead symbols.
1078 ExplodedNodeSet CheckedSet;
1079 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
1080 DiagnosticStmt, *this, K);
1081
1082 // For each node in CheckedSet, generate CleanedNodes that have the
1083 // environment, the store, and the constraints cleaned up but have the
1084 // user-supplied states as the predecessors.
1085 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
1086 for (const auto I : CheckedSet) {
1087 ProgramStateRef CheckerState = I->getState();
1088
1089 // The constraint manager has not been cleaned up yet, so clean up now.
1090 CheckerState =
1091 getConstraintManager().removeDeadBindings(CheckerState, SymReaper);
1092
1093 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
1094 "Checkers are not allowed to modify the Environment as a part of "
1095 "checkDeadSymbols processing.");
1096 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
1097 "Checkers are not allowed to modify the Store as a part of "
1098 "checkDeadSymbols processing.");
1099
1100 // Create a state based on CleanedState with CheckerState GDM and
1101 // generate a transition to that state.
1102 ProgramStateRef CleanedCheckerSt =
1103 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
1104 Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, cleanupNodeTag(), K);
1105 }
1106}
1107
1109 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
1110 return &cleanupTag;
1111}
1112
1113void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
1114 // Reclaim any unnecessary nodes in the ExplodedGraph.
1115 G.reclaimRecentlyAllocatedNodes();
1116
1117 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1118 currStmt->getBeginLoc(),
1119 "Error evaluating statement");
1120
1121 // Remove dead bindings and symbols.
1122 ExplodedNodeSet CleanedStates;
1123 if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
1124 Pred->getLocationContext())) {
1125 removeDead(Pred, CleanedStates, currStmt,
1126 Pred->getLocationContext());
1127 } else
1128 CleanedStates.Add(Pred);
1129
1130 // Visit the statement.
1131 ExplodedNodeSet Dst;
1132 for (const auto I : CleanedStates) {
1133 ExplodedNodeSet DstI;
1134 // Visit the statement.
1135 Visit(currStmt, I, DstI);
1136 Dst.insert(DstI);
1137 }
1138
1139 // Enqueue the new nodes onto the work list.
1140 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
1141}
1142
1144 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1145 S->getBeginLoc(),
1146 "Error evaluating end of the loop");
1147 ExplodedNodeSet Dst;
1148 Dst.Add(Pred);
1149 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1150 ProgramStateRef NewState = Pred->getState();
1151
1152 if(AMgr.options.ShouldUnrollLoops)
1153 NewState = processLoopEnd(S, NewState);
1154
1155 LoopExit PP(S, Pred->getLocationContext());
1156 Bldr.generateNode(PP, NewState, Pred);
1157 // Enqueue the new nodes onto the work list.
1158 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
1159}
1160
1162 ExplodedNode *Pred) {
1163 const CXXCtorInitializer *BMI = CFGInit.getInitializer();
1164 const Expr *Init = BMI->getInit()->IgnoreImplicit();
1165 const LocationContext *LC = Pred->getLocationContext();
1166
1167 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1168 BMI->getSourceLocation(),
1169 "Error evaluating initializer");
1170
1171 // We don't clean up dead bindings here.
1172 const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
1173 const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
1174
1175 ProgramStateRef State = Pred->getState();
1176 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
1177
1178 ExplodedNodeSet Tmp;
1179 SVal FieldLoc;
1180
1181 // Evaluate the initializer, if necessary
1182 if (BMI->isAnyMemberInitializer()) {
1183 // Constructors build the object directly in the field,
1184 // but non-objects must be copied in from the initializer.
1185 if (getObjectUnderConstruction(State, BMI, LC)) {
1186 // The field was directly constructed, so there is no need to bind.
1187 // But we still need to stop tracking the object under construction.
1188 State = finishObjectConstruction(State, BMI, LC);
1189 NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
1190 PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
1191 Bldr.generateNode(PS, State, Pred);
1192 } else {
1193 const ValueDecl *Field;
1194 if (BMI->isIndirectMemberInitializer()) {
1195 Field = BMI->getIndirectMember();
1196 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
1197 } else {
1198 Field = BMI->getMember();
1199 FieldLoc = State->getLValue(BMI->getMember(), thisVal);
1200 }
1201
1202 SVal InitVal;
1203 if (Init->getType()->isArrayType()) {
1204 // Handle arrays of trivial type. We can represent this with a
1205 // primitive load/copy from the base array region.
1206 const ArraySubscriptExpr *ASE;
1207 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
1208 Init = ASE->getBase()->IgnoreImplicit();
1209
1210 InitVal = State->getSVal(Init, stackFrame);
1211
1212 // If we fail to get the value for some reason, use a symbolic value.
1213 if (InitVal.isUnknownOrUndef()) {
1214 SValBuilder &SVB = getSValBuilder();
1215 InitVal =
1216 SVB.conjureSymbolVal(getCFGElementRef(), stackFrame,
1217 Field->getType(), currBldrCtx->blockCount());
1218 }
1219 } else {
1220 InitVal = State->getSVal(BMI->getInit(), stackFrame);
1221 }
1222
1223 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
1224 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
1225 }
1226 } else if (BMI->isBaseInitializer() && isa<InitListExpr>(Init)) {
1227 // When the base class is initialized with an initialization list and the
1228 // base class does not have a ctor, there will not be a CXXConstructExpr to
1229 // initialize the base region. Hence, we need to make the bind for it.
1231 thisVal, QualType(BMI->getBaseClass(), 0), BMI->isBaseVirtual());
1232 SVal InitVal = State->getSVal(Init, stackFrame);
1233 evalBind(Tmp, Init, Pred, BaseLoc, InitVal, /*isInit=*/true);
1234 } else {
1235 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
1236 Tmp.insert(Pred);
1237 // We already did all the work when visiting the CXXConstructExpr.
1238 }
1239
1240 // Construct PostInitializer nodes whether the state changed or not,
1241 // so that the diagnostics don't get confused.
1242 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
1243 ExplodedNodeSet Dst;
1244 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
1245 for (const auto I : Tmp) {
1246 ProgramStateRef State = I->getState();
1247 Bldr.generateNode(PP, State, I);
1248 }
1249
1250 // Enqueue the new nodes onto the work list.
1251 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
1252}
1253
1254std::pair<ProgramStateRef, uint64_t>
1255ExprEngine::prepareStateForArrayDestruction(const ProgramStateRef State,
1256 const MemRegion *Region,
1257 const QualType &ElementTy,
1258 const LocationContext *LCtx,
1259 SVal *ElementCountVal) {
1260 assert(Region != nullptr && "Not-null region expected");
1261
1262 QualType Ty = ElementTy.getDesugaredType(getContext());
1263 while (const auto *NTy = dyn_cast<ArrayType>(Ty))
1264 Ty = NTy->getElementType().getDesugaredType(getContext());
1265
1266 auto ElementCount = getDynamicElementCount(State, Region, svalBuilder, Ty);
1267
1268 if (ElementCountVal)
1269 *ElementCountVal = ElementCount;
1270
1271 // Note: the destructors are called in reverse order.
1272 unsigned Idx = 0;
1273 if (auto OptionalIdx = getPendingArrayDestruction(State, LCtx)) {
1274 Idx = *OptionalIdx;
1275 } else {
1276 // The element count is either unknown, or an SVal that's not an integer.
1277 if (!ElementCount.isConstant())
1278 return {State, 0};
1279
1280 Idx = ElementCount.getAsInteger()->getLimitedValue();
1281 }
1282
1283 if (Idx == 0)
1284 return {State, 0};
1285
1286 --Idx;
1287
1288 return {setPendingArrayDestruction(State, LCtx, Idx), Idx};
1289}
1290
1292 ExplodedNode *Pred) {
1293 ExplodedNodeSet Dst;
1294 switch (D.getKind()) {
1297 break;
1299 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
1300 break;
1302 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
1303 break;
1306 break;
1308 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
1309 break;
1310 default:
1311 llvm_unreachable("Unexpected dtor kind.");
1312 }
1313
1314 // Enqueue the new nodes onto the work list.
1315 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
1316}
1317
1319 ExplodedNode *Pred) {
1320 ExplodedNodeSet Dst;
1322 AnalyzerOptions &Opts = AMgr.options;
1323 // TODO: We're not evaluating allocators for all cases just yet as
1324 // we're not handling the return value correctly, which causes false
1325 // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
1326 if (Opts.MayInlineCXXAllocator)
1327 VisitCXXNewAllocatorCall(NE, Pred, Dst);
1328 else {
1329 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1330 const LocationContext *LCtx = Pred->getLocationContext();
1331 PostImplicitCall PP(NE->getOperatorNew(), NE->getBeginLoc(), LCtx,
1333 Bldr.generateNode(PP, Pred->getState(), Pred);
1334 }
1335 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
1336}
1337
1339 ExplodedNode *Pred,
1340 ExplodedNodeSet &Dst) {
1341 const auto *DtorDecl = Dtor.getDestructorDecl(getContext());
1342 const VarDecl *varDecl = Dtor.getVarDecl();
1343 QualType varType = varDecl->getType();
1344
1345 ProgramStateRef state = Pred->getState();
1346 const LocationContext *LCtx = Pred->getLocationContext();
1347
1348 SVal dest = state->getLValue(varDecl, LCtx);
1349 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
1350
1351 if (varType->isReferenceType()) {
1352 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
1353 if (!ValueRegion) {
1354 // FIXME: This should not happen. The language guarantees a presence
1355 // of a valid initializer here, so the reference shall not be undefined.
1356 // It seems that we're calling destructors over variables that
1357 // were not initialized yet.
1358 return;
1359 }
1360 Region = ValueRegion->getBaseRegion();
1361 varType = cast<TypedValueRegion>(Region)->getValueType();
1362 }
1363
1364 unsigned Idx = 0;
1365 if (isa<ArrayType>(varType)) {
1366 SVal ElementCount;
1367 std::tie(state, Idx) = prepareStateForArrayDestruction(
1368 state, Region, varType, LCtx, &ElementCount);
1369
1370 if (ElementCount.isConstant()) {
1371 uint64_t ArrayLength = ElementCount.getAsInteger()->getLimitedValue();
1372 assert(ArrayLength &&
1373 "An automatic dtor for a 0 length array shouldn't be triggered!");
1374
1375 // Still handle this case if we don't have assertions enabled.
1376 if (!ArrayLength) {
1377 static SimpleProgramPointTag PT(
1378 "ExprEngine", "Skipping automatic 0 length array destruction, "
1379 "which shouldn't be in the CFG.");
1380 PostImplicitCall PP(DtorDecl, varDecl->getLocation(), LCtx,
1381 getCFGElementRef(), &PT);
1382 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1383 Bldr.generateSink(PP, Pred->getState(), Pred);
1384 return;
1385 }
1386 }
1387 }
1388
1389 EvalCallOptions CallOpts;
1390 Region = makeElementRegion(state, loc::MemRegionVal(Region), varType,
1391 CallOpts.IsArrayCtorOrDtor, Idx)
1392 .getAsRegion();
1393
1394 NodeBuilder Bldr(Pred, Dst, getBuilderContext());
1395
1396 static SimpleProgramPointTag PT("ExprEngine",
1397 "Prepare for object destruction");
1398 PreImplicitCall PP(DtorDecl, varDecl->getLocation(), LCtx, getCFGElementRef(),
1399 &PT);
1400 Pred = Bldr.generateNode(PP, state, Pred);
1401
1402 if (!Pred)
1403 return;
1404 Bldr.takeNodes(Pred);
1405
1406 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(),
1407 /*IsBase=*/false, Pred, Dst, CallOpts);
1408}
1409
1411 ExplodedNode *Pred,
1412 ExplodedNodeSet &Dst) {
1413 ProgramStateRef State = Pred->getState();
1414 const LocationContext *LCtx = Pred->getLocationContext();
1415 const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
1416 const Stmt *Arg = DE->getArgument();
1417 QualType DTy = DE->getDestroyedType();
1418 SVal ArgVal = State->getSVal(Arg, LCtx);
1419
1420 // If the argument to delete is known to be a null value,
1421 // don't run destructor.
1422 if (State->isNull(ArgVal).isConstrainedTrue()) {
1424 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
1425 const CXXDestructorDecl *Dtor = RD->getDestructor();
1426
1427 PostImplicitCall PP(Dtor, DE->getBeginLoc(), LCtx, getCFGElementRef());
1428 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1429 Bldr.generateNode(PP, Pred->getState(), Pred);
1430 return;
1431 }
1432
1433 auto getDtorDecl = [](const QualType &DTy) {
1434 const CXXRecordDecl *RD = DTy->getAsCXXRecordDecl();
1435 return RD->getDestructor();
1436 };
1437
1438 unsigned Idx = 0;
1439 EvalCallOptions CallOpts;
1440 const MemRegion *ArgR = ArgVal.getAsRegion();
1441
1442 if (DE->isArrayForm()) {
1443 CallOpts.IsArrayCtorOrDtor = true;
1444 // Yes, it may even be a multi-dimensional array.
1445 while (const auto *AT = getContext().getAsArrayType(DTy))
1446 DTy = AT->getElementType();
1447
1448 if (ArgR) {
1449 SVal ElementCount;
1450 std::tie(State, Idx) = prepareStateForArrayDestruction(
1451 State, ArgR, DTy, LCtx, &ElementCount);
1452
1453 // If we're about to destruct a 0 length array, don't run any of the
1454 // destructors.
1455 if (ElementCount.isConstant() &&
1456 ElementCount.getAsInteger()->getLimitedValue() == 0) {
1457
1458 static SimpleProgramPointTag PT(
1459 "ExprEngine", "Skipping 0 length array delete destruction");
1460 PostImplicitCall PP(getDtorDecl(DTy), DE->getBeginLoc(), LCtx,
1461 getCFGElementRef(), &PT);
1462 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1463 Bldr.generateNode(PP, Pred->getState(), Pred);
1464 return;
1465 }
1466
1467 ArgR = State->getLValue(DTy, svalBuilder.makeArrayIndex(Idx), ArgVal)
1468 .getAsRegion();
1469 }
1470 }
1471
1472 NodeBuilder Bldr(Pred, Dst, getBuilderContext());
1473 static SimpleProgramPointTag PT("ExprEngine",
1474 "Prepare for object destruction");
1475 PreImplicitCall PP(getDtorDecl(DTy), DE->getBeginLoc(), LCtx,
1476 getCFGElementRef(), &PT);
1477 Pred = Bldr.generateNode(PP, State, Pred);
1478
1479 if (!Pred)
1480 return;
1481 Bldr.takeNodes(Pred);
1482
1483 VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
1484}
1485
1487 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1488 const LocationContext *LCtx = Pred->getLocationContext();
1489
1490 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
1491 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
1492 LCtx->getStackFrame());
1493 SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
1494
1495 // Create the base object region.
1497 QualType BaseTy = Base->getType();
1498 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
1499 Base->isVirtual());
1500
1501 EvalCallOptions CallOpts;
1502 VisitCXXDestructor(BaseTy, BaseVal.getAsRegion(), CurDtor->getBody(),
1503 /*IsBase=*/true, Pred, Dst, CallOpts);
1504}
1505
1507 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1508 const auto *DtorDecl = D.getDestructorDecl(getContext());
1509 const FieldDecl *Member = D.getFieldDecl();
1510 QualType T = Member->getType();
1511 ProgramStateRef State = Pred->getState();
1512 const LocationContext *LCtx = Pred->getLocationContext();
1513
1514 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
1515 Loc ThisStorageLoc =
1516 getSValBuilder().getCXXThis(CurDtor, LCtx->getStackFrame());
1517 Loc ThisLoc = State->getSVal(ThisStorageLoc).castAs<Loc>();
1518 SVal FieldVal = State->getLValue(Member, ThisLoc);
1519
1520 unsigned Idx = 0;
1521 if (isa<ArrayType>(T)) {
1522 SVal ElementCount;
1523 std::tie(State, Idx) = prepareStateForArrayDestruction(
1524 State, FieldVal.getAsRegion(), T, LCtx, &ElementCount);
1525
1526 if (ElementCount.isConstant()) {
1527 uint64_t ArrayLength = ElementCount.getAsInteger()->getLimitedValue();
1528 assert(ArrayLength &&
1529 "A member dtor for a 0 length array shouldn't be triggered!");
1530
1531 // Still handle this case if we don't have assertions enabled.
1532 if (!ArrayLength) {
1533 static SimpleProgramPointTag PT(
1534 "ExprEngine", "Skipping member 0 length array destruction, which "
1535 "shouldn't be in the CFG.");
1536 PostImplicitCall PP(DtorDecl, Member->getLocation(), LCtx,
1537 getCFGElementRef(), &PT);
1538 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1539 Bldr.generateSink(PP, Pred->getState(), Pred);
1540 return;
1541 }
1542 }
1543 }
1544
1545 EvalCallOptions CallOpts;
1546 FieldVal =
1547 makeElementRegion(State, FieldVal, T, CallOpts.IsArrayCtorOrDtor, Idx);
1548
1549 NodeBuilder Bldr(Pred, Dst, getBuilderContext());
1550
1551 static SimpleProgramPointTag PT("ExprEngine",
1552 "Prepare for object destruction");
1553 PreImplicitCall PP(DtorDecl, Member->getLocation(), LCtx, getCFGElementRef(),
1554 &PT);
1555 Pred = Bldr.generateNode(PP, State, Pred);
1556
1557 if (!Pred)
1558 return;
1559 Bldr.takeNodes(Pred);
1560
1561 VisitCXXDestructor(T, FieldVal.getAsRegion(), CurDtor->getBody(),
1562 /*IsBase=*/false, Pred, Dst, CallOpts);
1563}
1564
1566 ExplodedNode *Pred,
1567 ExplodedNodeSet &Dst) {
1569 ProgramStateRef State = Pred->getState();
1570 const LocationContext *LC = Pred->getLocationContext();
1571 const MemRegion *MR = nullptr;
1572
1573 if (std::optional<SVal> V = getObjectUnderConstruction(
1574 State, D.getBindTemporaryExpr(), Pred->getLocationContext())) {
1575 // FIXME: Currently we insert temporary destructors for default parameters,
1576 // but we don't insert the constructors, so the entry in
1577 // ObjectsUnderConstruction may be missing.
1578 State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
1579 Pred->getLocationContext());
1580 MR = V->getAsRegion();
1581 }
1582
1583 // If copy elision has occurred, and the constructor corresponding to the
1584 // destructor was elided, we need to skip the destructor as well.
1585 if (isDestructorElided(State, BTE, LC)) {
1586 State = cleanupElidedDestructor(State, BTE, LC);
1587 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1591 Bldr.generateNode(PP, State, Pred);
1592 return;
1593 }
1594
1595 ExplodedNodeSet CleanDtorState;
1596 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
1597 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
1598
1600 // FIXME: Currently CleanDtorState can be empty here due to temporaries being
1601 // bound to default parameters.
1602 assert(CleanDtorState.size() <= 1);
1603 ExplodedNode *CleanPred =
1604 CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
1605
1606 EvalCallOptions CallOpts;
1607 CallOpts.IsTemporaryCtorOrDtor = true;
1608 if (!MR) {
1609 // FIXME: If we have no MR, we still need to unwrap the array to avoid
1610 // destroying the whole array at once.
1611 //
1612 // For this case there is no universal solution as there is no way to
1613 // directly create an array of temporary objects. There are some expressions
1614 // however which can create temporary objects and have an array type.
1615 //
1616 // E.g.: std::initializer_list<S>{S(), S()};
1617 //
1618 // The expression above has a type of 'const struct S[2]' but it's a single
1619 // 'std::initializer_list<>'. The destructors of the 2 temporary 'S()'
1620 // objects will be called anyway, because they are 2 separate objects in 2
1621 // separate clusters, i.e.: not an array.
1622 //
1623 // Now the 'std::initializer_list<>' is not an array either even though it
1624 // has the type of an array. The point is, we only want to invoke the
1625 // destructor for the initializer list once not twice or so.
1626 while (const ArrayType *AT = getContext().getAsArrayType(T)) {
1627 T = AT->getElementType();
1628
1629 // FIXME: Enable this flag once we handle this case properly.
1630 // CallOpts.IsArrayCtorOrDtor = true;
1631 }
1632 } else {
1633 // FIXME: We'd eventually need to makeElementRegion() trick here,
1634 // but for now we don't have the respective construction contexts,
1635 // so MR would always be null in this case. Do nothing for now.
1636 }
1638 /*IsBase=*/false, CleanPred, Dst, CallOpts);
1639}
1640
1642 NodeBuilderContext &BldCtx,
1643 ExplodedNode *Pred,
1644 ExplodedNodeSet &Dst,
1645 const CFGBlock *DstT,
1646 const CFGBlock *DstF) {
1647 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
1648 ProgramStateRef State = Pred->getState();
1649 const LocationContext *LC = Pred->getLocationContext();
1650 if (getObjectUnderConstruction(State, BTE, LC)) {
1651 TempDtorBuilder.generateNode(State, true, Pred);
1652 } else {
1653 TempDtorBuilder.generateNode(State, false, Pred);
1654 }
1655}
1656
1658 ExplodedNodeSet &PreVisit,
1659 ExplodedNodeSet &Dst) {
1660 // This is a fallback solution in case we didn't have a construction
1661 // context when we were constructing the temporary. Otherwise the map should
1662 // have been populated there.
1663 if (!getAnalysisManager().options.ShouldIncludeTemporaryDtorsInCFG) {
1664 // In case we don't have temporary destructors in the CFG, do not mark
1665 // the initialization - we would otherwise never clean it up.
1666 Dst = PreVisit;
1667 return;
1668 }
1669 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
1670 for (ExplodedNode *Node : PreVisit) {
1671 ProgramStateRef State = Node->getState();
1672 const LocationContext *LC = Node->getLocationContext();
1673 if (!getObjectUnderConstruction(State, BTE, LC)) {
1674 // FIXME: Currently the state might also already contain the marker due to
1675 // incorrect handling of temporaries bound to default parameters; for
1676 // those, we currently skip the CXXBindTemporaryExpr but rely on adding
1677 // temporary destructor nodes.
1678 State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
1679 }
1680 StmtBldr.generateNode(BTE, Node, State);
1681 }
1682}
1683
1685 ArrayRef<SVal> Vs,
1687 const CallEvent *Call) const {
1688 class CollectReachableSymbolsCallback final : public SymbolVisitor {
1689 InvalidatedSymbols &Symbols;
1690
1691 public:
1692 explicit CollectReachableSymbolsCallback(InvalidatedSymbols &Symbols)
1693 : Symbols(Symbols) {}
1694
1695 const InvalidatedSymbols &getSymbols() const { return Symbols; }
1696
1697 bool VisitSymbol(SymbolRef Sym) override {
1698 Symbols.insert(Sym);
1699 return true;
1700 }
1701 };
1702 InvalidatedSymbols Symbols;
1703 CollectReachableSymbolsCallback CallBack(Symbols);
1704 for (SVal V : Vs)
1705 State->scanReachableSymbols(V, CallBack);
1706
1708 State, CallBack.getSymbols(), Call, K, nullptr);
1709}
1710
1712 ExplodedNodeSet &DstTop) {
1713 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1714 S->getBeginLoc(), "Error evaluating statement");
1715 ExplodedNodeSet Dst;
1716 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
1717
1718 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
1719
1720 switch (S->getStmtClass()) {
1721 // C++, OpenMP and ARC stuff we don't support yet.
1722 case Stmt::CXXDependentScopeMemberExprClass:
1723 case Stmt::CXXTryStmtClass:
1724 case Stmt::CXXTypeidExprClass:
1725 case Stmt::CXXUuidofExprClass:
1726 case Stmt::CXXFoldExprClass:
1727 case Stmt::MSPropertyRefExprClass:
1728 case Stmt::MSPropertySubscriptExprClass:
1729 case Stmt::CXXUnresolvedConstructExprClass:
1730 case Stmt::DependentScopeDeclRefExprClass:
1731 case Stmt::ArrayTypeTraitExprClass:
1732 case Stmt::ExpressionTraitExprClass:
1733 case Stmt::UnresolvedLookupExprClass:
1734 case Stmt::UnresolvedMemberExprClass:
1735 case Stmt::RecoveryExprClass:
1736 case Stmt::CXXNoexceptExprClass:
1737 case Stmt::PackExpansionExprClass:
1738 case Stmt::PackIndexingExprClass:
1739 case Stmt::SubstNonTypeTemplateParmPackExprClass:
1740 case Stmt::FunctionParmPackExprClass:
1741 case Stmt::CoroutineBodyStmtClass:
1742 case Stmt::CoawaitExprClass:
1743 case Stmt::DependentCoawaitExprClass:
1744 case Stmt::CoreturnStmtClass:
1745 case Stmt::CoyieldExprClass:
1746 case Stmt::SEHTryStmtClass:
1747 case Stmt::SEHExceptStmtClass:
1748 case Stmt::SEHLeaveStmtClass:
1749 case Stmt::SEHFinallyStmtClass:
1750 case Stmt::OMPCanonicalLoopClass:
1751 case Stmt::OMPParallelDirectiveClass:
1752 case Stmt::OMPSimdDirectiveClass:
1753 case Stmt::OMPForDirectiveClass:
1754 case Stmt::OMPForSimdDirectiveClass:
1755 case Stmt::OMPSectionsDirectiveClass:
1756 case Stmt::OMPSectionDirectiveClass:
1757 case Stmt::OMPScopeDirectiveClass:
1758 case Stmt::OMPSingleDirectiveClass:
1759 case Stmt::OMPMasterDirectiveClass:
1760 case Stmt::OMPCriticalDirectiveClass:
1761 case Stmt::OMPParallelForDirectiveClass:
1762 case Stmt::OMPParallelForSimdDirectiveClass:
1763 case Stmt::OMPParallelSectionsDirectiveClass:
1764 case Stmt::OMPParallelMasterDirectiveClass:
1765 case Stmt::OMPParallelMaskedDirectiveClass:
1766 case Stmt::OMPTaskDirectiveClass:
1767 case Stmt::OMPTaskyieldDirectiveClass:
1768 case Stmt::OMPBarrierDirectiveClass:
1769 case Stmt::OMPTaskwaitDirectiveClass:
1770 case Stmt::OMPErrorDirectiveClass:
1771 case Stmt::OMPTaskgroupDirectiveClass:
1772 case Stmt::OMPFlushDirectiveClass:
1773 case Stmt::OMPDepobjDirectiveClass:
1774 case Stmt::OMPScanDirectiveClass:
1775 case Stmt::OMPOrderedDirectiveClass:
1776 case Stmt::OMPAtomicDirectiveClass:
1777 case Stmt::OMPAssumeDirectiveClass:
1778 case Stmt::OMPTargetDirectiveClass:
1779 case Stmt::OMPTargetDataDirectiveClass:
1780 case Stmt::OMPTargetEnterDataDirectiveClass:
1781 case Stmt::OMPTargetExitDataDirectiveClass:
1782 case Stmt::OMPTargetParallelDirectiveClass:
1783 case Stmt::OMPTargetParallelForDirectiveClass:
1784 case Stmt::OMPTargetUpdateDirectiveClass:
1785 case Stmt::OMPTeamsDirectiveClass:
1786 case Stmt::OMPCancellationPointDirectiveClass:
1787 case Stmt::OMPCancelDirectiveClass:
1788 case Stmt::OMPTaskLoopDirectiveClass:
1789 case Stmt::OMPTaskLoopSimdDirectiveClass:
1790 case Stmt::OMPMasterTaskLoopDirectiveClass:
1791 case Stmt::OMPMaskedTaskLoopDirectiveClass:
1792 case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
1793 case Stmt::OMPMaskedTaskLoopSimdDirectiveClass:
1794 case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
1795 case Stmt::OMPParallelMaskedTaskLoopDirectiveClass:
1796 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
1797 case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass:
1798 case Stmt::OMPDistributeDirectiveClass:
1799 case Stmt::OMPDistributeParallelForDirectiveClass:
1800 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1801 case Stmt::OMPDistributeSimdDirectiveClass:
1802 case Stmt::OMPTargetParallelForSimdDirectiveClass:
1803 case Stmt::OMPTargetSimdDirectiveClass:
1804 case Stmt::OMPTeamsDistributeDirectiveClass:
1805 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1806 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1807 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1808 case Stmt::OMPTargetTeamsDirectiveClass:
1809 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1810 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1811 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1812 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1813 case Stmt::OMPReverseDirectiveClass:
1814 case Stmt::OMPStripeDirectiveClass:
1815 case Stmt::OMPTileDirectiveClass:
1816 case Stmt::OMPInterchangeDirectiveClass:
1817 case Stmt::OMPFuseDirectiveClass:
1818 case Stmt::OMPInteropDirectiveClass:
1819 case Stmt::OMPDispatchDirectiveClass:
1820 case Stmt::OMPMaskedDirectiveClass:
1821 case Stmt::OMPGenericLoopDirectiveClass:
1822 case Stmt::OMPTeamsGenericLoopDirectiveClass:
1823 case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
1824 case Stmt::OMPParallelGenericLoopDirectiveClass:
1825 case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
1826 case Stmt::CapturedStmtClass:
1827 case Stmt::SYCLKernelCallStmtClass:
1828 case Stmt::OpenACCComputeConstructClass:
1829 case Stmt::OpenACCLoopConstructClass:
1830 case Stmt::OpenACCCombinedConstructClass:
1831 case Stmt::OpenACCDataConstructClass:
1832 case Stmt::OpenACCEnterDataConstructClass:
1833 case Stmt::OpenACCExitDataConstructClass:
1834 case Stmt::OpenACCHostDataConstructClass:
1835 case Stmt::OpenACCWaitConstructClass:
1836 case Stmt::OpenACCCacheConstructClass:
1837 case Stmt::OpenACCInitConstructClass:
1838 case Stmt::OpenACCShutdownConstructClass:
1839 case Stmt::OpenACCSetConstructClass:
1840 case Stmt::OpenACCUpdateConstructClass:
1841 case Stmt::OpenACCAtomicConstructClass:
1842 case Stmt::OMPUnrollDirectiveClass:
1843 case Stmt::OMPMetaDirectiveClass:
1844 case Stmt::HLSLOutArgExprClass: {
1845 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1846 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1847 break;
1848 }
1849
1850 case Stmt::ParenExprClass:
1851 llvm_unreachable("ParenExprs already handled.");
1852 case Stmt::GenericSelectionExprClass:
1853 llvm_unreachable("GenericSelectionExprs already handled.");
1854 // Cases that should never be evaluated simply because they shouldn't
1855 // appear in the CFG.
1856 case Stmt::BreakStmtClass:
1857 case Stmt::CaseStmtClass:
1858 case Stmt::CompoundStmtClass:
1859 case Stmt::ContinueStmtClass:
1860 case Stmt::CXXForRangeStmtClass:
1861 case Stmt::DefaultStmtClass:
1862 case Stmt::DoStmtClass:
1863 case Stmt::ForStmtClass:
1864 case Stmt::GotoStmtClass:
1865 case Stmt::IfStmtClass:
1866 case Stmt::IndirectGotoStmtClass:
1867 case Stmt::LabelStmtClass:
1868 case Stmt::NoStmtClass:
1869 case Stmt::NullStmtClass:
1870 case Stmt::SwitchStmtClass:
1871 case Stmt::WhileStmtClass:
1872 case Expr::MSDependentExistsStmtClass:
1873 llvm_unreachable("Stmt should not be in analyzer evaluation loop");
1874 case Stmt::ImplicitValueInitExprClass:
1875 // These nodes are shared in the CFG and would case caching out.
1876 // Moreover, no additional evaluation required for them, the
1877 // analyzer can reconstruct these values from the AST.
1878 llvm_unreachable("Should be pruned from CFG");
1879
1880 case Stmt::ObjCSubscriptRefExprClass:
1881 case Stmt::ObjCPropertyRefExprClass:
1882 llvm_unreachable("These are handled by PseudoObjectExpr");
1883
1884 case Stmt::GNUNullExprClass: {
1885 // GNU __null is a pointer-width integer, not an actual pointer.
1886 ProgramStateRef state = Pred->getState();
1887 state = state->BindExpr(
1888 S, Pred->getLocationContext(),
1889 svalBuilder.makeIntValWithWidth(getContext().VoidPtrTy, 0));
1890 Bldr.generateNode(S, Pred, state);
1891 break;
1892 }
1893
1894 case Stmt::ObjCAtSynchronizedStmtClass:
1895 Bldr.takeNodes(Pred);
1897 Bldr.addNodes(Dst);
1898 break;
1899
1900 case Expr::ConstantExprClass:
1901 case Stmt::ExprWithCleanupsClass:
1902 // Handled due to fully linearised CFG.
1903 break;
1904
1905 case Stmt::CXXBindTemporaryExprClass: {
1906 Bldr.takeNodes(Pred);
1907 ExplodedNodeSet PreVisit;
1908 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1912 Bldr.addNodes(Dst);
1913 break;
1914 }
1915
1916 case Stmt::ArrayInitLoopExprClass:
1917 Bldr.takeNodes(Pred);
1919 Bldr.addNodes(Dst);
1920 break;
1921 // Cases not handled yet; but will handle some day.
1922 case Stmt::DesignatedInitExprClass:
1923 case Stmt::DesignatedInitUpdateExprClass:
1924 case Stmt::ArrayInitIndexExprClass:
1925 case Stmt::ExtVectorElementExprClass:
1926 case Stmt::ImaginaryLiteralClass:
1927 case Stmt::ObjCAtCatchStmtClass:
1928 case Stmt::ObjCAtFinallyStmtClass:
1929 case Stmt::ObjCAtTryStmtClass:
1930 case Stmt::ObjCAutoreleasePoolStmtClass:
1931 case Stmt::ObjCEncodeExprClass:
1932 case Stmt::ObjCIsaExprClass:
1933 case Stmt::ObjCProtocolExprClass:
1934 case Stmt::ObjCSelectorExprClass:
1935 case Stmt::ParenListExprClass:
1936 case Stmt::ShuffleVectorExprClass:
1937 case Stmt::ConvertVectorExprClass:
1938 case Stmt::VAArgExprClass:
1939 case Stmt::CUDAKernelCallExprClass:
1940 case Stmt::OpaqueValueExprClass:
1941 case Stmt::AsTypeExprClass:
1942 case Stmt::ConceptSpecializationExprClass:
1943 case Stmt::CXXRewrittenBinaryOperatorClass:
1944 case Stmt::RequiresExprClass:
1945 case Stmt::EmbedExprClass:
1946 // Fall through.
1947
1948 // Cases we intentionally don't evaluate, since they don't need
1949 // to be explicitly evaluated.
1950 case Stmt::PredefinedExprClass:
1951 case Stmt::AddrLabelExprClass:
1952 case Stmt::IntegerLiteralClass:
1953 case Stmt::FixedPointLiteralClass:
1954 case Stmt::CharacterLiteralClass:
1955 case Stmt::CXXScalarValueInitExprClass:
1956 case Stmt::CXXBoolLiteralExprClass:
1957 case Stmt::ObjCBoolLiteralExprClass:
1958 case Stmt::ObjCAvailabilityCheckExprClass:
1959 case Stmt::FloatingLiteralClass:
1960 case Stmt::NoInitExprClass:
1961 case Stmt::SizeOfPackExprClass:
1962 case Stmt::StringLiteralClass:
1963 case Stmt::SourceLocExprClass:
1964 case Stmt::ObjCStringLiteralClass:
1965 case Stmt::CXXPseudoDestructorExprClass:
1966 case Stmt::SubstNonTypeTemplateParmExprClass:
1967 case Stmt::CXXNullPtrLiteralExprClass:
1968 case Stmt::ArraySectionExprClass:
1969 case Stmt::OMPArrayShapingExprClass:
1970 case Stmt::OMPIteratorExprClass:
1971 case Stmt::SYCLUniqueStableNameExprClass:
1972 case Stmt::OpenACCAsteriskSizeExprClass:
1973 case Stmt::TypeTraitExprClass: {
1974 Bldr.takeNodes(Pred);
1975 ExplodedNodeSet preVisit;
1976 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1977 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
1978 Bldr.addNodes(Dst);
1979 break;
1980 }
1981
1982 case Stmt::AttributedStmtClass: {
1983 Bldr.takeNodes(Pred);
1985 Bldr.addNodes(Dst);
1986 break;
1987 }
1988
1989 case Stmt::CXXDefaultArgExprClass:
1990 case Stmt::CXXDefaultInitExprClass: {
1991 Bldr.takeNodes(Pred);
1992 ExplodedNodeSet PreVisit;
1993 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1994
1995 ExplodedNodeSet Tmp;
1996 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
1997
1998 const Expr *ArgE;
1999 if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
2000 ArgE = DefE->getExpr();
2001 else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
2002 ArgE = DefE->getExpr();
2003 else
2004 llvm_unreachable("unknown constant wrapper kind");
2005
2006 bool IsTemporary = false;
2007 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
2008 ArgE = MTE->getSubExpr();
2009 IsTemporary = true;
2010 }
2011
2012 std::optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
2013 if (!ConstantVal)
2014 ConstantVal = UnknownVal();
2015
2016 const LocationContext *LCtx = Pred->getLocationContext();
2017 for (const auto I : PreVisit) {
2018 ProgramStateRef State = I->getState();
2019 State = State->BindExpr(S, LCtx, *ConstantVal);
2020 if (IsTemporary)
2021 State = createTemporaryRegionIfNeeded(State, LCtx,
2022 cast<Expr>(S),
2023 cast<Expr>(S));
2024 Bldr2.generateNode(S, I, State);
2025 }
2026
2027 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
2028 Bldr.addNodes(Dst);
2029 break;
2030 }
2031
2032 // Cases we evaluate as opaque expressions, conjuring a symbol.
2033 case Stmt::CXXStdInitializerListExprClass:
2034 case Expr::ObjCArrayLiteralClass:
2035 case Expr::ObjCDictionaryLiteralClass:
2036 case Expr::ObjCBoxedExprClass: {
2037 Bldr.takeNodes(Pred);
2038
2039 ExplodedNodeSet preVisit;
2040 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
2041
2042 ExplodedNodeSet Tmp;
2043 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
2044
2045 const auto *Ex = cast<Expr>(S);
2046 QualType resultType = Ex->getType();
2047
2048 for (const auto N : preVisit) {
2049 const LocationContext *LCtx = N->getLocationContext();
2050 SVal result = svalBuilder.conjureSymbolVal(
2051 /*symbolTag=*/nullptr, getCFGElementRef(), LCtx, resultType,
2052 currBldrCtx->blockCount());
2053 ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
2054
2055 // Escape pointers passed into the list, unless it's an ObjC boxed
2056 // expression which is not a boxable C structure.
2057 if (!(isa<ObjCBoxedExpr>(Ex) &&
2058 !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
2059 ->getType()->isRecordType()))
2060 for (auto Child : Ex->children()) {
2061 assert(Child);
2062 SVal Val = State->getSVal(Child, LCtx);
2063 State = escapeValues(State, Val, PSK_EscapeOther);
2064 }
2065
2066 Bldr2.generateNode(S, N, State);
2067 }
2068
2069 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
2070 Bldr.addNodes(Dst);
2071 break;
2072 }
2073
2074 case Stmt::ArraySubscriptExprClass:
2075 Bldr.takeNodes(Pred);
2077 Bldr.addNodes(Dst);
2078 break;
2079
2080 case Stmt::MatrixSubscriptExprClass:
2081 llvm_unreachable("Support for MatrixSubscriptExpr is not implemented.");
2082 break;
2083
2084 case Stmt::GCCAsmStmtClass: {
2085 Bldr.takeNodes(Pred);
2086 ExplodedNodeSet PreVisit;
2087 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
2088 ExplodedNodeSet PostVisit;
2089 for (ExplodedNode *const N : PreVisit)
2090 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), N, PostVisit);
2091 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
2092 Bldr.addNodes(Dst);
2093 break;
2094 }
2095
2096 case Stmt::MSAsmStmtClass:
2097 Bldr.takeNodes(Pred);
2098 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
2099 Bldr.addNodes(Dst);
2100 break;
2101
2102 case Stmt::BlockExprClass:
2103 Bldr.takeNodes(Pred);
2104 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
2105 Bldr.addNodes(Dst);
2106 break;
2107
2108 case Stmt::LambdaExprClass:
2109 if (AMgr.options.ShouldInlineLambdas) {
2110 Bldr.takeNodes(Pred);
2111 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
2112 Bldr.addNodes(Dst);
2113 } else {
2114 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
2115 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
2116 }
2117 break;
2118
2119 case Stmt::BinaryOperatorClass: {
2120 const auto *B = cast<BinaryOperator>(S);
2121 if (B->isLogicalOp()) {
2122 Bldr.takeNodes(Pred);
2123 VisitLogicalExpr(B, Pred, Dst);
2124 Bldr.addNodes(Dst);
2125 break;
2126 }
2127 else if (B->getOpcode() == BO_Comma) {
2128 ProgramStateRef state = Pred->getState();
2129 Bldr.generateNode(B, Pred,
2130 state->BindExpr(B, Pred->getLocationContext(),
2131 state->getSVal(B->getRHS(),
2132 Pred->getLocationContext())));
2133 break;
2134 }
2135
2136 Bldr.takeNodes(Pred);
2137
2138 if (AMgr.options.ShouldEagerlyAssume &&
2139 (B->isRelationalOp() || B->isEqualityOp())) {
2140 ExplodedNodeSet Tmp;
2143 }
2144 else
2146
2147 Bldr.addNodes(Dst);
2148 break;
2149 }
2150
2151 case Stmt::CXXOperatorCallExprClass: {
2152 const auto *OCE = cast<CXXOperatorCallExpr>(S);
2153
2154 // For instance method operators, make sure the 'this' argument has a
2155 // valid region.
2156 const Decl *Callee = OCE->getCalleeDecl();
2157 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
2158 if (MD->isImplicitObjectMemberFunction()) {
2159 ProgramStateRef State = Pred->getState();
2160 const LocationContext *LCtx = Pred->getLocationContext();
2161 ProgramStateRef NewState =
2162 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
2163 if (NewState != State) {
2164 Pred = Bldr.generateNode(OCE, Pred, NewState, /*tag=*/nullptr,
2166 // Did we cache out?
2167 if (!Pred)
2168 break;
2169 }
2170 }
2171 }
2172 [[fallthrough]];
2173 }
2174
2175 case Stmt::CallExprClass:
2176 case Stmt::CXXMemberCallExprClass:
2177 case Stmt::UserDefinedLiteralClass:
2178 Bldr.takeNodes(Pred);
2179 VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
2180 Bldr.addNodes(Dst);
2181 break;
2182
2183 case Stmt::CXXCatchStmtClass:
2184 Bldr.takeNodes(Pred);
2186 Bldr.addNodes(Dst);
2187 break;
2188
2189 case Stmt::CXXTemporaryObjectExprClass:
2190 case Stmt::CXXConstructExprClass:
2191 Bldr.takeNodes(Pred);
2193 Bldr.addNodes(Dst);
2194 break;
2195
2196 case Stmt::CXXInheritedCtorInitExprClass:
2197 Bldr.takeNodes(Pred);
2199 Dst);
2200 Bldr.addNodes(Dst);
2201 break;
2202
2203 case Stmt::CXXNewExprClass: {
2204 Bldr.takeNodes(Pred);
2205
2206 ExplodedNodeSet PreVisit;
2207 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
2208
2209 ExplodedNodeSet PostVisit;
2210 for (const auto i : PreVisit)
2211 VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
2212
2213 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
2214 Bldr.addNodes(Dst);
2215 break;
2216 }
2217
2218 case Stmt::CXXDeleteExprClass: {
2219 Bldr.takeNodes(Pred);
2220 ExplodedNodeSet PreVisit;
2221 const auto *CDE = cast<CXXDeleteExpr>(S);
2222 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
2223 ExplodedNodeSet PostVisit;
2224 getCheckerManager().runCheckersForPostStmt(PostVisit, PreVisit, S, *this);
2225
2226 for (const auto i : PostVisit)
2227 VisitCXXDeleteExpr(CDE, i, Dst);
2228
2229 Bldr.addNodes(Dst);
2230 break;
2231 }
2232 // FIXME: ChooseExpr is really a constant. We need to fix
2233 // the CFG do not model them as explicit control-flow.
2234
2235 case Stmt::ChooseExprClass: { // __builtin_choose_expr
2236 Bldr.takeNodes(Pred);
2237 const auto *C = cast<ChooseExpr>(S);
2238 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
2239 Bldr.addNodes(Dst);
2240 break;
2241 }
2242
2243 case Stmt::CompoundAssignOperatorClass:
2244 Bldr.takeNodes(Pred);
2246 Bldr.addNodes(Dst);
2247 break;
2248
2249 case Stmt::CompoundLiteralExprClass:
2250 Bldr.takeNodes(Pred);
2252 Bldr.addNodes(Dst);
2253 break;
2254
2255 case Stmt::BinaryConditionalOperatorClass:
2256 case Stmt::ConditionalOperatorClass: { // '?' operator
2257 Bldr.takeNodes(Pred);
2258 const auto *C = cast<AbstractConditionalOperator>(S);
2259 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
2260 Bldr.addNodes(Dst);
2261 break;
2262 }
2263
2264 case Stmt::CXXThisExprClass:
2265 Bldr.takeNodes(Pred);
2266 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
2267 Bldr.addNodes(Dst);
2268 break;
2269
2270 case Stmt::DeclRefExprClass: {
2271 Bldr.takeNodes(Pred);
2272 const auto *DE = cast<DeclRefExpr>(S);
2273 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
2274 Bldr.addNodes(Dst);
2275 break;
2276 }
2277
2278 case Stmt::DeclStmtClass:
2279 Bldr.takeNodes(Pred);
2280 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
2281 Bldr.addNodes(Dst);
2282 break;
2283
2284 case Stmt::ImplicitCastExprClass:
2285 case Stmt::CStyleCastExprClass:
2286 case Stmt::CXXStaticCastExprClass:
2287 case Stmt::CXXDynamicCastExprClass:
2288 case Stmt::CXXReinterpretCastExprClass:
2289 case Stmt::CXXConstCastExprClass:
2290 case Stmt::CXXFunctionalCastExprClass:
2291 case Stmt::BuiltinBitCastExprClass:
2292 case Stmt::ObjCBridgedCastExprClass:
2293 case Stmt::CXXAddrspaceCastExprClass: {
2294 Bldr.takeNodes(Pred);
2295 const auto *C = cast<CastExpr>(S);
2296 ExplodedNodeSet dstExpr;
2297 VisitCast(C, C->getSubExpr(), Pred, dstExpr);
2298
2299 // Handle the postvisit checks.
2300 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
2301 Bldr.addNodes(Dst);
2302 break;
2303 }
2304
2305 case Expr::MaterializeTemporaryExprClass: {
2306 Bldr.takeNodes(Pred);
2307 const auto *MTE = cast<MaterializeTemporaryExpr>(S);
2308 ExplodedNodeSet dstPrevisit;
2309 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
2310 ExplodedNodeSet dstExpr;
2311 for (const auto i : dstPrevisit)
2312 CreateCXXTemporaryObject(MTE, i, dstExpr);
2313 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
2314 Bldr.addNodes(Dst);
2315 break;
2316 }
2317
2318 case Stmt::InitListExprClass: {
2319 const InitListExpr *E = cast<InitListExpr>(S);
2320 Bldr.takeNodes(Pred);
2321 ConstructInitList(E, E->inits(), E->isTransparent(), Pred, Dst);
2322 Bldr.addNodes(Dst);
2323 break;
2324 }
2325
2326 case Expr::CXXParenListInitExprClass: {
2328 Bldr.takeNodes(Pred);
2329 ConstructInitList(E, E->getInitExprs(), /*IsTransparent*/ false, Pred,
2330 Dst);
2331 Bldr.addNodes(Dst);
2332 break;
2333 }
2334
2335 case Stmt::MemberExprClass:
2336 Bldr.takeNodes(Pred);
2337 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
2338 Bldr.addNodes(Dst);
2339 break;
2340
2341 case Stmt::AtomicExprClass:
2342 Bldr.takeNodes(Pred);
2343 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
2344 Bldr.addNodes(Dst);
2345 break;
2346
2347 case Stmt::ObjCIvarRefExprClass:
2348 Bldr.takeNodes(Pred);
2350 Bldr.addNodes(Dst);
2351 break;
2352
2353 case Stmt::ObjCForCollectionStmtClass:
2354 Bldr.takeNodes(Pred);
2356 Bldr.addNodes(Dst);
2357 break;
2358
2359 case Stmt::ObjCMessageExprClass:
2360 Bldr.takeNodes(Pred);
2362 Bldr.addNodes(Dst);
2363 break;
2364
2365 case Stmt::ObjCAtThrowStmtClass:
2366 case Stmt::CXXThrowExprClass:
2367 // FIXME: This is not complete. We basically treat @throw as
2368 // an abort.
2369 Bldr.generateSink(S, Pred, Pred->getState());
2370 break;
2371
2372 case Stmt::ReturnStmtClass:
2373 Bldr.takeNodes(Pred);
2374 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
2375 Bldr.addNodes(Dst);
2376 break;
2377
2378 case Stmt::OffsetOfExprClass: {
2379 Bldr.takeNodes(Pred);
2380 ExplodedNodeSet PreVisit;
2381 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
2382
2383 ExplodedNodeSet PostVisit;
2384 for (const auto Node : PreVisit)
2385 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
2386
2387 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
2388 Bldr.addNodes(Dst);
2389 break;
2390 }
2391
2392 case Stmt::UnaryExprOrTypeTraitExprClass:
2393 Bldr.takeNodes(Pred);
2395 Pred, Dst);
2396 Bldr.addNodes(Dst);
2397 break;
2398
2399 case Stmt::StmtExprClass: {
2400 const auto *SE = cast<StmtExpr>(S);
2401
2402 if (SE->getSubStmt()->body_empty()) {
2403 // Empty statement expression.
2404 assert(SE->getType() == getContext().VoidTy
2405 && "Empty statement expression must have void type.");
2406 break;
2407 }
2408
2409 if (const auto *LastExpr =
2410 dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
2411 ProgramStateRef state = Pred->getState();
2412 Bldr.generateNode(SE, Pred,
2413 state->BindExpr(SE, Pred->getLocationContext(),
2414 state->getSVal(LastExpr,
2415 Pred->getLocationContext())));
2416 }
2417 break;
2418 }
2419
2420 case Stmt::UnaryOperatorClass: {
2421 Bldr.takeNodes(Pred);
2422 const auto *U = cast<UnaryOperator>(S);
2423 if (AMgr.options.ShouldEagerlyAssume && (U->getOpcode() == UO_LNot)) {
2424 ExplodedNodeSet Tmp;
2425 VisitUnaryOperator(U, Pred, Tmp);
2427 }
2428 else
2429 VisitUnaryOperator(U, Pred, Dst);
2430 Bldr.addNodes(Dst);
2431 break;
2432 }
2433
2434 case Stmt::PseudoObjectExprClass: {
2435 Bldr.takeNodes(Pred);
2436 ProgramStateRef state = Pred->getState();
2437 const auto *PE = cast<PseudoObjectExpr>(S);
2438 if (const Expr *Result = PE->getResultExpr()) {
2439 SVal V = state->getSVal(Result, Pred->getLocationContext());
2440 Bldr.generateNode(S, Pred,
2441 state->BindExpr(S, Pred->getLocationContext(), V));
2442 }
2443 else
2444 Bldr.generateNode(S, Pred,
2445 state->BindExpr(S, Pred->getLocationContext(),
2446 UnknownVal()));
2447
2448 Bldr.addNodes(Dst);
2449 break;
2450 }
2451
2452 case Expr::ObjCIndirectCopyRestoreExprClass: {
2453 // ObjCIndirectCopyRestoreExpr implies passing a temporary for
2454 // correctness of lifetime management. Due to limited analysis
2455 // of ARC, this is implemented as direct arg passing.
2456 Bldr.takeNodes(Pred);
2457 ProgramStateRef state = Pred->getState();
2458 const auto *OIE = cast<ObjCIndirectCopyRestoreExpr>(S);
2459 const Expr *E = OIE->getSubExpr();
2460 SVal V = state->getSVal(E, Pred->getLocationContext());
2461 Bldr.generateNode(S, Pred,
2462 state->BindExpr(S, Pred->getLocationContext(), V));
2463 Bldr.addNodes(Dst);
2464 break;
2465 }
2466 }
2467}
2468
2469bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
2470 const LocationContext *CalleeLC) {
2471 const StackFrameContext *CalleeSF = CalleeLC->getStackFrame();
2472 const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame();
2473 assert(CalleeSF && CallerSF);
2474 ExplodedNode *BeforeProcessingCall = nullptr;
2475 const Stmt *CE = CalleeSF->getCallSite();
2476
2477 // Find the first node before we started processing the call expression.
2478 while (N) {
2479 ProgramPoint L = N->getLocation();
2480 BeforeProcessingCall = N;
2481 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2482
2483 // Skip the nodes corresponding to the inlined code.
2484 if (L.getStackFrame() != CallerSF)
2485 continue;
2486 // We reached the caller. Find the node right before we started
2487 // processing the call.
2488 if (L.isPurgeKind())
2489 continue;
2490 if (L.getAs<PreImplicitCall>())
2491 continue;
2492 if (L.getAs<CallEnter>())
2493 continue;
2494 if (std::optional<StmtPoint> SP = L.getAs<StmtPoint>())
2495 if (SP->getStmt() == CE)
2496 continue;
2497 break;
2498 }
2499
2500 if (!BeforeProcessingCall)
2501 return false;
2502
2503 // TODO: Clean up the unneeded nodes.
2504
2505 // Build an Epsilon node from which we will restart the analyzes.
2506 // Note that CE is permitted to be NULL!
2507 static SimpleProgramPointTag PT("ExprEngine", "Replay without inlining");
2508 ProgramPoint NewNodeLoc = EpsilonPoint(
2509 BeforeProcessingCall->getLocationContext(), CE, nullptr, &PT);
2510 // Add the special flag to GDM to signal retrying with no inlining.
2511 // Note, changing the state ensures that we are not going to cache out.
2512 ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
2513 NewNodeState =
2514 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
2515
2516 // Make the new node a successor of BeforeProcessingCall.
2517 bool IsNew = false;
2518 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
2519 // We cached out at this point. Caching out is common due to us backtracking
2520 // from the inlined function, which might spawn several paths.
2521 if (!IsNew)
2522 return true;
2523
2524 NewNode->addPredecessor(BeforeProcessingCall, G);
2525
2526 // Add the new node to the work list.
2527 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
2528 CalleeSF->getIndex());
2529 NumTimesRetriedWithoutInlining++;
2530 return true;
2531}
2532
2533/// Return the innermost location context which is inlined at `Node`, unless
2534/// it's the top-level (entry point) location context.
2536 ExplodedGraph &G) {
2537 const LocationContext *CalleeLC = Node->getLocation().getLocationContext();
2538 const LocationContext *RootLC =
2540
2541 if (CalleeLC->getStackFrame() == RootLC->getStackFrame())
2542 return nullptr;
2543
2544 return CalleeLC;
2545}
2546
2547/// Block entrance. (Update counters).
2549 NodeBuilderWithSinks &nodeBuilder,
2550 ExplodedNode *Pred) {
2551 // If we reach a loop which has a known bound (and meets
2552 // other constraints) then consider completely unrolling it.
2553 if(AMgr.options.ShouldUnrollLoops) {
2554 unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
2555 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt();
2556 if (Term) {
2557 ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
2558 Pred, maxBlockVisitOnPath);
2559 if (NewState != Pred->getState()) {
2560 ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
2561 if (!UpdatedNode)
2562 return;
2563 Pred = UpdatedNode;
2564 }
2565 }
2566 // Is we are inside an unrolled loop then no need the check the counters.
2567 if(isUnrolledState(Pred->getState()))
2568 return;
2569 }
2570
2571 // If this block is terminated by a loop and it has already been visited the
2572 // maximum number of times, widen the loop.
2573 unsigned int BlockCount = nodeBuilder.getContext().blockCount();
2574 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
2575 AMgr.options.ShouldWidenLoops) {
2576 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt();
2577 if (!isa_and_nonnull<ForStmt, WhileStmt, DoStmt, CXXForRangeStmt>(Term))
2578 return;
2579
2580 // Widen.
2581 const LocationContext *LCtx = Pred->getLocationContext();
2582
2583 // FIXME:
2584 // We cannot use the CFG element from the via `ExprEngine::getCFGElementRef`
2585 // since we are currently at the block entrance and the current reference
2586 // would be stale. Ideally, we should pass on the terminator of the CFG
2587 // block, but the terminator cannot be referred as a CFG element.
2588 // Here we just pass the the first CFG element in the block.
2589 ProgramStateRef WidenedState =
2590 getWidenedLoopState(Pred->getState(), LCtx, BlockCount,
2591 *nodeBuilder.getContext().getBlock()->ref_begin());
2592 nodeBuilder.generateNode(WidenedState, Pred);
2593 return;
2594 }
2595
2596 // FIXME: Refactor this into a checker.
2597 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
2598 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
2599 const ExplodedNode *Sink =
2600 nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
2601
2602 if (const LocationContext *LC = getInlinedLocationContext(Pred, G)) {
2603 // FIXME: This will unconditionally prevent inlining this function (even
2604 // from other entry points), which is not a reasonable heuristic: even if
2605 // we reached max block count on this particular execution path, there
2606 // may be other execution paths (especially with other parametrizations)
2607 // where the analyzer can reach the end of the function (so there is no
2608 // natural reason to avoid inlining it). However, disabling this would
2609 // significantly increase the analysis time (because more entry points
2610 // would exhaust their allocated budget), so it must be compensated by a
2611 // different (more reasonable) reduction of analysis scope.
2612 Engine.FunctionSummaries->markShouldNotInline(
2613 LC->getStackFrame()->getDecl());
2614
2615 // Re-run the call evaluation without inlining it, by storing the
2616 // no-inlining policy in the state and enqueuing the new work item on
2617 // the list. Replay should almost never fail. Use the stats to catch it
2618 // if it does.
2619 if ((!AMgr.options.NoRetryExhausted && replayWithoutInlining(Pred, LC)))
2620 return;
2621 NumMaxBlockCountReachedInInlined++;
2622 } else
2623 NumMaxBlockCountReached++;
2624
2625 // Make sink nodes as exhausted(for stats) only if retry failed.
2626 Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
2627 }
2628}
2629
2631 const BlockEntrance &Entrance,
2632 ExplodedNode *Pred,
2633 ExplodedNodeSet &Dst) {
2634 llvm::PrettyStackTraceFormat CrashInfo(
2635 "Processing block entrance B%d -> B%d",
2636 Entrance.getPreviousBlock()->getBlockID(),
2637 Entrance.getBlock()->getBlockID());
2638 currBldrCtx = &BldCtx;
2639 getCheckerManager().runCheckersForBlockEntrance(Dst, Pred, Entrance, *this);
2640 currBldrCtx = nullptr;
2641}
2642
2643//===----------------------------------------------------------------------===//
2644// Branch processing.
2645//===----------------------------------------------------------------------===//
2646
2647/// RecoverCastedSymbol - A helper function for ProcessBranch that is used
2648/// to try to recover some path-sensitivity for casts of symbolic
2649/// integers that promote their values (which are currently not tracked well).
2650/// This function returns the SVal bound to Condition->IgnoreCasts if all the
2651// cast(s) did was sign-extend the original value.
2653 const Stmt *Condition,
2654 const LocationContext *LCtx,
2655 ASTContext &Ctx) {
2656
2657 const auto *Ex = dyn_cast<Expr>(Condition);
2658 if (!Ex)
2659 return UnknownVal();
2660
2661 uint64_t bits = 0;
2662 bool bitsInit = false;
2663
2664 while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
2665 QualType T = CE->getType();
2666
2667 if (!T->isIntegralOrEnumerationType())
2668 return UnknownVal();
2669
2670 uint64_t newBits = Ctx.getTypeSize(T);
2671 if (!bitsInit || newBits < bits) {
2672 bitsInit = true;
2673 bits = newBits;
2674 }
2675
2676 Ex = CE->getSubExpr();
2677 }
2678
2679 // We reached a non-cast. Is it a symbolic value?
2680 QualType T = Ex->getType();
2681
2682 if (!bitsInit || !T->isIntegralOrEnumerationType() ||
2683 Ctx.getTypeSize(T) > bits)
2684 return UnknownVal();
2685
2686 return state->getSVal(Ex, LCtx);
2687}
2688
2689#ifndef NDEBUG
2690static const Stmt *getRightmostLeaf(const Stmt *Condition) {
2691 while (Condition) {
2692 const auto *BO = dyn_cast<BinaryOperator>(Condition);
2693 if (!BO || !BO->isLogicalOp()) {
2694 return Condition;
2695 }
2696 Condition = BO->getRHS()->IgnoreParens();
2697 }
2698 return nullptr;
2699}
2700#endif
2701
2702// Returns the condition the branch at the end of 'B' depends on and whose value
2703// has been evaluated within 'B'.
2704// In most cases, the terminator condition of 'B' will be evaluated fully in
2705// the last statement of 'B'; in those cases, the resolved condition is the
2706// given 'Condition'.
2707// If the condition of the branch is a logical binary operator tree, the CFG is
2708// optimized: in that case, we know that the expression formed by all but the
2709// rightmost leaf of the logical binary operator tree must be true, and thus
2710// the branch condition is at this point equivalent to the truth value of that
2711// rightmost leaf; the CFG block thus only evaluates this rightmost leaf
2712// expression in its final statement. As the full condition in that case was
2713// not evaluated, and is thus not in the SVal cache, we need to use that leaf
2714// expression to evaluate the truth value of the condition in the current state
2715// space.
2717 const CFGBlock *B) {
2718 if (const auto *Ex = dyn_cast<Expr>(Condition))
2719 Condition = Ex->IgnoreParens();
2720
2721 const auto *BO = dyn_cast<BinaryOperator>(Condition);
2722 if (!BO || !BO->isLogicalOp())
2723 return Condition;
2724
2725 assert(B->getTerminator().isStmtBranch() &&
2726 "Other kinds of branches are handled separately!");
2727
2728 // For logical operations, we still have the case where some branches
2729 // use the traditional "merge" approach and others sink the branch
2730 // directly into the basic blocks representing the logical operation.
2731 // We need to distinguish between those two cases here.
2732
2733 // The invariants are still shifting, but it is possible that the
2734 // last element in a CFGBlock is not a CFGStmt. Look for the last
2735 // CFGStmt as the value of the condition.
2736 for (CFGElement Elem : llvm::reverse(*B)) {
2737 std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
2738 if (!CS)
2739 continue;
2740 const Stmt *LastStmt = CS->getStmt();
2741 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
2742 return LastStmt;
2743 }
2744 llvm_unreachable("could not resolve condition");
2745}
2746
2748 std::pair<const ObjCForCollectionStmt *, const LocationContext *>;
2749
2750REGISTER_MAP_WITH_PROGRAMSTATE(ObjCForHasMoreIterations, ObjCForLctxPair, bool)
2751
2753 ProgramStateRef State, const ObjCForCollectionStmt *O,
2754 const LocationContext *LC, bool HasMoreIteraton) {
2755 assert(!State->contains<ObjCForHasMoreIterations>({O, LC}));
2756 return State->set<ObjCForHasMoreIterations>({O, LC}, HasMoreIteraton);
2757}
2758
2761 const ObjCForCollectionStmt *O,
2762 const LocationContext *LC) {
2763 assert(State->contains<ObjCForHasMoreIterations>({O, LC}));
2764 return State->remove<ObjCForHasMoreIterations>({O, LC});
2765}
2766
2768 const ObjCForCollectionStmt *O,
2769 const LocationContext *LC) {
2770 assert(State->contains<ObjCForHasMoreIterations>({O, LC}));
2771 return *State->get<ObjCForHasMoreIterations>({O, LC});
2772}
2773
2774/// Split the state on whether there are any more iterations left for this loop.
2775/// Returns a (HasMoreIteration, HasNoMoreIteration) pair, or std::nullopt when
2776/// the acquisition of the loop condition value failed.
2777static std::optional<std::pair<ProgramStateRef, ProgramStateRef>>
2779 ProgramStateRef State = N->getState();
2780 if (const auto *ObjCFor = dyn_cast<ObjCForCollectionStmt>(Condition)) {
2781 bool HasMoreIteraton =
2783 // Checkers have already ran on branch conditions, so the current
2784 // information as to whether the loop has more iteration becomes outdated
2785 // after this point.
2786 State = ExprEngine::removeIterationState(State, ObjCFor,
2787 N->getLocationContext());
2788 if (HasMoreIteraton)
2789 return std::pair<ProgramStateRef, ProgramStateRef>{State, nullptr};
2790 else
2791 return std::pair<ProgramStateRef, ProgramStateRef>{nullptr, State};
2792 }
2793 SVal X = State->getSVal(Condition, N->getLocationContext());
2794
2795 if (X.isUnknownOrUndef()) {
2796 // Give it a chance to recover from unknown.
2797 if (const auto *Ex = dyn_cast<Expr>(Condition)) {
2798 if (Ex->getType()->isIntegralOrEnumerationType()) {
2799 // Try to recover some path-sensitivity. Right now casts of symbolic
2800 // integers that promote their values are currently not tracked well.
2801 // If 'Condition' is such an expression, try and recover the
2802 // underlying value and use that instead.
2803 SVal recovered =
2805 N->getState()->getStateManager().getContext());
2806
2807 if (!recovered.isUnknown()) {
2808 X = recovered;
2809 }
2810 }
2811 }
2812 }
2813
2814 // If the condition is still unknown, give up.
2815 if (X.isUnknownOrUndef())
2816 return std::nullopt;
2817
2818 DefinedSVal V = X.castAs<DefinedSVal>();
2819
2820 ProgramStateRef StTrue, StFalse;
2821 return State->assume(V);
2822}
2823
2825 const Stmt *Condition, NodeBuilderContext &BldCtx, ExplodedNode *Pred,
2826 ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF,
2827 std::optional<unsigned> IterationsCompletedInLoop) {
2829 "CXXBindTemporaryExprs are handled by processBindTemporary.");
2830 currBldrCtx = &BldCtx;
2831
2832 // Check for NULL conditions; e.g. "for(;;)"
2833 if (!Condition) {
2834 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
2835 NullCondBldr.generateNode(Pred->getState(), true, Pred);
2836 return;
2837 }
2838
2839 if (const auto *Ex = dyn_cast<Expr>(Condition))
2840 Condition = Ex->IgnoreParens();
2841
2843 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
2844 Condition->getBeginLoc(),
2845 "Error evaluating branch");
2846
2847 ExplodedNodeSet CheckersOutSet;
2849 Pred, *this);
2850 // We generated only sinks.
2851 if (CheckersOutSet.empty())
2852 return;
2853
2854 BranchNodeBuilder Builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
2855 for (ExplodedNode *PredN : CheckersOutSet) {
2856 if (PredN->isSink())
2857 continue;
2858
2859 ProgramStateRef PrevState = PredN->getState();
2860
2861 ProgramStateRef StTrue = PrevState, StFalse = PrevState;
2862 if (const auto KnownCondValueAssumption = assumeCondition(Condition, PredN))
2863 std::tie(StTrue, StFalse) = *KnownCondValueAssumption;
2864
2865 if (StTrue && StFalse)
2867
2868 // We want to ensure consistent behavior between `eagerly-assume=false`,
2869 // when the state split is always performed by the `assumeCondition()`
2870 // call within this function and `eagerly-assume=true` (the default), when
2871 // some conditions (comparison operators, unary negation) can trigger a
2872 // state split before this callback. There are some contrived corner cases
2873 // that behave differently with and without `eagerly-assume`, but I don't
2874 // know about an example that could plausibly appear in "real" code.
2875 bool BothFeasible =
2876 (StTrue && StFalse) ||
2877 didEagerlyAssumeBifurcateAt(PrevState, dyn_cast<Expr>(Condition));
2878
2879 if (StTrue) {
2880 // In a loop, if both branches are feasible (i.e. the analyzer doesn't
2881 // understand the loop condition) and two iterations have already been
2882 // completed, then don't assume a third iteration because it is a
2883 // redundant execution path (unlikely to be different from earlier loop
2884 // exits) and can cause false positives if e.g. the loop iterates over a
2885 // two-element structure with an opaque condition.
2886 //
2887 // The iteration count "2" is hardcoded because it's the natural limit:
2888 // * the fact that the programmer wrote a loop (and not just an `if`)
2889 // implies that they thought that the loop body might be executed twice;
2890 // * however, there are situations where the programmer knows that there
2891 // are at most two iterations but writes a loop that appears to be
2892 // generic, because there is no special syntax for "loop with at most
2893 // two iterations". (This pattern is common in FFMPEG and appears in
2894 // many other projects as well.)
2895 bool CompletedTwoIterations = IterationsCompletedInLoop.value_or(0) >= 2;
2896 bool SkipTrueBranch = BothFeasible && CompletedTwoIterations;
2897
2898 // FIXME: This "don't assume third iteration" heuristic partially
2899 // conflicts with the widen-loop analysis option (which is off by
2900 // default). If we intend to support and stabilize the loop widening,
2901 // we must ensure that it 'plays nicely' with this logic.
2902 if (!SkipTrueBranch || AMgr.options.ShouldWidenLoops) {
2903 Builder.generateNode(StTrue, true, PredN);
2904 } else if (!AMgr.options.InlineFunctionsWithAmbiguousLoops) {
2905 // FIXME: There is an ancient and arbitrary heuristic in
2906 // `ExprEngine::processCFGBlockEntrance` which prevents all further
2907 // inlining of a function if it finds an execution path within that
2908 // function which reaches the `MaxBlockVisitOnPath` limit (a/k/a
2909 // `analyzer-max-loop`, by default four iterations in a loop). Adding
2910 // this "don't assume third iteration" logic significantly increased
2911 // the analysis runtime on some inputs because less functions were
2912 // arbitrarily excluded from being inlined, so more entry points used
2913 // up their full allocated budget. As a hacky compensation for this,
2914 // here we apply the "should not inline" mark in cases when the loop
2915 // could potentially reach the `MaxBlockVisitOnPath` limit without the
2916 // "don't assume third iteration" logic. This slightly overcompensates
2917 // (activates if the third iteration can be entered, and will not
2918 // recognize cases where the fourth iteration would't be completed), but
2919 // should be good enough for practical purposes.
2920 if (const LocationContext *LC = getInlinedLocationContext(Pred, G)) {
2921 Engine.FunctionSummaries->markShouldNotInline(
2922 LC->getStackFrame()->getDecl());
2923 }
2924 }
2925 }
2926
2927 if (StFalse) {
2928 // In a loop, if both branches are feasible (i.e. the analyzer doesn't
2929 // understand the loop condition), we are before the first iteration and
2930 // the analyzer option `assume-at-least-one-iteration` is set to `true`,
2931 // then avoid creating the execution path where the loop is skipped.
2932 //
2933 // In some situations this "loop is skipped" execution path is an
2934 // important corner case that may evade the notice of the developer and
2935 // hide significant bugs -- however, there are also many situations where
2936 // it's guaranteed that at least one iteration will happen (e.g. some
2937 // data structure is always nonempty), but the analyzer cannot realize
2938 // this and will produce false positives when it assumes that the loop is
2939 // skipped.
2940 bool BeforeFirstIteration = IterationsCompletedInLoop == std::optional{0};
2941 bool SkipFalseBranch = BothFeasible && BeforeFirstIteration &&
2942 AMgr.options.ShouldAssumeAtLeastOneIteration;
2943 if (!SkipFalseBranch)
2944 Builder.generateNode(StFalse, false, PredN);
2945 }
2946 }
2947 currBldrCtx = nullptr;
2948}
2949
2950/// The GDM component containing the set of global variables which have been
2951/// previously initialized with explicit initializers.
2953 llvm::ImmutableSet<const VarDecl *>)
2954
2956 const DeclStmt *DS, NodeBuilderContext &BuilderCtx, ExplodedNode *Pred,
2957 ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) {
2958 currBldrCtx = &BuilderCtx;
2959
2960 const auto *VD = cast<VarDecl>(DS->getSingleDecl());
2961 ProgramStateRef state = Pred->getState();
2962 bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
2963 BranchNodeBuilder Builder(Pred, Dst, BuilderCtx, DstT, DstF);
2964
2965 if (!initHasRun) {
2966 state = state->add<InitializedGlobalsSet>(VD);
2967 }
2968
2969 Builder.generateNode(state, initHasRun, Pred);
2970
2971 currBldrCtx = nullptr;
2972}
2973
2974/// processIndirectGoto - Called by CoreEngine. Used to generate successor
2975/// nodes by processing the 'effects' of a computed goto jump.
2977 ProgramStateRef state = builder.getState();
2978 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
2979
2980 // Three possibilities:
2981 //
2982 // (1) We know the computed label.
2983 // (2) The label is NULL (or some other constant), or Undefined.
2984 // (3) We have no clue about the label. Dispatch to all targets.
2985 //
2986
2988
2989 if (std::optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
2990 const LabelDecl *L = LV->getLabel();
2991
2992 for (iterator Succ : builder) {
2993 if (Succ.getLabel() == L) {
2994 builder.generateNode(Succ, state);
2995 return;
2996 }
2997 }
2998
2999 llvm_unreachable("No block with label.");
3000 }
3001
3003 // Dispatch to the first target and mark it as a sink.
3004 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
3005 // FIXME: add checker visit.
3006 // UndefBranches.insert(N);
3007 return;
3008 }
3009
3010 // This is really a catch-all. We don't support symbolics yet.
3011 // FIXME: Implement dispatch for symbolic pointers.
3012
3013 for (iterator Succ : builder)
3014 builder.generateNode(Succ, state);
3015}
3016
3018 ExplodedNode *Pred,
3019 ExplodedNodeSet &Dst,
3020 const BlockEdge &L) {
3021 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
3022 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
3023}
3024
3025/// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
3026/// nodes when the control reaches the end of a function.
3028 ExplodedNode *Pred,
3029 const ReturnStmt *RS) {
3030 ProgramStateRef State = Pred->getState();
3031
3032 if (!Pred->getStackFrame()->inTopFrame())
3033 State = finishArgumentConstruction(
3034 State, *getStateManager().getCallEventManager().getCaller(
3035 Pred->getStackFrame(), Pred->getState()));
3036
3037 // FIXME: We currently cannot assert that temporaries are clear, because
3038 // lifetime extended temporaries are not always modelled correctly. In some
3039 // cases when we materialize the temporary, we do
3040 // createTemporaryRegionIfNeeded(), and the region changes, and also the
3041 // respective destructor becomes automatic from temporary. So for now clean up
3042 // the state manually before asserting. Ideally, this braced block of code
3043 // should go away.
3044 {
3045 const LocationContext *FromLC = Pred->getLocationContext();
3046 const LocationContext *ToLC = FromLC->getStackFrame()->getParent();
3047 const LocationContext *LC = FromLC;
3048 while (LC != ToLC) {
3049 assert(LC && "ToLC must be a parent of FromLC!");
3050 for (auto I : State->get<ObjectsUnderConstruction>())
3051 if (I.first.getLocationContext() == LC) {
3052 // The comment above only pardons us for not cleaning up a
3053 // temporary destructor. If any other statements are found here,
3054 // it must be a separate problem.
3055 assert(I.first.getItem().getKind() ==
3057 I.first.getItem().getKind() ==
3059 State = State->remove<ObjectsUnderConstruction>(I.first);
3060 }
3061 LC = LC->getParent();
3062 }
3063 }
3064
3065 // Perform the transition with cleanups.
3066 if (State != Pred->getState()) {
3067 ExplodedNodeSet PostCleanup;
3068 NodeBuilder Bldr(Pred, PostCleanup, BC);
3069 Pred = Bldr.generateNode(Pred->getLocation(), State, Pred);
3070 if (!Pred) {
3071 // The node with clean temporaries already exists. We might have reached
3072 // it on a path on which we initialize different temporaries.
3073 return;
3074 }
3075 }
3076
3077 assert(areAllObjectsFullyConstructed(Pred->getState(),
3078 Pred->getLocationContext(),
3079 Pred->getStackFrame()->getParent()));
3080 ExplodedNodeSet Dst;
3081 if (Pred->getLocationContext()->inTopFrame()) {
3082 // Remove dead symbols.
3083 ExplodedNodeSet AfterRemovedDead;
3084 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
3085
3086 // Notify checkers.
3087 for (const auto I : AfterRemovedDead)
3088 getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this, RS);
3089 } else {
3090 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this, RS);
3091 }
3092
3093 Engine.enqueueEndOfFunction(Dst, RS);
3094}
3095
3096/// ProcessSwitch - Called by CoreEngine. Used to generate successor
3097/// nodes by processing the 'effects' of a switch statement.
3100
3101 ProgramStateRef state = builder.getState();
3102 const Expr *CondE = builder.getCondition();
3103 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
3104
3105 if (CondV_untested.isUndef()) {
3106 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
3107 // FIXME: add checker
3108 //UndefBranches.insert(N);
3109
3110 return;
3111 }
3112 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
3113
3114 ProgramStateRef DefaultSt = state;
3115
3116 iterator I = builder.begin(), EI = builder.end();
3117 bool defaultIsFeasible = I == EI;
3118
3119 for ( ; I != EI; ++I) {
3120 // Successor may be pruned out during CFG construction.
3121 if (!I.getBlock())
3122 continue;
3123
3124 const CaseStmt *Case = I.getCase();
3125
3126 // Evaluate the LHS of the case value.
3127 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
3128 assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
3129
3130 // Get the RHS of the case, if it exists.
3131 llvm::APSInt V2;
3132 if (const Expr *E = Case->getRHS())
3133 V2 = E->EvaluateKnownConstInt(getContext());
3134 else
3135 V2 = V1;
3136
3137 ProgramStateRef StateCase;
3138 if (std::optional<NonLoc> NL = CondV.getAs<NonLoc>())
3139 std::tie(StateCase, DefaultSt) =
3140 DefaultSt->assumeInclusiveRange(*NL, V1, V2);
3141 else // UnknownVal
3142 StateCase = DefaultSt;
3143
3144 if (StateCase)
3145 builder.generateCaseStmtNode(I, StateCase);
3146
3147 // Now "assume" that the case doesn't match. Add this state
3148 // to the default state (if it is feasible).
3149 if (DefaultSt)
3150 defaultIsFeasible = true;
3151 else {
3152 defaultIsFeasible = false;
3153 break;
3154 }
3155 }
3156
3157 if (!defaultIsFeasible)
3158 return;
3159
3160 // If we have switch(enum value), the default branch is not
3161 // feasible if all of the enum constants not covered by 'case:' statements
3162 // are not feasible values for the switch condition.
3163 //
3164 // Note that this isn't as accurate as it could be. Even if there isn't
3165 // a case for a particular enum value as long as that enum value isn't
3166 // feasible then it shouldn't be considered for making 'default:' reachable.
3167 const SwitchStmt *SS = builder.getSwitch();
3168 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
3169 if (CondExpr->getType()->isEnumeralType()) {
3170 if (SS->isAllEnumCasesCovered())
3171 return;
3172 }
3173
3174 builder.generateDefaultCaseNode(DefaultSt);
3175}
3176
3177//===----------------------------------------------------------------------===//
3178// Transfer functions: Loads and stores.
3179//===----------------------------------------------------------------------===//
3180
3182 ExplodedNode *Pred,
3183 ExplodedNodeSet &Dst) {
3184 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
3185
3186 ProgramStateRef state = Pred->getState();
3187 const LocationContext *LCtx = Pred->getLocationContext();
3188
3189 auto resolveAsLambdaCapturedVar =
3190 [&](const ValueDecl *VD) -> std::optional<std::pair<SVal, QualType>> {
3191 const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
3192 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
3193 if (AMgr.options.ShouldInlineLambdas && DeclRefEx &&
3194 DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
3195 MD->getParent()->isLambda()) {
3196 // Lookup the field of the lambda.
3197 const CXXRecordDecl *CXXRec = MD->getParent();
3198 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
3199 FieldDecl *LambdaThisCaptureField;
3200 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
3201
3202 // Sema follows a sequence of complex rules to determine whether the
3203 // variable should be captured.
3204 if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
3205 Loc CXXThis = svalBuilder.getCXXThis(MD, LCtx->getStackFrame());
3206 SVal CXXThisVal = state->getSVal(CXXThis);
3207 return std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
3208 }
3209 }
3210
3211 return std::nullopt;
3212 };
3213
3214 if (const auto *VD = dyn_cast<VarDecl>(D)) {
3215 // C permits "extern void v", and if you cast the address to a valid type,
3216 // you can even do things with it. We simply pretend
3217 assert(Ex->isGLValue() || VD->getType()->isVoidType());
3218 const LocationContext *LocCtxt = Pred->getLocationContext();
3219 std::optional<std::pair<SVal, QualType>> VInfo =
3220 resolveAsLambdaCapturedVar(VD);
3221
3222 if (!VInfo)
3223 VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType());
3224
3225 SVal V = VInfo->first;
3226 bool IsReference = VInfo->second->isReferenceType();
3227
3228 // For references, the 'lvalue' is the pointer address stored in the
3229 // reference region.
3230 if (IsReference) {
3231 if (const MemRegion *R = V.getAsRegion())
3232 V = state->getSVal(R);
3233 else
3234 V = UnknownVal();
3235 }
3236
3237 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
3239 return;
3240 }
3241 if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
3242 assert(!Ex->isGLValue());
3243 SVal V = svalBuilder.makeIntVal(ED->getInitVal());
3244 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
3245 return;
3246 }
3247 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3248 SVal V = svalBuilder.getFunctionPointer(FD);
3249 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
3251 return;
3252 }
3254 // Delegate all work related to pointer to members to the surrounding
3255 // operator&.
3256 return;
3257 }
3258 if (const auto *BD = dyn_cast<BindingDecl>(D)) {
3259 // Handle structured bindings captured by lambda.
3260 if (std::optional<std::pair<SVal, QualType>> VInfo =
3261 resolveAsLambdaCapturedVar(BD)) {
3262 auto [V, T] = VInfo.value();
3263
3264 if (T->isReferenceType()) {
3265 if (const MemRegion *R = V.getAsRegion())
3266 V = state->getSVal(R);
3267 else
3268 V = UnknownVal();
3269 }
3270
3271 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
3273 return;
3274 }
3275
3276 const auto *DD = cast<DecompositionDecl>(BD->getDecomposedDecl());
3277
3278 SVal Base = state->getLValue(DD, LCtx);
3279 if (DD->getType()->isReferenceType()) {
3280 if (const MemRegion *R = Base.getAsRegion())
3281 Base = state->getSVal(R);
3282 else
3283 Base = UnknownVal();
3284 }
3285
3286 SVal V = UnknownVal();
3287
3288 // Handle binding to data members
3289 if (const auto *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
3290 const auto *Field = cast<FieldDecl>(ME->getMemberDecl());
3291 V = state->getLValue(Field, Base);
3292 }
3293 // Handle binding to arrays
3294 else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
3295 SVal Idx = state->getSVal(ASE->getIdx(), LCtx);
3296
3297 // Note: the index of an element in a structured binding is automatically
3298 // created and it is a unique identifier of the specific element. Thus it
3299 // cannot be a value that varies at runtime.
3300 assert(Idx.isConstant() && "BindingDecl array index is not a constant!");
3301
3302 V = state->getLValue(BD->getType(), Idx, Base);
3303 }
3304 // Handle binding to tuple-like structures
3305 else if (const auto *HV = BD->getHoldingVar()) {
3306 V = state->getLValue(HV, LCtx);
3307
3308 if (HV->getType()->isReferenceType()) {
3309 if (const MemRegion *R = V.getAsRegion())
3310 V = state->getSVal(R);
3311 else
3312 V = UnknownVal();
3313 }
3314 } else
3315 llvm_unreachable("An unknown case of structured binding encountered!");
3316
3317 // In case of tuple-like types the references are already handled, so we
3318 // don't want to handle them again.
3319 if (BD->getType()->isReferenceType() && !BD->getHoldingVar()) {
3320 if (const MemRegion *R = V.getAsRegion())
3321 V = state->getSVal(R);
3322 else
3323 V = UnknownVal();
3324 }
3325
3326 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
3328
3329 return;
3330 }
3331
3332 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
3333 // FIXME: We should meaningfully implement this.
3334 (void)TPO;
3335 return;
3336 }
3337
3338 llvm_unreachable("Support for this Decl not implemented.");
3339}
3340
3341/// VisitArrayInitLoopExpr - Transfer function for array init loop.
3343 ExplodedNode *Pred,
3344 ExplodedNodeSet &Dst) {
3345 ExplodedNodeSet CheckerPreStmt;
3346 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, Ex, *this);
3347
3348 ExplodedNodeSet EvalSet;
3349 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
3350
3351 const Expr *Arr = Ex->getCommonExpr()->getSourceExpr();
3352
3353 for (auto *Node : CheckerPreStmt) {
3354
3355 // The constructor visitior has already taken care of everything.
3357 break;
3358
3359 const LocationContext *LCtx = Node->getLocationContext();
3360 ProgramStateRef state = Node->getState();
3361
3362 SVal Base = UnknownVal();
3363
3364 // As in case of this expression the sub-expressions are not visited by any
3365 // other transfer functions, they are handled by matching their AST.
3366
3367 // Case of implicit copy or move ctor of object with array member
3368 //
3369 // Note: ExprEngine::VisitMemberExpr is not able to bind the array to the
3370 // environment.
3371 //
3372 // struct S {
3373 // int arr[2];
3374 // };
3375 //
3376 //
3377 // S a;
3378 // S b = a;
3379 //
3380 // The AST in case of a *copy constructor* looks like this:
3381 // ArrayInitLoopExpr
3382 // |-OpaqueValueExpr
3383 // | `-MemberExpr <-- match this
3384 // | `-DeclRefExpr
3385 // ` ...
3386 //
3387 //
3388 // S c;
3389 // S d = std::move(d);
3390 //
3391 // In case of a *move constructor* the resulting AST looks like:
3392 // ArrayInitLoopExpr
3393 // |-OpaqueValueExpr
3394 // | `-MemberExpr <-- match this first
3395 // | `-CXXStaticCastExpr <-- match this after
3396 // | `-DeclRefExpr
3397 // ` ...
3398 if (const auto *ME = dyn_cast<MemberExpr>(Arr)) {
3399 Expr *MEBase = ME->getBase();
3400
3401 // Move ctor
3402 if (auto CXXSCE = dyn_cast<CXXStaticCastExpr>(MEBase)) {
3403 MEBase = CXXSCE->getSubExpr();
3404 }
3405
3406 auto ObjDeclExpr = cast<DeclRefExpr>(MEBase);
3407 SVal Obj = state->getLValue(cast<VarDecl>(ObjDeclExpr->getDecl()), LCtx);
3408
3409 Base = state->getLValue(cast<FieldDecl>(ME->getMemberDecl()), Obj);
3410 }
3411
3412 // Case of lambda capture and decomposition declaration
3413 //
3414 // int arr[2];
3415 //
3416 // [arr]{ int a = arr[0]; }();
3417 // auto[a, b] = arr;
3418 //
3419 // In both of these cases the AST looks like the following:
3420 // ArrayInitLoopExpr
3421 // |-OpaqueValueExpr
3422 // | `-DeclRefExpr <-- match this
3423 // ` ...
3424 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arr))
3425 Base = state->getLValue(cast<VarDecl>(DRE->getDecl()), LCtx);
3426
3427 // Create a lazy compound value to the original array
3428 if (const MemRegion *R = Base.getAsRegion())
3429 Base = state->getSVal(R);
3430 else
3431 Base = UnknownVal();
3432
3433 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, Base));
3434 }
3435
3436 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
3437}
3438
3439/// VisitArraySubscriptExpr - Transfer function for array accesses
3441 ExplodedNode *Pred,
3442 ExplodedNodeSet &Dst){
3443 const Expr *Base = A->getBase()->IgnoreParens();
3444 const Expr *Idx = A->getIdx()->IgnoreParens();
3445
3446 ExplodedNodeSet CheckerPreStmt;
3447 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
3448
3449 ExplodedNodeSet EvalSet;
3450 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
3451
3452 bool IsVectorType = A->getBase()->getType()->isVectorType();
3453
3454 // The "like" case is for situations where C standard prohibits the type to
3455 // be an lvalue, e.g. taking the address of a subscript of an expression of
3456 // type "void *".
3457 bool IsGLValueLike = A->isGLValue() ||
3458 (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
3459
3460 for (auto *Node : CheckerPreStmt) {
3461 const LocationContext *LCtx = Node->getLocationContext();
3462 ProgramStateRef state = Node->getState();
3463
3464 if (IsGLValueLike) {
3465 QualType T = A->getType();
3466
3467 // One of the forbidden LValue types! We still need to have sensible
3468 // symbolic locations to represent this stuff. Note that arithmetic on
3469 // void pointers is a GCC extension.
3470 if (T->isVoidType())
3471 T = getContext().CharTy;
3472
3473 SVal V = state->getLValue(T,
3474 state->getSVal(Idx, LCtx),
3475 state->getSVal(Base, LCtx));
3476 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
3478 } else if (IsVectorType) {
3479 // FIXME: non-glvalue vector reads are not modelled.
3480 Bldr.generateNode(A, Node, state, nullptr);
3481 } else {
3482 llvm_unreachable("Array subscript should be an lValue when not \
3483a vector and not a forbidden lvalue type");
3484 }
3485 }
3486
3487 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
3488}
3489
3490/// VisitMemberExpr - Transfer function for member expressions.
3492 ExplodedNodeSet &Dst) {
3493 // FIXME: Prechecks eventually go in ::Visit().
3494 ExplodedNodeSet CheckedSet;
3495 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
3496
3497 ExplodedNodeSet EvalSet;
3499
3500 // Handle static member variables and enum constants accessed via
3501 // member syntax.
3503 for (const auto I : CheckedSet)
3504 VisitCommonDeclRefExpr(M, Member, I, EvalSet);
3505 } else {
3506 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
3507 ExplodedNodeSet Tmp;
3508
3509 for (const auto I : CheckedSet) {
3510 ProgramStateRef state = I->getState();
3511 const LocationContext *LCtx = I->getLocationContext();
3512 Expr *BaseExpr = M->getBase();
3513
3514 // Handle C++ method calls.
3515 if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
3516 if (MD->isImplicitObjectMemberFunction())
3517 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
3518
3519 SVal MDVal = svalBuilder.getFunctionPointer(MD);
3520 state = state->BindExpr(M, LCtx, MDVal);
3521
3522 Bldr.generateNode(M, I, state);
3523 continue;
3524 }
3525
3526 // Handle regular struct fields / member variables.
3527 const SubRegion *MR = nullptr;
3528 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr,
3529 /*Result=*/nullptr,
3530 /*OutRegionWithAdjustments=*/&MR);
3531 SVal baseExprVal =
3532 MR ? loc::MemRegionVal(MR) : state->getSVal(BaseExpr, LCtx);
3533
3534 // FIXME: Copied from RegionStoreManager::bind()
3535 if (const auto *SR =
3536 dyn_cast_or_null<SymbolicRegion>(baseExprVal.getAsRegion())) {
3537 QualType T = SR->getPointeeStaticType();
3538 baseExprVal =
3539 loc::MemRegionVal(getStoreManager().GetElementZeroRegion(SR, T));
3540 }
3541
3542 const auto *field = cast<FieldDecl>(Member);
3543 SVal L = state->getLValue(field, baseExprVal);
3544
3545 if (M->isGLValue() || M->getType()->isArrayType()) {
3546 // We special-case rvalues of array type because the analyzer cannot
3547 // reason about them, since we expect all regions to be wrapped in Locs.
3548 // We instead treat these as lvalues and assume that they will decay to
3549 // pointers as soon as they are used.
3550 if (!M->isGLValue()) {
3551 assert(M->getType()->isArrayType());
3552 const auto *PE =
3553 dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
3554 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
3555 llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
3556 }
3557 }
3558
3559 if (field->getType()->isReferenceType()) {
3560 if (const MemRegion *R = L.getAsRegion())
3561 L = state->getSVal(R);
3562 else
3563 L = UnknownVal();
3564 }
3565
3566 Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr,
3568 } else {
3569 Bldr.takeNodes(I);
3570 evalLoad(Tmp, M, M, I, state, L);
3571 Bldr.addNodes(Tmp);
3572 }
3573 }
3574 }
3575
3576 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
3577}
3578
3580 ExplodedNodeSet &Dst) {
3581 ExplodedNodeSet AfterPreSet;
3582 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
3583
3584 // For now, treat all the arguments to C11 atomics as escaping.
3585 // FIXME: Ideally we should model the behavior of the atomics precisely here.
3586
3587 ExplodedNodeSet AfterInvalidateSet;
3588 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
3589
3590 for (const auto I : AfterPreSet) {
3591 ProgramStateRef State = I->getState();
3592 const LocationContext *LCtx = I->getLocationContext();
3593
3594 SmallVector<SVal, 8> ValuesToInvalidate;
3595 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
3596 const Expr *SubExpr = AE->getSubExprs()[SI];
3597 SVal SubExprVal = State->getSVal(SubExpr, LCtx);
3598 ValuesToInvalidate.push_back(SubExprVal);
3599 }
3600
3601 State = State->invalidateRegions(ValuesToInvalidate, getCFGElementRef(),
3602 currBldrCtx->blockCount(), LCtx,
3603 /*CausedByPointerEscape*/ true,
3604 /*Symbols=*/nullptr);
3605
3606 SVal ResultVal = UnknownVal();
3607 State = State->BindExpr(AE, LCtx, ResultVal);
3608 Bldr.generateNode(AE, I, State, nullptr,
3610 }
3611
3612 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
3613}
3614
3615// A value escapes in four possible cases:
3616// (1) We are binding to something that is not a memory region.
3617// (2) We are binding to a MemRegion that does not have stack storage.
3618// (3) We are binding to a top-level parameter region with a non-trivial
3619// destructor. We won't see the destructor during analysis, but it's there.
3620// (4) We are binding to a MemRegion with stack storage that the store
3621// does not understand.
3623 ProgramStateRef State, ArrayRef<std::pair<SVal, SVal>> LocAndVals,
3624 const LocationContext *LCtx, PointerEscapeKind Kind,
3625 const CallEvent *Call) {
3626 SmallVector<SVal, 8> Escaped;
3627 for (const std::pair<SVal, SVal> &LocAndVal : LocAndVals) {
3628 // Cases (1) and (2).
3629 const MemRegion *MR = LocAndVal.first.getAsRegion();
3630 const MemSpaceRegion *Space = MR ? MR->getMemorySpace(State) : nullptr;
3632 Escaped.push_back(LocAndVal.second);
3633 continue;
3634 }
3635
3636 // Case (3).
3637 if (const auto *VR = dyn_cast<VarRegion>(MR->getBaseRegion()))
3638 if (isa<StackArgumentsSpaceRegion>(Space) &&
3639 VR->getStackFrame()->inTopFrame())
3640 if (const auto *RD = VR->getValueType()->getAsCXXRecordDecl())
3641 if (!RD->hasTrivialDestructor()) {
3642 Escaped.push_back(LocAndVal.second);
3643 continue;
3644 }
3645
3646 // Case (4): in order to test that, generate a new state with the binding
3647 // added. If it is the same state, then it escapes (since the store cannot
3648 // represent the binding).
3649 // Do this only if we know that the store is not supposed to generate the
3650 // same state.
3651 SVal StoredVal = State->getSVal(MR);
3652 if (StoredVal != LocAndVal.second)
3653 if (State ==
3654 (State->bindLoc(loc::MemRegionVal(MR), LocAndVal.second, LCtx)))
3655 Escaped.push_back(LocAndVal.second);
3656 }
3657
3658 if (Escaped.empty())
3659 return State;
3660
3661 return escapeValues(State, Escaped, Kind, Call);
3662}
3663
3666 SVal Val, const LocationContext *LCtx) {
3667 std::pair<SVal, SVal> LocAndVal(Loc, Val);
3668 return processPointerEscapedOnBind(State, LocAndVal, LCtx, PSK_EscapeOnBind,
3669 nullptr);
3670}
3671
3674 const InvalidatedSymbols *Invalidated,
3675 ArrayRef<const MemRegion *> ExplicitRegions,
3676 const CallEvent *Call,
3678 if (!Invalidated || Invalidated->empty())
3679 return State;
3680
3681 if (!Call)
3683 *Invalidated,
3684 nullptr,
3686 &ITraits);
3687
3688 // If the symbols were invalidated by a call, we want to find out which ones
3689 // were invalidated directly due to being arguments to the call.
3690 InvalidatedSymbols SymbolsDirectlyInvalidated;
3691 for (const auto I : ExplicitRegions) {
3692 if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
3693 SymbolsDirectlyInvalidated.insert(R->getSymbol());
3694 }
3695
3696 InvalidatedSymbols SymbolsIndirectlyInvalidated;
3697 for (const auto &sym : *Invalidated) {
3698 if (SymbolsDirectlyInvalidated.count(sym))
3699 continue;
3700 SymbolsIndirectlyInvalidated.insert(sym);
3701 }
3702
3703 if (!SymbolsDirectlyInvalidated.empty())
3705 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
3706
3707 // Notify about the symbols that get indirectly invalidated by the call.
3708 if (!SymbolsIndirectlyInvalidated.empty())
3710 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
3711
3712 return State;
3713}
3714
3715/// evalBind - Handle the semantics of binding a value to a specific location.
3716/// This method is used by evalStore and (soon) VisitDeclStmt, and others.
3717void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
3718 ExplodedNode *Pred, SVal location, SVal Val,
3719 bool AtDeclInit, const ProgramPoint *PP) {
3720 const LocationContext *LC = Pred->getLocationContext();
3721 PostStmt PS(StoreE, LC);
3722 if (!PP)
3723 PP = &PS;
3724
3725 // Do a previsit of the bind.
3726 ExplodedNodeSet CheckedSet;
3727 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
3728 StoreE, AtDeclInit, *this, *PP);
3729
3730 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
3731
3732 // If the location is not a 'Loc', it will already be handled by
3733 // the checkers. There is nothing left to do.
3734 if (!isa<Loc>(location)) {
3735 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
3736 /*tag*/nullptr);
3737 ProgramStateRef state = Pred->getState();
3738 state = processPointerEscapedOnBind(state, location, Val, LC);
3739 Bldr.generateNode(L, state, Pred);
3740 return;
3741 }
3742
3743 for (const auto PredI : CheckedSet) {
3744 ProgramStateRef state = PredI->getState();
3745
3746 state = processPointerEscapedOnBind(state, location, Val, LC);
3747
3748 // When binding the value, pass on the hint that this is a initialization.
3749 // For initializations, we do not need to inform clients of region
3750 // changes.
3751 state = state->bindLoc(location.castAs<Loc>(), Val, LC,
3752 /* notifyChanges = */ !AtDeclInit);
3753
3754 const MemRegion *LocReg = nullptr;
3755 if (std::optional<loc::MemRegionVal> LocRegVal =
3756 location.getAs<loc::MemRegionVal>()) {
3757 LocReg = LocRegVal->getRegion();
3758 }
3759
3760 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
3761 Bldr.generateNode(L, state, PredI);
3762 }
3763}
3764
3765/// evalStore - Handle the semantics of a store via an assignment.
3766/// @param Dst The node set to store generated state nodes
3767/// @param AssignE The assignment expression if the store happens in an
3768/// assignment.
3769/// @param LocationE The location expression that is stored to.
3770/// @param state The current simulation state
3771/// @param location The location to store the value
3772/// @param Val The value to be stored
3774 const Expr *LocationE,
3775 ExplodedNode *Pred,
3776 ProgramStateRef state, SVal location, SVal Val,
3777 const ProgramPointTag *tag) {
3778 // Proceed with the store. We use AssignE as the anchor for the PostStore
3779 // ProgramPoint if it is non-NULL, and LocationE otherwise.
3780 const Expr *StoreE = AssignE ? AssignE : LocationE;
3781
3782 // Evaluate the location (checks for bad dereferences).
3783 ExplodedNodeSet Tmp;
3784 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false);
3785
3786 if (Tmp.empty())
3787 return;
3788
3789 if (location.isUndef())
3790 return;
3791
3792 for (const auto I : Tmp)
3793 evalBind(Dst, StoreE, I, location, Val, false);
3794}
3795
3797 const Expr *NodeEx,
3798 const Expr *BoundEx,
3799 ExplodedNode *Pred,
3800 ProgramStateRef state,
3801 SVal location,
3802 const ProgramPointTag *tag,
3803 QualType LoadTy) {
3804 assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
3805 assert(NodeEx);
3806 assert(BoundEx);
3807 // Evaluate the location (checks for bad dereferences).
3808 ExplodedNodeSet Tmp;
3809 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true);
3810 if (Tmp.empty())
3811 return;
3812
3813 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
3814 if (location.isUndef())
3815 return;
3816
3817 // Proceed with the load.
3818 for (const auto I : Tmp) {
3819 state = I->getState();
3820 const LocationContext *LCtx = I->getLocationContext();
3821
3822 SVal V = UnknownVal();
3823 if (location.isValid()) {
3824 if (LoadTy.isNull())
3825 LoadTy = BoundEx->getType();
3826 V = state->getSVal(location.castAs<Loc>(), LoadTy);
3827 }
3828
3829 Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
3831 }
3832}
3833
3834void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
3835 const Stmt *NodeEx,
3836 const Stmt *BoundEx,
3837 ExplodedNode *Pred,
3838 ProgramStateRef state,
3839 SVal location,
3840 bool isLoad) {
3841 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
3842 // Early checks for performance reason.
3843 if (location.isUnknown()) {
3844 return;
3845 }
3846
3847 ExplodedNodeSet Src;
3848 BldrTop.takeNodes(Pred);
3849 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
3850 if (Pred->getState() != state) {
3851 // Associate this new state with an ExplodedNode.
3852 // FIXME: If I pass null tag, the graph is incorrect, e.g for
3853 // int *p;
3854 // p = 0;
3855 // *p = 0xDEADBEEF;
3856 // "p = 0" is not noted as "Null pointer value stored to 'p'" but
3857 // instead "int *p" is noted as
3858 // "Variable 'p' initialized to a null pointer value"
3859
3860 static SimpleProgramPointTag tag(TagProviderName, "Location");
3861 Bldr.generateNode(NodeEx, Pred, state, &tag);
3862 }
3863 ExplodedNodeSet Tmp;
3864 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
3865 NodeEx, BoundEx, *this);
3866 BldrTop.addNodes(Tmp);
3867}
3868
3869std::pair<const ProgramPointTag *, const ProgramPointTag *>
3871 static SimpleProgramPointTag TrueTag(TagProviderName, "Eagerly Assume True"),
3872 FalseTag(TagProviderName, "Eagerly Assume False");
3873
3874 return std::make_pair(&TrueTag, &FalseTag);
3875}
3876
3877/// If the last EagerlyAssume attempt was successful (i.e. the true and false
3878/// cases were both feasible), this state trait stores the expression where it
3879/// happened; otherwise this holds nullptr.
3880REGISTER_TRAIT_WITH_PROGRAMSTATE(LastEagerlyAssumeExprIfSuccessful,
3881 const Expr *)
3882
3884 ExplodedNodeSet &Src,
3885 const Expr *Ex) {
3886 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
3887
3888 for (ExplodedNode *Pred : Src) {
3889 // Test if the previous node was as the same expression. This can happen
3890 // when the expression fails to evaluate to anything meaningful and
3891 // (as an optimization) we don't generate a node.
3892 ProgramPoint P = Pred->getLocation();
3893 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
3894 continue;
3895 }
3896
3897 ProgramStateRef State = Pred->getState();
3898 State = State->set<LastEagerlyAssumeExprIfSuccessful>(nullptr);
3899 SVal V = State->getSVal(Ex, Pred->getLocationContext());
3900 std::optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
3901 if (SEV && SEV->isExpression()) {
3902 const auto &[TrueTag, FalseTag] = getEagerlyAssumeBifurcationTags();
3903
3904 auto [StateTrue, StateFalse] = State->assume(*SEV);
3905
3906 if (StateTrue && StateFalse) {
3907 StateTrue = StateTrue->set<LastEagerlyAssumeExprIfSuccessful>(Ex);
3908 StateFalse = StateFalse->set<LastEagerlyAssumeExprIfSuccessful>(Ex);
3909 }
3910
3911 // First assume that the condition is true.
3912 if (StateTrue) {
3913 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
3914 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
3915 Bldr.generateNode(Ex, Pred, StateTrue, TrueTag);
3916 }
3917
3918 // Next, assume that the condition is false.
3919 if (StateFalse) {
3920 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
3921 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
3922 Bldr.generateNode(Ex, Pred, StateFalse, FalseTag);
3923 }
3924 }
3925 }
3926}
3927
3929 const Expr *Ex) const {
3930 return Ex && State->get<LastEagerlyAssumeExprIfSuccessful>() == Ex;
3931}
3932
3934 ExplodedNodeSet &Dst) {
3935 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
3936 // We have processed both the inputs and the outputs. All of the outputs
3937 // should evaluate to Locs. Nuke all of their values.
3938
3939 // FIXME: Some day in the future it would be nice to allow a "plug-in"
3940 // which interprets the inline asm and stores proper results in the
3941 // outputs.
3942
3943 ProgramStateRef state = Pred->getState();
3944
3945 for (const Expr *O : A->outputs()) {
3946 SVal X = state->getSVal(O, Pred->getLocationContext());
3947 assert(!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef.
3948
3949 if (std::optional<Loc> LV = X.getAs<Loc>())
3950 state = state->invalidateRegions(*LV, getCFGElementRef(),
3951 currBldrCtx->blockCount(),
3952 Pred->getLocationContext(),
3953 /*CausedByPointerEscape=*/true);
3954 }
3955
3956 // Do not reason about locations passed inside inline assembly.
3957 for (const Expr *I : A->inputs()) {
3958 SVal X = state->getSVal(I, Pred->getLocationContext());
3959
3960 if (std::optional<Loc> LV = X.getAs<Loc>())
3961 state = state->invalidateRegions(*LV, getCFGElementRef(),
3962 currBldrCtx->blockCount(),
3963 Pred->getLocationContext(),
3964 /*CausedByPointerEscape=*/true);
3965 }
3966
3967 Bldr.generateNode(A, Pred, state);
3968}
3969
3971 ExplodedNodeSet &Dst) {
3972 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
3973 Bldr.generateNode(A, Pred, Pred->getState());
3974}
3975
3976//===----------------------------------------------------------------------===//
3977// Visualization.
3978//===----------------------------------------------------------------------===//
3979
3980namespace llvm {
3981
3982template<>
3984 DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3985
3986 static bool nodeHasBugReport(const ExplodedNode *N) {
3987 BugReporter &BR = static_cast<ExprEngine &>(
3988 N->getState()->getStateManager().getOwningEngine()).getBugReporter();
3989
3990 for (const auto &Class : BR.equivalenceClasses()) {
3991 for (const auto &Report : Class.getReports()) {
3992 const auto *PR = dyn_cast<PathSensitiveBugReport>(Report.get());
3993 if (!PR)
3994 continue;
3995 const ExplodedNode *EN = PR->getErrorNode();
3996 if (EN->getState() == N->getState() &&
3997 EN->getLocation() == N->getLocation())
3998 return true;
3999 }
4000 }
4001 return false;
4002 }
4003
4004 /// \p PreCallback: callback before break.
4005 /// \p PostCallback: callback after break.
4006 /// \p Stop: stop iteration if returns @c true
4007 /// \return Whether @c Stop ever returned @c true.
4009 const ExplodedNode *N,
4010 llvm::function_ref<void(const ExplodedNode *)> PreCallback,
4011 llvm::function_ref<void(const ExplodedNode *)> PostCallback,
4012 llvm::function_ref<bool(const ExplodedNode *)> Stop) {
4013 while (true) {
4014 PreCallback(N);
4015 if (Stop(N))
4016 return true;
4017
4018 if (N->succ_size() != 1 || !isNodeHidden(N->getFirstSucc(), nullptr))
4019 break;
4020 PostCallback(N);
4021
4022 N = N->getFirstSucc();
4023 }
4024 return false;
4025 }
4026
4027 static bool isNodeHidden(const ExplodedNode *N, const ExplodedGraph *G) {
4028 return N->isTrivial();
4029 }
4030
4031 static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){
4032 std::string Buf;
4033 llvm::raw_string_ostream Out(Buf);
4034
4035 const bool IsDot = true;
4036 const unsigned int Space = 1;
4037 ProgramStateRef State = N->getState();
4038
4039 Out << "{ \"state_id\": " << State->getID()
4040 << ",\\l";
4041
4042 Indent(Out, Space, IsDot) << "\"program_points\": [\\l";
4043
4044 // Dump program point for all the previously skipped nodes.
4046 N,
4047 [&](const ExplodedNode *OtherNode) {
4048 Indent(Out, Space + 1, IsDot) << "{ ";
4049 OtherNode->getLocation().printJson(Out, /*NL=*/"\\l");
4050 Out << ", \"tag\": ";
4051 if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag())
4052 Out << '\"' << Tag->getDebugTag() << '\"';
4053 else
4054 Out << "null";
4055 Out << ", \"node_id\": " << OtherNode->getID() <<
4056 ", \"is_sink\": " << OtherNode->isSink() <<
4057 ", \"has_report\": " << nodeHasBugReport(OtherNode) << " }";
4058 },
4059 // Adds a comma and a new-line between each program point.
4060 [&](const ExplodedNode *) { Out << ",\\l"; },
4061 [&](const ExplodedNode *) { return false; });
4062
4063 Out << "\\l"; // Adds a new-line to the last program point.
4064 Indent(Out, Space, IsDot) << "],\\l";
4065
4066 State->printDOT(Out, N->getLocationContext(), Space);
4067
4068 Out << "\\l}\\l";
4069 return Buf;
4070 }
4071};
4072
4073} // namespace llvm
4074
4075void ExprEngine::ViewGraph(bool trim) {
4076 std::string Filename = DumpGraph(trim);
4077 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
4078}
4079
4081 std::string Filename = DumpGraph(Nodes);
4082 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
4083}
4084
4085std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) {
4086 if (trim) {
4087 std::vector<const ExplodedNode *> Src;
4088
4089 // Iterate through the reports and get their nodes.
4090 for (const auto &Class : BR.equivalenceClasses()) {
4091 const auto *R =
4092 dyn_cast<PathSensitiveBugReport>(Class.getReports()[0].get());
4093 if (!R)
4094 continue;
4095 const auto *N = const_cast<ExplodedNode *>(R->getErrorNode());
4096 Src.push_back(N);
4097 }
4098 return DumpGraph(Src, Filename);
4099 }
4100
4101 return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false,
4102 /*Title=*/"Exploded Graph",
4103 /*Filename=*/std::string(Filename));
4104}
4105
4107 StringRef Filename) {
4108 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
4109
4110 if (!TrimmedG) {
4111 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
4112 return "";
4113 }
4114
4115 return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine",
4116 /*ShortNames=*/false,
4117 /*Title=*/"Trimmed Exploded Graph",
4118 /*Filename=*/std::string(Filename));
4119}
4120
4122 static int index = 0;
4123 return &index;
4124}
4125
4126void ExprEngine::anchor() { }
4127
4129 bool IsTransparent, ExplodedNode *Pred,
4130 ExplodedNodeSet &Dst) {
4132
4133 const LocationContext *LC = Pred->getLocationContext();
4134
4135 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
4136 ProgramStateRef S = Pred->getState();
4138
4139 bool IsCompound = T->isArrayType() || T->isRecordType() ||
4140 T->isAnyComplexType() || T->isVectorType();
4141
4142 if (Args.size() > 1 || (E->isPRValue() && IsCompound && !IsTransparent)) {
4143 llvm::ImmutableList<SVal> ArgList = getBasicVals().getEmptySValList();
4144 for (Expr *E : llvm::reverse(Args))
4145 ArgList = getBasicVals().prependSVal(S->getSVal(E, LC), ArgList);
4146
4147 B.generateNode(E, Pred,
4148 S->BindExpr(E, LC, svalBuilder.makeCompoundVal(T, ArgList)));
4149 } else {
4150 B.generateNode(E, Pred,
4151 S->BindExpr(E, LC,
4152 Args.size() == 0
4153 ? getSValBuilder().makeZeroVal(T)
4154 : S->getSVal(Args.front(), LC)));
4155 }
4156}
Defines the clang::ASTContext interface.
#define V(N, I)
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
#define STAT_COUNTER(VARNAME, DESC)
Defines the clang::Expr interface and subclasses for C++ expressions.
static const Stmt * getRightmostLeaf(const Stmt *Condition)
static SVal RecoverCastedSymbol(ProgramStateRef state, const Stmt *Condition, const LocationContext *LCtx, ASTContext &Ctx)
RecoverCastedSymbol - A helper function for ProcessBranch that is used to try to recover some path-se...
static void printObjectsUnderConstructionJson(raw_ostream &Out, ProgramStateRef State, const char *NL, const LocationContext *LCtx, unsigned int Space=0, bool IsDot=false)
static void printIndicesOfElementsToConstructJson(raw_ostream &Out, ProgramStateRef State, const char *NL, const LocationContext *LCtx, unsigned int Space=0, bool IsDot=false)
static void printStateTraitWithLocationContextJson(raw_ostream &Out, ProgramStateRef State, const LocationContext *LCtx, const char *NL, unsigned int Space, bool IsDot, const char *jsonPropertyName, Printer printer, Args &&...args)
A helper function to generalize program state trait printing.
static void printPendingArrayDestructionsJson(raw_ostream &Out, ProgramStateRef State, const char *NL, const LocationContext *LCtx, unsigned int Space=0, bool IsDot=false)
static bool shouldRemoveDeadBindings(AnalysisManager &AMgr, const Stmt *S, const ExplodedNode *Pred, const LocationContext *LC)
static const Stmt * ResolveCondition(const Stmt *Condition, const CFGBlock *B)
REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction, ObjectsUnderConstructionMap) typedef llvm REGISTER_TRAIT_WITH_PROGRAMSTATE(IndexOfElementToConstruct, IndexOfElementToConstructMap) typedef llvm typedef llvm::ImmutableMap< const LocationContext *, unsigned > PendingArrayDestructionMap
static void printPendingInitLoopJson(raw_ostream &Out, ProgramStateRef State, const char *NL, const LocationContext *LCtx, unsigned int Space=0, bool IsDot=false)
llvm::ImmutableMap< ConstructedObjectKey, SVal > ObjectsUnderConstructionMap
static const LocationContext * getInlinedLocationContext(ExplodedNode *Node, ExplodedGraph &G)
Return the innermost location context which is inlined at Node, unless it's the top-level (entry poin...
static std::optional< std::pair< ProgramStateRef, ProgramStateRef > > assumeCondition(const Stmt *Condition, ExplodedNode *N)
Split the state on whether there are any more iterations left for this loop.
std::pair< const ObjCForCollectionStmt *, const LocationContext * > ObjCForLctxPair
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
This header contains the declarations of functions which are used to decide which loops should be com...
This header contains the declarations of functions which are used to widen loops which do not otherwi...
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
#define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)
Declares a program state trait for type Type called Name, and introduce a type named NameTy.
static bool isRecordType(QualType T)
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
Defines the Objective-C statement AST node classes.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType CharTy
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:825
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
ASTContext & getASTContext() const
Stores options for the analyzer from the command line.
AnalysisPurgeMode AnalysisPurgeOpt
Represents a loop initializing the elements of an array.
Definition Expr.h:5902
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5917
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5922
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
outputs_range outputs()
Definition Stmt.h:3369
inputs_range inputs()
Definition Stmt.h:3340
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6814
Expr ** getSubExprs()
Definition Expr.h:6889
static unsigned getNumSubExprs(AtomicOp Op)
Determine the number of arguments the specified atomic builtin should have.
Definition Expr.cpp:5153
const CFGBlock * getPreviousBlock() const
const CFGBlock * getBlock() const
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Definition CFG.h:418
const VarDecl * getVarDecl() const
Definition CFG.h:423
const Stmt * getTriggerStmt() const
Definition CFG.h:428
Represents C++ object destructor implicitly generated for base object in destructor.
Definition CFG.h:469
const CXXBaseSpecifier * getBaseSpecifier() const
Definition CFG.h:474
Represents a single basic block in a source-level CFG.
Definition CFG.h:605
ref_iterator ref_begin()
Definition CFG.h:935
CFGTerminator getTerminator() const
Definition CFG.h:1085
Stmt * getTerminatorStmt()
Definition CFG.h:1087
unsigned getBlockID() const
Definition CFG.h:1111
Represents C++ object destructor generated from a call to delete.
Definition CFG.h:443
const CXXDeleteExpr * getDeleteExpr() const
Definition CFG.h:453
Represents a top-level expression in a basic block.
Definition CFG.h:55
@ CleanupFunction
Definition CFG.h:79
@ CXXRecordTypedCall
Definition CFG.h:68
@ AutomaticObjectDtor
Definition CFG.h:72
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type.
Definition CFG.h:99
Kind getKind() const
Definition CFG.h:118
Represents C++ object destructor implicitly generated by compiler on various occasions.
Definition CFG.h:367
const CXXDestructorDecl * getDestructorDecl(ASTContext &astContext) const
Definition CFG.cpp:5398
Represents C++ base or member initializer from constructor's initialization list.
Definition CFG.h:228
CXXCtorInitializer * getInitializer() const
Definition CFG.h:233
Represents the point where a loop ends.
Definition CFG.h:274
const Stmt * getLoopStmt() const
Definition CFG.h:278
Represents C++ object destructor implicitly generated for member object in destructor.
Definition CFG.h:490
const FieldDecl * getFieldDecl() const
Definition CFG.h:495
Represents C++ allocator call.
Definition CFG.h:248
const CXXNewExpr * getAllocatorExpr() const
Definition CFG.h:254
const Stmt * getStmt() const
Definition CFG.h:139
Represents C++ object destructor implicitly generated at the end of full expression for temporary obj...
Definition CFG.h:511
const CXXBindTemporaryExpr * getBindTemporaryExpr() const
Definition CFG.h:516
bool isStmtBranch() const
Definition CFG.h:568
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1494
const Expr * getSubExpr() const
Definition ExprCXX.h:1516
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:1520
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
Represents a C++ base or member initializer.
Definition DeclCXX.h:2369
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition DeclCXX.h:2509
bool isDelegatingInitializer() const
Determine whether this initializer is creating a delegating constructor.
Definition DeclCXX.h:2469
Expr * getInit() const
Get the initializer.
Definition DeclCXX.h:2571
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition DeclCXX.cpp:2903
bool isAnyMemberInitializer() const
Definition DeclCXX.h:2449
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition DeclCXX.h:2441
bool isIndirectMemberInitializer() const
Definition DeclCXX.h:2453
int64_t getID(const ASTContext &Context) const
Definition DeclCXX.cpp:2884
const Type * getBaseClass() const
If this is a base class initializer, returns the type of the base class.
Definition DeclCXX.cpp:2896
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2515
IndirectFieldDecl * getIndirectMember() const
Definition DeclCXX.h:2523
bool isBaseVirtual() const
Returns whether the base is virtual or not.
Definition DeclCXX.h:2495
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2628
bool isArrayForm() const
Definition ExprCXX.h:2654
SourceLocation getBeginLoc() const
Definition ExprCXX.h:2678
QualType getDestroyedType() const
Retrieve the type being destroyed.
Definition ExprCXX.cpp:338
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2357
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5143
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5183
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1784
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2121
Represents a point when we begin processing an inlined call.
CaseStmt - Represent a case statement.
Definition Stmt.h:1920
Expr * getLHS()
Definition Stmt.h:2003
Expr * getRHS()
Definition Stmt.h:2015
Represents a single point (AST node) in the program that requires attention during construction of an...
unsigned getIndex() const
If a single trigger statement triggers multiple constructors, they are usually being enumerated.
const CXXCtorInitializer * getCXXCtorInitializer() const
The construction site is not necessarily a statement.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1611
const Decl * getSingleDecl() const
Definition Stmt.h:1626
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This is a meta program point, which should be skipped by all the diagnostic reasoning etc.
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:80
bool isGLValue() const
Definition Expr.h:287
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3073
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
bool isPRValue() const
Definition Expr.h:285
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3160
This represents a GCC inline-assembly statement extension.
Definition Stmt.h:3395
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
Describes an C or C++ initializer list.
Definition Expr.h:5233
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2457
ArrayRef< Expr * > inits()
Definition Expr.h:5283
Represents the declaration of a label.
Definition Decl.h:524
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
const Decl * getDecl() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
const LocationContext * getParent() const
It might return null.
const StackFrameContext * getStackFrame() const
virtual bool inTopFrame() const
void printJson(raw_ostream &Out, const char *NL="\n", unsigned int Space=0, bool IsDot=false, std::function< void(const LocationContext *)> printMoreInfoPerContext=[](const LocationContext *) {}) const
Prints out the call stack in json format.
Represents a point when we exit a loop.
This represents a Microsoft inline-assembly statement extension.
Definition Stmt.h:3614
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
This represents a decl that may have a name.
Definition Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Represents Objective-C's collection statement.
Definition StmtObjC.h:23
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1228
bool isConsumedExpr(Expr *E) const
Represents a parameter to a function.
Definition Decl.h:1790
Represents a program point just after an implicit call event.
Represents a program point after a store evaluation.
Represents a program point just before an implicit call event.
If a crash happens while one of these objects are live, the message is printed out along with the spe...
ProgramPoints can be "tagged" as representing points specific to a given analysis entity.
const ProgramPointTag * getTag() const
bool isPurgeKind()
Is this a program point corresponding to purge/removal of dead symbols and bindings.
T castAs() const
Convert to the specified ProgramPoint type, asserting that this ProgramPoint is of the desired type.
void printJson(llvm::raw_ostream &Out, const char *NL="\n") const
const StackFrameContext * getStackFrame() const
std::optional< T > getAs() const
Convert to the specified ProgramPoint type, returning std::nullopt if this ProgramPoint is not of the...
const LocationContext * getLocationContext() const
A (possibly-)qualified type.
Definition TypeBase.h:937
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1296
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:8339
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8308
std::string getAsString() const
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3160
std::string printToString(const SourceManager &SM) const
It represents a stack frame of the call stack (based on CallEvent).
const Stmt * getCallSite() const
const CFGBlock * getCallSiteBlock() const
bool inTopFrame() const override
const Stmt * getStmt() const
Stmt - This represents one statement.
Definition Stmt.h:85
@ NoStmtClass
Definition Stmt.h:88
void printJson(raw_ostream &Out, PrinterHelper *Helper, const PrintingPolicy &Policy, bool AddQuotes) const
Pretty-prints in JSON format.
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
const char * getStmtClassName() const
Definition Stmt.cpp:87
int64_t getID(const ASTContext &Context) const
Definition Stmt.cpp:370
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2509
bool isAllEnumCasesCovered() const
Returns true if the SwitchStmt is a switch of an enum value and all cases have been explicitly covere...
Definition Stmt.h:2669
Expr * getCond()
Definition Stmt.h:2572
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8623
bool isReferenceType() const
Definition TypeBase.h:8548
bool isEnumeralType() const
Definition TypeBase.h:8655
bool isVectorType() const
Definition TypeBase.h:8663
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
This class is used for tools that requires cross translation unit capability.
llvm::ImmutableList< SVal > getEmptySValList()
llvm::ImmutableList< SVal > prependSVal(SVal X, llvm::ImmutableList< SVal > L)
BranchNodeBuilder is responsible for constructing the nodes corresponding to the two branches of the ...
Definition CoreEngine.h:436
ExplodedNode * generateNode(ProgramStateRef State, bool branch, ExplodedNode *Pred)
BugReporter is a utility class for generating PathDiagnostics for analysis.
llvm::iterator_range< EQClasses_iterator > equivalenceClasses()
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:153
static bool isCallStmt(const Stmt *S)
Returns true if this is a statement is a function or method call of some kind.
void runCheckersForEndFunction(NodeBuilderContext &BC, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng, const ReturnStmt *RS)
Run checkers on end of function.
void runCheckersForLocation(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, bool isLoad, const Stmt *NodeEx, const Stmt *BoundEx, ExprEngine &Eng)
Run checkers for load/store of a location.
void runCheckersForBind(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, SVal val, const Stmt *S, bool AtDeclInit, ExprEngine &Eng, const ProgramPoint &PP)
Run checkers for binding of a value to a location.
void runCheckersForEndAnalysis(ExplodedGraph &G, BugReporter &BR, ExprEngine &Eng)
Run checkers for end of analysis.
void runCheckersForPrintStateJson(raw_ostream &Out, ProgramStateRef State, const char *NL="\n", unsigned int Space=0, bool IsDot=false) const
Run checkers for debug-printing a ProgramState.
void runCheckersForDeadSymbols(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SymbolReaper &SymReaper, const Stmt *S, ExprEngine &Eng, ProgramPoint::Kind K)
Run checkers for dead symbols.
ProgramStateRef runCheckersForRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef< const MemRegion * > ExplicitRegions, ArrayRef< const MemRegion * > Regions, const LocationContext *LCtx, const CallEvent *Call)
Run checkers for region changes.
void runCheckersForLiveSymbols(ProgramStateRef state, SymbolReaper &SymReaper)
Run checkers for live symbols.
void runCheckersForBeginFunction(ExplodedNodeSet &Dst, const BlockEdge &L, ExplodedNode *Pred, ExprEngine &Eng)
Run checkers on beginning of function.
void runCheckersForPostStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting Stmts.
void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng)
Run checkers for pre-visiting Stmts.
void runCheckersForBlockEntrance(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const BlockEntrance &Entrance, ExprEngine &Eng) const
Run checkers after taking a control flow edge.
void runCheckersForBranchCondition(const Stmt *condition, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng)
Run checkers for branch condition.
ProgramStateRef runCheckersForPointerEscape(ProgramStateRef State, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ITraits)
Run checkers when pointers escape.
ProgramStateRef runCheckersForEvalAssume(ProgramStateRef state, SVal Cond, bool Assumption)
Run checkers for handling assumptions on symbolic values.
virtual ProgramStateRef removeDeadBindings(ProgramStateRef state, SymbolReaper &SymReaper)=0
Scan all symbols referenced by the constraints.
void enqueueStmtNode(ExplodedNode *N, const CFGBlock *Block, unsigned Idx)
Enqueue a single node created as a result of statement processing.
ExplodedNode * getNode(const ProgramPoint &L, ProgramStateRef State, bool IsSink=false, bool *IsNew=nullptr)
Retrieve the node associated with a (Location, State) pair, where the 'Location' is a ProgramPoint in...
ExplodedNode * getRoot() const
Get the root node of the graph.
void insert(const ExplodedNodeSet &S)
void Add(ExplodedNode *N)
const ProgramStateRef & getState() const
bool isTrivial() const
The node is trivial if it has only one successor, only one predecessor, it's predecessor has only one...
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
void addPredecessor(ExplodedNode *V, ExplodedGraph &G)
addPredeccessor - Adds a predecessor to the current node, and in tandem add this node as a successor ...
ExplodedNode * getFirstSucc()
const StackFrameContext * getStackFrame() const
const LocationContext * getLocationContext() const
unsigned succ_size() const
void processEndOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred, const ReturnStmt *RS=nullptr)
Called by CoreEngine.
void VisitBinaryOperator(const BinaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitBinaryOperator - Transfer function logic for binary operators.
ProgramStateManager & getStateManager()
Definition ExprEngine.h:421
void VisitArraySubscriptExpr(const ArraySubscriptExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitArraySubscriptExpr - Transfer function for array accesses.
void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred)
void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void ProcessTemporaryDtor(const CFGTemporaryDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitGuardedExpr - Transfer function logic for ?, __builtin_choose.
void processBeginOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred, ExplodedNodeSet &Dst, const BlockEdge &L)
Called by CoreEngine.
void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCast - Transfer function logic for all casts (implicit and explicit).
void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out, const Stmt *ReferenceStmt, const LocationContext *LC, const Stmt *DiagnosticStmt=nullptr, ProgramPoint::Kind K=ProgramPoint::PreStmtPurgeDeadSymbolsKind)
Run the analyzer's garbage collection - remove dead symbols and bindings from the state.
BasicValueFactory & getBasicVals()
Definition ExprEngine.h:437
void VisitLogicalExpr(const BinaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLogicalExpr - Transfer function logic for '&&', '||'.
void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, const Stmt *S, bool IsBaseDtor, ExplodedNode *Pred, ExplodedNodeSet &Dst, EvalCallOptions &Options)
void evalEagerlyAssumeBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, const Expr *Ex)
evalEagerlyAssumeBifurcation - Given the nodes in 'Src', eagerly assume concrete boolean values for '...
void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for ObjCAtSynchronizedStmts.
void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitReturnStmt - Transfer function logic for return statements.
SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, SVal LHS, SVal RHS, QualType T)
Definition ExprEngine.h:626
void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
ProgramStateRef processRegionChange(ProgramStateRef state, const MemRegion *MR, const LocationContext *LCtx)
Definition ExprEngine.h:410
void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLambdaExpr - Transfer function logic for LambdaExprs.
void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred)
void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitObjCForCollectionStmt - Transfer function logic for ObjCForCollectionStmt.
void VisitUnaryOperator(const UnaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitUnaryOperator - Transfer function logic for unary operators.
ProgramStateRef getInitialState(const LocationContext *InitLoc)
getInitialState - Return the initial state used for the root vertex in the ExplodedGraph.
void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for computing the lvalue of an Objective-C ivar.
static bool hasMoreIteration(ProgramStateRef State, const ObjCForCollectionStmt *O, const LocationContext *LC)
void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitDeclStmt - Transfer function logic for DeclStmts.
void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitMSAsmStmt - Transfer function logic for MS inline asm.
static std::optional< SVal > getObjectUnderConstruction(ProgramStateRef State, const ConstructionContextItem &Item, const LocationContext *LC)
By looking at a certain item that may be potentially part of an object's ConstructionContext,...
std::string DumpGraph(bool trim=false, StringRef Filename="")
Dump graph to the specified filename.
void printJson(raw_ostream &Out, ProgramStateRef State, const LocationContext *LCtx, const char *NL, unsigned int Space, bool IsDot) const
printJson - Called by ProgramStateManager to print checker-specific data.
InliningModes
The modes of inlining, which override the default analysis-wide settings.
Definition ExprEngine.h:129
ProgramStateRef processPointerEscapedOnBind(ProgramStateRef State, ArrayRef< std::pair< SVal, SVal > > LocAndVals, const LocationContext *LCtx, PointerEscapeKind Kind, const CallEvent *Call)
Call PointerEscape callback when a value escapes as a result of bind.
const LocationContext * getRootLocationContext() const
Definition ExprEngine.h:227
static ProgramStateRef removeIterationState(ProgramStateRef State, const ObjCForCollectionStmt *O, const LocationContext *LC)
ProgramStateRef processAssume(ProgramStateRef state, SVal cond, bool assumption)
evalAssume - Callback function invoked by the ConstraintManager when making assumptions about state v...
AnalysisDeclContextManager & getAnalysisDeclContextManager()
Definition ExprEngine.h:201
static std::optional< unsigned > getIndexOfElementToConstruct(ProgramStateRef State, const CXXConstructExpr *E, const LocationContext *LCtx)
Retreives which element is being constructed in a non-POD type array.
void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitBlockExpr - Transfer function logic for BlockExprs.
void ProcessBaseDtor(const CFGBaseDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
static std::pair< const ProgramPointTag *, const ProgramPointTag * > getEagerlyAssumeBifurcationTags()
void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCall - Transfer function for function calls.
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition ExprEngine.h:196
StoreManager & getStoreManager()
Definition ExprEngine.h:424
void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Create a C++ temporary object for an rvalue.
void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitGCCAsmStmt - Transfer function logic for inline asm.
BugReporter & getBugReporter()
Definition ExprEngine.h:212
void processCFGBlockEntrance(const BlockEdge &L, NodeBuilderWithSinks &nodeBuilder, ExplodedNode *Pred)
Called by CoreEngine when processing the entrance of a CFGBlock.
ProgramStateRef processRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef< const MemRegion * > ExplicitRegions, ArrayRef< const MemRegion * > Regions, const LocationContext *LCtx, const CallEvent *Call)
processRegionChanges - Called by ProgramStateManager whenever a change is made to the store.
void ProcessStmt(const Stmt *S, ExplodedNode *Pred)
ConstCFGElementRef getCFGElementRef() const
Definition ExprEngine.h:232
ExprEngine(cross_tu::CrossTranslationUnitContext &CTU, AnalysisManager &mgr, SetOfConstDecls *VisitedCalleesIn, FunctionSummariesTy *FS, InliningModes HowToInlineIn)
void ViewGraph(bool trim=false)
Visualize the ExplodedGraph created by executing the simulation.
static std::optional< unsigned > getPendingArrayDestruction(ProgramStateRef State, const LocationContext *LCtx)
Retreives which element is being destructed in a non-POD type array.
ProgramStateRef notifyCheckersOfPointerEscape(ProgramStateRef State, const InvalidatedSymbols *Invalidated, ArrayRef< const MemRegion * > ExplicitRegions, const CallEvent *Call, RegionAndSymbolInvalidationTraits &ITraits)
Call PointerEscape callback when a value escapes as a result of region invalidation.
static const ProgramPointTag * cleanupNodeTag()
A tag to track convenience transitions, which can be removed at cleanup.
void processCFGElement(const CFGElement E, ExplodedNode *Pred, unsigned StmtIdx, NodeBuilderContext *Ctx)
processCFGElement - Called by CoreEngine.
void processStaticInitializer(const DeclStmt *DS, NodeBuilderContext &BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF)
Called by CoreEngine.
void ConstructInitList(const Expr *Source, ArrayRef< Expr * > Args, bool IsTransparent, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
ProgramStateRef escapeValues(ProgramStateRef State, ArrayRef< SVal > Vs, PointerEscapeKind K, const CallEvent *Call=nullptr) const
A simple wrapper when you only need to notify checkers of pointer-escape of some values.
void processBranch(const Stmt *Condition, NodeBuilderContext &BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF, std::optional< unsigned > IterationsCompletedInLoop)
ProcessBranch - Called by CoreEngine.
void ProcessLoopExit(const Stmt *S, ExplodedNode *Pred)
void processSwitch(SwitchNodeBuilder &builder)
ProcessSwitch - Called by CoreEngine.
void processEndWorklist()
Called by CoreEngine when the analysis worklist has terminated.
CheckerManager & getCheckerManager() const
Definition ExprEngine.h:205
SymbolManager & getSymbolManager()
Definition ExprEngine.h:441
void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitAtomicExpr - Transfer function for builtin atomic expressions.
MemRegionManager & getRegionManager()
Definition ExprEngine.h:443
void ProcessMemberDtor(const CFGMemberDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitMemberExpr - Transfer function for member expressions.
void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
bool didEagerlyAssumeBifurcateAt(ProgramStateRef State, const Expr *Ex) const
ConstraintManager & getConstraintManager()
Definition ExprEngine.h:429
void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, NodeBuilderContext &BldCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF)
Called by CoreEngine.
void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitOffsetOfExpr - Transfer function for offsetof.
void evalLoad(ExplodedNodeSet &Dst, const Expr *NodeEx, const Expr *BoundExpr, ExplodedNode *Pred, ProgramStateRef St, SVal location, const ProgramPointTag *tag=nullptr, QualType LoadTy=QualType())
Simulate a read of the result of Ex.
void removeDeadOnEndOfFunction(NodeBuilderContext &BC, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Remove dead bindings/symbols before exiting a function.
void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Visit - Transfer function logic for all statements.
AnalysisManager & getAnalysisManager()
Definition ExprEngine.h:198
ExplodedGraph & getGraph()
Definition ExprEngine.h:259
void runCheckersForBlockEntrance(const NodeBuilderContext &BldCtx, const BlockEntrance &Entrance, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void ProcessDeleteDtor(const CFGDeleteDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCompoundLiteralExpr - Transfer function logic for compound literals.
SValBuilder & getSValBuilder()
Definition ExprEngine.h:209
void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitArrayInitLoopExpr - Transfer function for array init loop.
void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE, ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val, const ProgramPointTag *tag=nullptr)
evalStore - Handle the semantics of a store via an assignment.
void VisitAttributedStmt(const AttributedStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitAttributedStmt - Transfer function logic for AttributedStmt.
void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, ExplodedNodeSet &PreVisit, ExplodedNodeSet &Dst)
void processIndirectGoto(IndirectGotoNodeBuilder &builder)
processIndirectGoto - Called by CoreEngine.
const NodeBuilderContext & getBuilderContext()
Definition ExprEngine.h:220
static ProgramStateRef setWhetherHasMoreIteration(ProgramStateRef State, const ObjCForCollectionStmt *O, const LocationContext *LC, bool HasMoreIteraton)
Note whether this loop has any more iterations to model. These methods.
static std::optional< unsigned > getPendingInitLoop(ProgramStateRef State, const CXXConstructExpr *E, const LocationContext *LCtx)
Retreives the size of the array in the pending ArrayInitLoopExpr.
void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred)
const LocationContext * getLocationContext() const
Definition CoreEngine.h:511
ProgramStateRef getState() const
Definition CoreEngine.h:509
ExplodedNode * generateNode(const iterator &I, ProgramStateRef State, bool isSink=false)
static bool isLocType(QualType T)
Definition SVals.h:262
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:98
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemSpaceRegion * getMemorySpace(ProgramStateRef State) const
Returns the most specific memory space for this memory region in the given ProgramStateRef.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
MemSpaceRegion - A memory region that represents a "memory space"; for example, the set of global var...
Definition MemRegion.h:236
const CFGBlock * getBlock() const
Return the CFGBlock associated with this builder.
Definition CoreEngine.h:217
unsigned blockCount() const
Returns the number of times the current basic block has been visited on the exploded graph path.
Definition CoreEngine.h:224
This node builder keeps track of the generated sink nodes.
Definition CoreEngine.h:347
ExplodedNode * generateNode(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag=nullptr)
Definition CoreEngine.h:359
ExplodedNode * generateSink(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag=nullptr)
Definition CoreEngine.h:366
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition CoreEngine.h:240
ExplodedNode * generateNode(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a node in the ExplodedGraph.
Definition CoreEngine.h:293
void takeNodes(const ExplodedNodeSet &S)
Definition CoreEngine.h:335
ExplodedNode * generateSink(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a sink in the ExplodedGraph.
Definition CoreEngine.h:306
void addNodes(const ExplodedNodeSet &S)
Definition CoreEngine.h:341
const NodeBuilderContext & getContext()
Definition CoreEngine.h:332
While alive, includes the current analysis stack in a crash trace.
Information about invalidation for a particular region/symbol.
Definition MemRegion.h:1657
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrameContext *SFC)
Return a memory region for the 'this' object reference.
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, ConstCFGElementRef elem, const LocationContext *LCtx, unsigned count)
Create a new symbol with a unique 'name'.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:56
bool isUndef() const
Definition SVals.h:107
bool isUnknownOrUndef() const
Definition SVals.h:109
bool isConstant() const
Definition SVals.cpp:245
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition SVals.h:87
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
bool isValid() const
Definition SVals.h:111
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:83
bool isUnknown() const
Definition SVals.h:105
This builder class is useful for generating nodes that resulted from visiting a statement.
Definition CoreEngine.h:384
ExplodedNode * generateNode(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition CoreEngine.h:413
ExplodedNode * generateSink(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition CoreEngine.h:423
SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast)
Evaluates a chain of derived-to-base casts through the path specified in Cast.
Definition Store.cpp:254
virtual SVal getLValueField(const FieldDecl *D, SVal Base)
Definition Store.h:154
SubRegion - A region that subsets another larger region.
Definition MemRegion.h:474
ProgramStateRef getState() const
Definition CoreEngine.h:563
const Expr * getCondition() const
Definition CoreEngine.h:561
ExplodedNode * generateDefaultCaseNode(ProgramStateRef State, bool isSink=false)
ExplodedNode * generateCaseStmtNode(const iterator &I, ProgramStateRef State)
const LocationContext * getLocationContext() const
Definition CoreEngine.h:565
const SwitchStmt * getSwitch() const
Definition CoreEngine.h:551
A class responsible for cleaning up unused symbols.
void markLive(SymbolRef sym)
Unconditionally marks a symbol as live.
SymbolicRegion - A special, "non-concrete" region.
Definition MemRegion.h:808
Represents symbolic expression that isn't a location.
Definition SVals.h:279
#define bool
Definition gpuintrin.h:32
Definition ARM.cpp:1134
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
@ PSK_DirectEscapeOnCall
The pointer has been passed to a function call directly.
@ PSK_EscapeOnBind
A pointer escapes due to binding its value to a location that the analyzer cannot track.
@ PSK_IndirectEscapeOnCall
The pointer has been passed to a function indirectly.
@ PSK_EscapeOther
The reason for pointer escape is unknown.
DefinedOrUnknownSVal getDynamicElementCount(ProgramStateRef State, const MemRegion *MR, SValBuilder &SVB, QualType Ty)
llvm::DenseSet< const Decl * > SetOfConstDecls
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition Store.h:51
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:133
ProgramStateRef processLoopEnd(const Stmt *LoopStmt, ProgramStateRef State)
Updates the given ProgramState.
bool isUnrolledState(ProgramStateRef State)
Returns if the given State indicates that is inside a completely unrolled loop.
ProgramStateRef getWidenedLoopState(ProgramStateRef PrevState, const LocationContext *LCtx, unsigned BlockCount, ConstCFGElementRef Elem)
Get the states that result from widening the loop.
ProgramStateRef updateLoopStack(const Stmt *LoopStmt, ASTContext &ASTCtx, ExplodedNode *Pred, unsigned maxVisitOnPath)
Updates the stack of loops contained by the ProgramState.
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1274
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:204
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition Specifiers.h:339
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:342
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:340
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5876
Expr * extractElementInitializerFromNestedAILE(const ArrayInitLoopExpr *AILE)
Definition CFG.cpp:1448
@ CXXThis
Parameter for C++ 'this' argument.
Definition Decl.h:1734
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
Describes how types, statements, expressions, and declarations should be printed.
Hints for figuring out of a call should be inlined during evalCall().
Definition ExprEngine.h:97
bool IsTemporaryCtorOrDtor
This call is a constructor or a destructor of a temporary value.
Definition ExprEngine.h:107
bool IsArrayCtorOrDtor
This call is a constructor or a destructor for a single element within an array, a part of array cons...
Definition ExprEngine.h:104
Traits for storing the call processing policy inside GDM.
static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G)
static bool nodeHasBugReport(const ExplodedNode *N)
static bool traverseHiddenNodes(const ExplodedNode *N, llvm::function_ref< void(const ExplodedNode *)> PreCallback, llvm::function_ref< void(const ExplodedNode *)> PostCallback, llvm::function_ref< bool(const ExplodedNode *)> Stop)
PreCallback: callback before break.
static bool isNodeHidden(const ExplodedNode *N, const ExplodedGraph *G)