From 449deda718db4338bcc8cfd88a40926cbf010ee1 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 26 Nov 2026 22:13:07 -0600 Subject: [PATCH 01/12] Track the other paths --- lib/forwardanalyzer.cpp | 48 +++++++++++++++++++- test/testcondition.cpp | 97 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 144 insertions(+), 1 deletion(-) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 46330f41e9d..6325bc03d8d 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -65,6 +65,38 @@ namespace { // Total forks of the traversal (shared via the fork() copy); backstop past the depth bound. std::shared_ptr forkBudget = std::make_shared(0); + // The paths that left this traversal without escaping: forks carried past their if and + // then-paths that are not followed further. + struct OtherPaths { + Analyzer::Result result; + bool exist = false; + void add(const Analyzer::Result& r) { + if (r.terminate == Analyzer::Terminate::Escape) + return; + result.update(r); + exist = true; + } + void add(const OtherPaths& paths) { + if (paths.exist) + add(paths.result); + } + }; + OtherPaths otherPaths; + + // The result over every path to end, not only the path this traversal follows + Analyzer::Result result(const Token* end) const { + Analyzer::Result r{actions, terminate}; + if (!otherPaths.exist) + return r; + if (terminate == Analyzer::Terminate::Escape) { + if (isReturnScope(end, settings().library)) + return r; + r.terminate = otherPaths.result.terminate; + } + r.action |= otherPaths.result.action; + return r; + } + Progress Break(Analyzer::Terminate t = Analyzer::Terminate::None) { if ((!analyzeOnly || analyzeTerminate) && t != Analyzer::Terminate::None) terminate = t; @@ -334,6 +366,7 @@ namespace { ft.analyzeTerminate = true; } ft.actions = Analyzer::Action::None; + ft.otherPaths = OtherPaths{}; return ft; } @@ -407,6 +440,8 @@ namespace { // Save and reset actions Analyzer::Action prevActions = actions; actions = Analyzer::Action::None; + OtherPaths prevPaths = otherPaths; + otherPaths = OtherPaths{}; Progress p = updateRange(branch.endBlock->link(), branch.endBlock, depth); branch.action |= actions; // Restore actions @@ -434,6 +469,14 @@ namespace { } } + // The other paths escape as well when the scope always escapes + if (!branch.isConclusiveEscape()) { + if (otherPaths.exist) + branch.action |= otherPaths.result.action; + prevPaths.add(otherPaths); + } + otherPaths = prevPaths; + return p; } @@ -838,6 +881,9 @@ namespace { ++ft.forkDepth; ft.analyzer->assume(condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute); ft.updateRange(tok->next(), end, depth - 1); + otherPaths.add(ft.result(end)); + } else if (!thenBranch.isConclusiveEscape()) { + otherPaths.add(ft.result(thenBranch.endBlock)); } if (elseBranch.progress == Progress::Break) { // Only the else branch escaped; the then branch falls through, so @@ -995,7 +1041,7 @@ Analyzer::Result valueFlowGenericForward(Token* start, const Token* end, const V if (start) ft.analyzer->updateState(start); ft.updateRange(start, end); - return Analyzer::Result{ ft.actions, ft.terminate }; + return ft.result(end); } Analyzer::Result valueFlowGenericForward(Token* start, const ValuePtr& a, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings) diff --git a/test/testcondition.cpp b/test/testcondition.cpp index 5961dca21a9..c41a7342164 100644 --- a/test/testcondition.cpp +++ b/test/testcondition.cpp @@ -5005,6 +5005,103 @@ class TestCondition : public TestFixture { "}\n"); ASSERT_EQUALS("", errout_str()); + check("bool g();\n" // only the path that skips 'w = true' returns + "void use();\n" + "void f(bool a, bool b) {\n" + " if (a) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w || !b)\n" + " return;\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // the path is split inside a block that is always entered + "void use();\n" + "void f(bool a, bool b) {\n" + " if (a) {\n" + " bool w = false;\n" + " if (a) {\n" + " if (g())\n" + " w = true;\n" + " }\n" + " if (!w)\n" + " return;\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:9] -> [test.cpp:6:13]: (warning) Identical inner 'if' condition is always true. [identicalInnerCondition]\n", + errout_str()); + + check("bool g();\n" // x is assigned on the path that sets w + "void use();\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (w)\n" + " x = 1;\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" + "void use();\n" + "void f(bool c) {\n" + " int x = 0;\n" + " if (c) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (w)\n" + " x = 1;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // every path returns + "void use();\n" + "void f(bool a, bool b) {\n" + " if (a) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " return;\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:9] -> [test.cpp:12:14]: (style) Condition 'a' is always false [knownConditionTrueFalse]\n", + errout_str()); + + check("bool g();\n" + "void use();\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " if (g())\n" + " x = 1;\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:11] -> [test.cpp:9:11]: (style) Condition 'x==0' is always false [knownConditionTrueFalse]\n", + errout_str()); + check("void f() {\n" " if (42) {}\n" " if (42U) {}\n" From c275013f8d133842af0dff0c258c528204dbb65b Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 28 Nov 2026 12:12:22 -0600 Subject: [PATCH 02/12] Use a worklist --- lib/forwardanalyzer.cpp | 599 ++++++++++++++++++++++++++++----------- test/testcondition.cpp | 159 +++++++++++ test/testnullpointer.cpp | 36 +++ test/testother.cpp | 37 +++ test/testvalueflow.cpp | 12 +- 5 files changed, 673 insertions(+), 170 deletions(-) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 6325bc03d8d..91285fc6c20 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -34,10 +34,14 @@ #include #include +#include #include #include #include +#include #include +#include +#include #include #include #include @@ -45,56 +49,35 @@ #include namespace { - struct ForwardTraversal { - enum class Progress : std::uint8_t { Continue, Break, Skip }; - ForwardTraversal(const ValuePtr& analyzer, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings) - : analyzer(analyzer), tokenList(tokenList), errorLogger(errorLogger), settings(settings) - {} + // One way through the code: the tracked value with the state assumed on the way. The traversal + // walks one path at a time; the others are kept aside and swapped in. + struct Path { + explicit Path(const ValuePtr& analyzer) : analyzer(analyzer) {} ValuePtr analyzer; - RefThunk tokenList; - RefThunk errorLogger; - RefThunk settings; Analyzer::Action actions; bool analyzeOnly{}; bool analyzeTerminate{}; Analyzer::Terminate terminate = Analyzer::Terminate::None; - std::vector loopEnds; int branchCount = 0; - // Nested condition-fork depth on this lineage (copied by fork()); bounds the fan-out. + // Nested condition-fork depth of this path; bounds the fan-out. int forkDepth = 0; + }; + + struct ForwardTraversal : Path { + // Forked: the path was replaced by the paths of a fork, which are counted in the range + enum class Progress : std::uint8_t { Continue, Break, Skip, Forked }; + ForwardTraversal(const ValuePtr& analyzer, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings) + : Path(analyzer), tokenList(tokenList), errorLogger(errorLogger), settings(settings) + {} + RefThunk tokenList; + RefThunk errorLogger; + RefThunk settings; + std::vector loopEnds; // Total forks of the traversal (shared via the fork() copy); backstop past the depth bound. std::shared_ptr forkBudget = std::make_shared(0); - // The paths that left this traversal without escaping: forks carried past their if and - // then-paths that are not followed further. - struct OtherPaths { - Analyzer::Result result; - bool exist = false; - void add(const Analyzer::Result& r) { - if (r.terminate == Analyzer::Terminate::Escape) - return; - result.update(r); - exist = true; - } - void add(const OtherPaths& paths) { - if (paths.exist) - add(paths.result); - } - }; - OtherPaths otherPaths; - - // The result over every path to end, not only the path this traversal follows - Analyzer::Result result(const Token* end) const { - Analyzer::Result r{actions, terminate}; - if (!otherPaths.exist) - return r; - if (terminate == Analyzer::Terminate::Escape) { - if (isReturnScope(end, settings().library)) - return r; - r.terminate = otherPaths.result.terminate; - } - r.action |= otherPaths.result.action; - return r; + Path& path() { + return *this; } Progress Break(Analyzer::Terminate t = Analyzer::Terminate::None) { @@ -103,13 +86,85 @@ namespace { return Progress::Break; } + // What became of the paths through a range + struct Outcome { + Analyzer::Action action = Analyzer::Action::None; + int reached = 0; + // How each path that did not reach the end stopped + std::vector stops; + + void reach(Analyzer::Action a) { + action |= a; + ++reached; + } + void stop(Analyzer::Action a, Analyzer::Terminate t) { + action |= a; + stops.push_back(t); + } + // The paths that stopped in a block of the range stopped in the range. If another path + // covers the code they did not walk, only an escape or a changed value counts. + void add(const Outcome& block, bool covered) { + action |= block.action; + for (Analyzer::Terminate t : block.stops) { + if (covered && t != Analyzer::Terminate::Escape && t != Analyzer::Terminate::Modified) + t = Analyzer::Terminate::None; + stops.push_back(t); + } + } + bool hasEscape() const { + return std::find(stops.cbegin(), stops.cend(), Analyzer::Terminate::Escape) != stops.cend(); + } + bool allEscape() const { + return reached == 0 && !stops.empty() && + std::count(stops.cbegin(), stops.cend(), Analyzer::Terminate::Escape) == static_cast(stops.size()); + } + Analyzer::Terminate worst() const { + Analyzer::Terminate result = Analyzer::Terminate::None; + for (Analyzer::Terminate t : stops) { + if (rank(t) > rank(result)) + result = t; + } + return result; + } + // A path stopped without walking the rest of the range + bool unwalked() const { + const Analyzer::Terminate t = worst(); + return t != Analyzer::Terminate::None && t != Analyzer::Terminate::Modified; + } + static int rank(Analyzer::Terminate t) { + switch (t) { + case Analyzer::Terminate::None: + case Analyzer::Terminate::Escape: + return 0; + case Analyzer::Terminate::Modified: + return 1; + case Analyzer::Terminate::Conditional: + return 2; + case Analyzer::Terminate::Inconclusive: + return 3; + case Analyzer::Terminate::Bail: + return 4; + } + cppcheck::unreachable(); + } + }; + + // One way through a statement that forks, e.g. the then block of an if struct Branch { explicit Branch(Token* tok = nullptr) : endBlock(tok) {} + // nullptr if there is nothing to walk, e.g. an if without else Token* endBlock = nullptr; + // The condition that holds on the way in. nullptr for the rest of a fork, where no + // condition of its alternatives holds. + const Token* condTok = nullptr; Analyzer::Action action = Analyzer::Action::None; - bool check = false; bool escape = false; bool escapeUnknown = false; + bool reachesEnd = true; + // The condition is false at the end of the block on every path (e.g. 'if (x > 5) x = 5;') + bool falseAtEnd = false; + // The paths at the end of the block + std::vector paths; bool isEscape() const { return escape || escapeUnknown; } @@ -128,13 +183,32 @@ namespace { bool hasGoto() const { return endBlock ? ForwardTraversal::hasGoto(endBlock) : false; } - Progress progress = Progress::Continue; - // The path through this branch continues past the if - bool continues() const { - return progress != Progress::Break && !isEscape(); - } }; + // A statement where the paths part, e.g. an if whose condition is undecided. Each alternative + // is walked with walkAlternative(), what is left of the incoming path with walkRest(), and + // joinFork() lets the paths go on. + struct ForkPoint { + // The paths of the alternatives go on past the statement. Otherwise they stop at the end + // of their block and the rest stands for every alternative. + bool split = false; + bool conditional = false; + int branchCount = 0; + }; + + // The paths of the range being walked, apart from the one in the traversal + struct Range { + // Whether the paths may part for good at a fork. They may not if the traversal goes on + // after the range: then one path has to stand for all of them at its end. + bool canSplit = false; + // Paths that go on from a token, last one first + std::vector> waiting; + // Paths at the end of the range + std::vector reached; + Outcome outcome; + }; + Range range; + bool stopUpdates() { analyzeOnly = true; return actions.isModified(); @@ -150,9 +224,13 @@ namespace { } std::pair evalCond(const Token* tok, const Token* ctx = nullptr) const { + return evalCond(*analyzer, tok, ctx); + } + + static std::pair evalCond(const Analyzer& a, const Token* tok, const Token* ctx) { if (!tok) return std::make_pair(false, false); - std::vector result = analyzer->evaluate(tok, ctx); + std::vector result = a.evaluate(tok, ctx); // TODO: We should convert to bool const bool checkThen = std::any_of(result.cbegin(), result.cend(), [](MathLib::bigint x) { return x != 0; @@ -349,9 +427,13 @@ namespace { } Analyzer::Action analyzeRange(const Token* start, const Token* end) const { + return analyzeRange(*analyzer, start, end); + } + + static Analyzer::Action analyzeRange(const Analyzer& a, const Token* start, const Token* end) { Analyzer::Action result = Analyzer::Action::None; for (const Token* tok = start; tok && tok != end; tok = tok->next()) { - Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Forward); + Analyzer::Action action = a.analyze(tok, Analyzer::Direction::Forward); if (action.isModified() || action.isInconclusive()) return action; result |= action; @@ -360,13 +442,15 @@ namespace { } ForwardTraversal fork(bool analyze = false) const { - ForwardTraversal ft = *this; + ForwardTraversal ft{analyzer, tokenList, errorLogger, settings}; + ft.path() = *this; + ft.loopEnds = loopEnds; + ft.forkBudget = forkBudget; if (analyze) { ft.analyzeOnly = true; ft.analyzeTerminate = true; } ft.actions = Analyzer::Action::None; - ft.otherPaths = OtherPaths{}; return ft; } @@ -381,10 +465,10 @@ namespace { // A value changed in either branch is only possible past the if, on both paths. False if // it cannot be lowered. - static bool lowerAfterBranches(Analyzer& a, const Branch& thenBranch, const Branch& elseBranch) { - if ((thenBranch.isModified() || elseBranch.isModified()) && !a.lowerToPossible()) + static bool lowerAfterBranches(Analyzer& a, const std::vector& branches) { + if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isModified)) && !a.lowerToPossible()) return false; - if ((thenBranch.isInconclusive() || elseBranch.isInconclusive()) && !a.lowerToInconclusive()) + if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isInconclusive)) && !a.lowerToInconclusive()) return false; return true; } @@ -400,7 +484,7 @@ namespace { std::vector tryForkUpdateScope(Token* endBlock, bool isModified = false) const { std::vector result = tryForkScope(endBlock, isModified); for (ForwardTraversal& ft : result) - ft.updateScope(endBlock); + ft.updateAllScopePaths(endBlock); return result; } @@ -435,70 +519,236 @@ namespace { return a; } - Progress updateBranch(Branch& branch, int depth) + // Walk a block on the path in the traversal. The paths do not part for good inside it: each + // one would have to be followed past the block to the end of the range, which costs too much. + // A path that stops in the block has stopped in the range; covered: another path goes on for + // it past the block. + Branch walkBranch(Token* endBlock, int depth, bool covered) { - // Save and reset actions - Analyzer::Action prevActions = actions; + const Analyzer::Action outerActions = actions; actions = Analyzer::Action::None; - OtherPaths prevPaths = otherPaths; - otherPaths = OtherPaths{}; - Progress p = updateRange(branch.endBlock->link(), branch.endBlock, depth); - branch.action |= actions; - // Restore actions - actions |= prevActions; - - if (terminate == Analyzer::Terminate::Escape) { + Range block = walkPaths(endBlock->link(), endBlock, depth, false); + range.outcome.add(block.outcome, covered); + // The path walked last is no longer in the traversal if it is at the end of the block + Branch branch = resolve(endBlock, block.outcome, analyzer ? *analyzer : *block.reached.back().analyzer); + branch.paths = std::move(block.reached); + for (Path& p : branch.paths) + p.actions |= outerActions; + return branch; + } + + Branch resolve(Token* endBlock, const Outcome& paths, const Analyzer& a) const + { + Branch branch{endBlock}; + branch.action = paths.action; + branch.reachesEnd = paths.reached > 0; + if (paths.allEscape()) { branch.escape = true; - // The traversal followed an escaping path, but if the scope does not structurally - // always escape then another path (e.g. a modified fork) falls through, so the escape - // is only conditional - keep isModified() meaningful by not treating it as conclusive. + // The paths can miss a way through the block: a call is taken to return what an + // earlier call of the same function returned. Unless the block structurally always + // escapes, it may fall through and change the value on the way. bool structuralUnknown = false; - const bool structuralEscape = isEscapeScope(branch.endBlock, structuralUnknown); + const bool structuralEscape = isEscapeScope(endBlock, structuralUnknown); branch.escapeUnknown = !structuralEscape || structuralUnknown; - // The traversal stopped at the escape, so the rest of the scope was not walked; a - // fall-through path could still modify the value there - include the whole scope's - // actions so isModified() sees it. if (branch.escapeUnknown) - branch.action |= analyzeScope(branch.endBlock); - } else { - // Detect an escape the traversal did not flag (e.g. an unknown noreturn call); - // escapeUnknown reports a possible (unknown) escape. - branch.escape = isEscapeScope(branch.endBlock, branch.escapeUnknown); - if (terminate != Analyzer::Terminate::None && terminate != Analyzer::Terminate::Modified) { - branch.action |= analyzeScope(branch.endBlock); - } + branch.action |= analyzeRange(a, endBlock->link(), endBlock); + return branch; } + // Detect an escape the paths did not flag (e.g. an unknown noreturn call); + // escapeUnknown reports a possible (unknown) escape. + branch.escape = isEscapeScope(endBlock, branch.escapeUnknown); + if (paths.unwalked()) + branch.action |= analyzeRange(a, endBlock->link(), endBlock); + return branch; + } - // The other paths escape as well when the scope always escapes - if (!branch.isConclusiveEscape()) { - if (otherPaths.exist) - branch.action |= otherPaths.result.action; - prevPaths.add(otherPaths); - } - otherPaths = prevPaths; + // The path in the traversal stops before the end of the range + void stopPath(Analyzer::Terminate t = Analyzer::Terminate::None) + { + Break(t); + range.outcome.stop(actions, terminate); + } - return p; + // The paths go on after tok, the first one first + Progress resume(std::vector paths, Token* tok) + { + for (auto it = paths.rbegin(); it != paths.rend(); ++it) + range.waiting.emplace_back(std::move(*it), tok->next()); + return Progress::Forked; } - // Update the branch that the evaluated condition takes - Progress updateTakenBranch(Branch& branch, const Token* skippedBlock, const Token* condTok, int depth) + // Walk the block that the evaluated condition takes + Progress updateTakenBranch(Token* endBlock, const Token* skippedBlock, const Token* condTok, Token* ifEnd, int depth) { // The condition is only "known" because of an earlier assumption, so the // skipped block could still modify the value -> lower to possible if (!condTok->hasKnownIntValue() && skippedBlock && analyzeScope(skippedBlock).isModified() && !analyzer->lowerToPossible()) return Break(Analyzer::Terminate::Bail); - if (!branch.endBlock) + if (!endBlock) { + // Record the state past the skipped block, so that the conditions evaluated later do + // not each look for changes in it + if (ifEnd->next()) + analyzer->updateState(ifEnd->next()); return Progress::Continue; - updateScopeState(branch.endBlock); - if (updateBranch(branch, depth - 1) == Progress::Break) - return Progress::Break; - // The branch was entered because of the tracked value; if it might not - // return (it ends in a call to an unknown, possibly noreturn function) - // then the value might not flow past the branch. - if (!condTok->hasKnownIntValue() && !branch.escape && branch.escapeUnknown && !analyzer->lowerToInconclusive()) - return Break(Analyzer::Terminate::Bail); - return Progress::Continue; + } + updateScopeState(endBlock); + Branch branch = walkBranch(endBlock, depth - 1, false); + std::vector paths; + for (Path& p : branch.paths) { + path() = std::move(p); + // The branch was entered because of the tracked value; if it might not + // return (it ends in a call to an unknown, possibly noreturn function) + // then the value might not flow past the branch. + if (!condTok->hasKnownIntValue() && !branch.escape && branch.escapeUnknown && !analyzer->lowerToInconclusive()) + stopPath(Analyzer::Terminate::Bail); + else + paths.push_back(std::move(path())); + } + return resume(std::move(paths), ifEnd); + } + + // The paths part at the path in the traversal + ForkPoint startFork(const Token* condTok) const + { + ForkPoint point; + point.split = range.canSplit && canFork(); + point.conditional = stopOnCondition(condTok); + point.branchCount = branchCount; + return point; + } + + // Walk a block on a copy of the incoming path, where condTok holds + Branch walkAlternative(const ForkPoint& point, const Path& incoming, const Token* condTok, Token* endBlock, int depth) + { + path() = incoming; + // The value only flows into the block when the condition can split it; for an opaque or + // correlated condition (e.g. 'if (f(x))') it does not, so the path is analyze-only: the + // block's effect is still tracked but nothing is reported in it. + if (!analyzer->updateScope(endBlock, false)) { + analyzeOnly = true; + analyzeTerminate = true; + } + if (point.split) { + ++(*forkBudget); + ++forkDepth; + } + analyzer->assume(condTok, true, Analyzer::Assume::Pending); + Branch branch = walkBranch(endBlock, depth, !point.split); + branch.condTok = condTok; + branch.falseAtEnd = !point.split && std::all_of(branch.paths.cbegin(), branch.paths.cend(), [&](const Path& p) { + const std::pair check = evalCond(*p.analyzer, condTok, endBlock->previous()); + return !check.first && check.second; + }); + return branch; + } + + // Walk the incoming path where no condition of the alternatives holds. endBlock is the block + // for that, if any. The path goes on after forkEnd. + Branch walkRest(const ForkPoint& point, + Path incoming, + const std::vector& alternatives, + Token* endBlock, + const Token* forkEnd, + int depth) + { + path() = std::move(incoming); + const unsigned int pending = endBlock ? Analyzer::Assume::Pending : Analyzer::Assume::None; + bool assumed = false; + for (const Branch& alt : alternatives) { + actions |= alt.action; + // The condition is an assumption on this path if the alternative drops the value. If + // its paths go on past the fork the value is the same with and without it. Otherwise + // this path stands for the alternative as well and records that the condition is + // false only if that holds on both. With a block the state is recorded after it. + if (alt.isDead()) + analyzer->assume(alt.condTok, false, Analyzer::Assume::None | pending); + else if (alt.reachesEnd && (point.split || alt.falseAtEnd)) + analyzer->assume(alt.condTok, false, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute | pending); + else + continue; + assumed = true; + } + // An assumption records the state where the path goes on. Without one the state stays + // at an earlier token, and every condition evaluated later looks for changes from there. + if (!endBlock) { + if (!assumed && forkEnd->next()) + analyzer->updateState(forkEnd->next()); + Branch rest; + rest.paths.push_back(std::move(path())); + return rest; + } + if (!assumed) + updateScopeState(endBlock); + Branch rest = walkBranch(endBlock, depth, false); + for (Path& p : rest.paths) + p.analyzer->updateState(endBlock->previous()); + return rest; + } + + // Let the paths at the end of the branches go on after tok + Progress joinFork(const ForkPoint& point, std::vector alternatives, Branch rest, Token* tok) + { + std::vector branches{&rest}; + std::transform(alternatives.cbegin(), alternatives.cend(), std::back_inserter(branches), [](const Branch& alt) { + return &alt; + }); + const Analyzer::Action action = + std::accumulate(branches.cbegin(), branches.cend(), Analyzer::Action{Analyzer::Action::None}, [](Analyzer::Action a, const Branch* branch) { + return a | branch->action; + }); + const bool dead = std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isDead)); + const bool jumps = std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::hasGoto)); + std::vector paths; + for (Branch& alt : alternatives) { + for (Path& p : alt.paths) { + path() = std::move(p); + actions |= action; + if (jumps) { + stopPath(Analyzer::Terminate::Bail); + } else if (alt.isEscape()) { + stopPath(Analyzer::Terminate::Escape); + } else if (!point.split) { + // The rest goes on for this path. If the rest stopped, nothing does. + if (!rest.reachesEnd) + stopPath(); + } else if (!lowerAfterBranches(*analyzer, branches)) { + stopPath(); + } else { + // The branch limit counts the branches on the way past the fork, as it does + // for the rest + branchCount = point.branchCount; + // Anchor the state (and the block's assignments) at the block end + analyzer->assume(alt.condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute); + paths.push_back(std::move(path())); + } + } + } + for (Path& p : rest.paths) { + path() = std::move(p); + actions |= action; + if (dead && point.conditional && stopUpdates()) + stopPath(Analyzer::Terminate::Conditional); + else if (!lowerAfterBranches(*analyzer, branches)) + stopPath(Analyzer::Terminate::Bail); + else if (jumps) + stopPath(Analyzer::Terminate::Bail); + else + paths.push_back(std::move(path())); + } + return resume(std::move(paths), tok); + } + + // Neither outcome of the condition is known: walk each on its own paths + Progress forkIf(const Token* condTok, Token* thenEnd, Token* elseEnd, int depth) + { + const ForkPoint point = startFork(condTok); + Token* ifEnd = elseEnd ? elseEnd : thenEnd; + Path incoming = std::move(path()); + std::vector alternatives; + alternatives.push_back(walkAlternative(point, incoming, condTok, thenEnd, depth - 1)); + Branch rest = walkRest(point, std::move(incoming), alternatives, elseEnd, ifEnd, depth - 1); + return joinFork(point, std::move(alternatives), std::move(rest), ifEnd); } bool reentersLoop(Token* endBlock, const Token* condTok, const Token* stepTok) const { @@ -630,7 +880,7 @@ namespace { if (forkContinue) { for (ForwardTraversal& ft : ftv) { if (!ft.actions.isIncremental()) - ft.updateRange(endBlock, endToken); + ft.updateAllPaths(endBlock, endToken); } } if (allAnalysis.isIncremental()) @@ -670,10 +920,73 @@ namespace { return updateRange(endBlock->link(), endBlock, depth); } + Progress updateAllScopePaths(Token* endBlock, int depth = 20) + { + if (!endBlock) + return Break(); + updateScopeState(endBlock); + return updateAllPaths(endBlock->link(), endBlock, depth); + } + + // This traversal goes on after the range, so the paths do not part for good in it: at a fork + // one path stands for every alternative. + Progress updateRange(Token* start, const Token* end, int depth = 20) { + Range walked = walkPaths(start, end, depth, false); + setResult(walked.outcome, end); + if (walked.reached.empty()) + return Progress::Break; + path() = std::move(walked.reached.front()); + return Progress::Continue; + } + + // Follow every path to the end of the range. This traversal gets their joint result and must + // not go on after the range. + Progress updateAllPaths(Token* start, const Token* end, int depth = 20) { + const Range walked = walkPaths(start, end, depth, true); + setResult(walked.outcome, end); + return walked.reached.empty() ? Progress::Break : Progress::Continue; + } + + void setResult(const Outcome& outcome, const Token* end) { + // A path that stopped without an escape was not followed to one, but the code can show + // that there is no way to the end of the range + const bool escapes = outcome.allEscape() || + (outcome.reached == 0 && outcome.hasEscape() && isReturnScope(end, settings().library)); + actions = outcome.action; + terminate = escapes ? Analyzer::Terminate::Escape : outcome.worst(); + } + + // Walk the path in the traversal and the paths that fork off it from start to end. No path is + // left in the traversal: the ones that go on are in the result. + Range walkPaths(Token* start, const Token* end, int depth, bool split) { + Range outer = std::move(range); + range = Range{}; + range.canSplit = split; + Token* tok = start; + for (;;) { + const Progress p = walkRange(tok, end, depth); + if (p == Progress::Continue) { + range.outcome.reach(actions); + range.reached.push_back(std::move(path())); + } else if (p == Progress::Break) { + range.outcome.stop(actions, terminate); + } + if (range.waiting.empty()) + break; + path() = std::move(range.waiting.back().first); + tok = range.waiting.back().second; + range.waiting.pop_back(); + } + Range walked = std::move(range); + range = std::move(outer); + return walked; + } + /** + * Walk the path in the traversal until it stops, reaches the end of the range or forks * @throws InternalError thrown on cyclic analysis */ - Progress updateRange(Token* start, const Token* end, int depth = 20) { + Progress walkRange(Token* start, const Token* end, int depth) { if (depth < 0) return Break(Analyzer::Terminate::Bail); std::size_t i = 0; @@ -828,76 +1141,24 @@ namespace { // Traverse condition if (updateRecursive(condTok) == Progress::Break) return Break(); - Branch thenBranch{endBlock}; - Branch elseBranch{endBlock->tokAt(2) ? endBlock->linkAt(2) : nullptr}; // Check if condition is true or false - std::tie(thenBranch.check, elseBranch.check) = evalCond(condTok); - if (!thenBranch.check && !elseBranch.check && stopOnCondition(condTok) && stopUpdates()) + bool checkThen, checkElse; + std::tie(checkThen, checkElse) = evalCond(condTok); + if (!checkThen && !checkElse && stopOnCondition(condTok) && stopUpdates()) return Break(Analyzer::Terminate::Conditional); - const bool hasElse = Token::simpleMatch(endBlock, "} else {"); - tok = hasElse ? endBlock->linkAt(2) : endBlock; - if (thenBranch.check) { - if (updateTakenBranch(thenBranch, hasElse ? elseBranch.endBlock : nullptr, condTok, depth) == - Progress::Break) - return Break(); - } else if (elseBranch.check) { - if (updateTakenBranch(elseBranch, thenBranch.endBlock, condTok, depth) == Progress::Break) - return Break(); - } else { - const bool conditional = stopOnCondition(condTok); - // The then-path runs on a fork, the else-path on this traversal. The value only - // flows into the then-branch when the condition can split it; for an opaque or - // correlated condition (e.g. 'if (f(x))') it does not, so the fork is analyze-only: - // the branch's effect is still tracked but nothing is reported in it. - ForwardTraversal ft = fork(!analyzer->updateScope(thenBranch.endBlock, false)); - ft.analyzer->assume(condTok, true, Analyzer::Assume::Pending); - thenBranch.progress = ft.updateBranch(thenBranch, depth - 1); - actions |= thenBranch.action; - // The condition is an assumption on the else-path only if the then-path drops - // the value. With an else block the state is recorded after it. - analyzer->assume(condTok, - false, - (thenBranch.isDead() ? Analyzer::Assume::None - : Analyzer::Assume::Quiet | Analyzer::Assume::Absolute) | - (hasElse ? Analyzer::Assume::Pending : Analyzer::Assume::None)); - if (hasElse) { - elseBranch.progress = updateBranch(elseBranch, depth - 1); - if (elseBranch.progress != Progress::Break) - analyzer->updateState(elseBranch.endBlock->previous()); - } - if ((thenBranch.isDead() || elseBranch.isDead()) && conditional && stopUpdates()) - elseBranch.progress = Break(Analyzer::Terminate::Conditional); - if (!lowerAfterBranches(*ft.analyzer, thenBranch, elseBranch)) - thenBranch.progress = Progress::Break; - if (elseBranch.progress != Progress::Break && !lowerAfterBranches(*analyzer, thenBranch, elseBranch)) - elseBranch.progress = Break(Analyzer::Terminate::Bail); - if (thenBranch.hasGoto() || elseBranch.hasGoto()) - return Break(Analyzer::Terminate::Bail); - // Carry the then-path past the if. Skip the closing brace, whose handler is for - // traversals that start inside the block; re-assume to anchor the state (and the - // block's assignments) at the block end. - if (thenBranch.continues() && canFork()) { - ++(*forkBudget); - ++ft.forkDepth; - ft.analyzer->assume(condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute); - ft.updateRange(tok->next(), end, depth - 1); - otherPaths.add(ft.result(end)); - } else if (!thenBranch.isConclusiveEscape()) { - otherPaths.add(ft.result(thenBranch.endBlock)); - } - if (elseBranch.progress == Progress::Break) { - // Only the else branch escaped; the then branch falls through, so - // the scope as a whole does not always escape. - if (terminate == Analyzer::Terminate::Escape && !thenBranch.isEscape()) - terminate = Analyzer::Terminate::None; - return Break(); - } - } + Token* elseEnd = Token::simpleMatch(endBlock, "} else {") ? endBlock->linkAt(2) : nullptr; + tok = elseEnd ? elseEnd : endBlock; + if (!checkThen && !checkElse) + return forkIf(condTok, endBlock, elseEnd, depth); + const Progress p = + updateTakenBranch(checkThen ? endBlock : elseEnd, checkThen ? elseEnd : endBlock, condTok, tok, depth); + if (p != Progress::Continue) + return p; } } else if (Token::simpleMatch(tok, "try {")) { Token* endBlock = tok->linkAt(1); ForwardTraversal tryTraversal = fork(); - tryTraversal.updateScope(endBlock, depth - 1); + tryTraversal.updateAllScopePaths(endBlock, depth - 1); bool bail = tryTraversal.actions.isModified(); if (bail) { actions = tryTraversal.actions; @@ -911,7 +1172,7 @@ namespace { return Break(); endBlock = endCatch->linkAt(1); ForwardTraversal ft = fork(); - ft.updateScope(endBlock, depth - 1); + ft.updateAllScopePaths(endBlock, depth - 1); bail |= ft.terminate != Analyzer::Terminate::None || ft.actions.isModified(); } if (bail) @@ -1040,8 +1301,8 @@ Analyzer::Result valueFlowGenericForward(Token* start, const Token* end, const V ForwardTraversal ft{a, tokenList, errorLogger, settings}; if (start) ft.analyzer->updateState(start); - ft.updateRange(start, end); - return ft.result(end); + ft.updateAllPaths(start, end); + return Analyzer::Result{ft.actions, ft.terminate}; } Analyzer::Result valueFlowGenericForward(Token* start, const ValuePtr& a, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings) diff --git a/test/testcondition.cpp b/test/testcondition.cpp index c41a7342164..39b9c466c0e 100644 --- a/test/testcondition.cpp +++ b/test/testcondition.cpp @@ -5102,6 +5102,165 @@ class TestCondition : public TestFixture { ASSERT_EQUALS("[test.cpp:4:11] -> [test.cpp:9:11]: (style) Condition 'x==0' is always false [knownConditionTrueFalse]\n", errout_str()); + check("bool g();\n" // the path that leaves the else block assigns x afterwards + "bool c();\n" + "int h();\n" + "void use(int);\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " if (c()) {\n" + " } else {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " }\n" + " x = h();\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use(x);\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // the same in a block that is always entered + "int h();\n" + "void use(int);\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " if (x == 0) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " }\n" + " x = h();\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use(x);\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:5:11] -> [test.cpp:6:15]: (warning) Identical inner 'if' condition is always true. [identicalInnerCondition]\n", + errout_str()); + + check("bool g();\n" // #15264 - the split is in the then block of another unknown condition + "bool h();\n" + "void use();\n" + "void f(bool a, bool b) {\n" + " if (a) {\n" + " if (h()) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " } else {\n" + " return;\n" + " }\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // #15264 - the split is in a loop + "void use();\n" + "void f(bool a, bool b, bool c) {\n" + " if (a) {\n" + " bool w = false;\n" + " while (g()) {\n" + " if (c)\n" + " w = true;\n" + " }\n" + " if (!w)\n" + " return;\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // the path that leaves the else block assigns x in a later block + "bool c();\n" + "void use();\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " bool w = false;\n" + " if (c()) {\n" + " } else {\n" + " if (g())\n" + " w = true;\n" + " }\n" + " if (w)\n" + " x = 1;\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // the path that leaves the loop assigns x in a later block + "void use();\n" + "void f(int x, bool c) {\n" + " if (x == 0) {\n" + " bool w = false;\n" + " while (g()) {\n" + " if (c)\n" + " w = true;\n" + " }\n" + " if (w)\n" + " x = 1;\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + { + // Without splitting, the path past 'if (g())' stands for both outcomes + /*const*/ Settings s = settings0; + s.vfOptions.maxForwardConditionForkDepth = 0; + check("bool g();\n" + "void use();\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (w)\n" + " x = 1;\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n", s); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // #15264 + "void use();\n" + "void f(bool a, bool b) {\n" + " if (a) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w || !b)\n" + " return;\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n", s); + ASSERT_EQUALS("", errout_str()); + } + check("void f() {\n" " if (42) {}\n" " if (42U) {}\n" diff --git a/test/testnullpointer.cpp b/test/testnullpointer.cpp index cecbb27ca09..9873a391e2b 100644 --- a/test/testnullpointer.cpp +++ b/test/testnullpointer.cpp @@ -154,6 +154,7 @@ class TestNullPointer : public TestFixture { TEST_CASE(nullpointer113); // a variable is clamped before the check TEST_CASE(nullpointer114); // the else block changes the value TEST_CASE(nullpointer115); // a range condition overlapping the assumed one + TEST_CASE(nullpointer116); // #15264 TEST_CASE(nullpointer_addressOf); // address of TEST_CASE(nullpointerSwitch); // #2626 TEST_CASE(nullpointer_cast); // #4692 @@ -3375,6 +3376,41 @@ class TestNullPointer : public TestFixture { ASSERT_EQUALS("[test.cpp:4:24]: (warning) Possible null pointer dereference: p [nullPointer]\n", errout_str()); } + void nullpointer116() { // #15264 - only the path that skips 'w = true' returns + check("bool g();\n" + "void use(int);\n" + "void f(const int *p) {\n" + " if (!p) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " }\n" + " use(*p);\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:9] -> [test.cpp:11:10]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p. [nullPointerRedundantCheck]\n", + errout_str()); + + check("bool g();\n" // the path leaves an else block + "void use(int);\n" + "void f(const int *p, bool c) {\n" + " if (!p) {\n" + " if (c) {\n" + " } else {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " }\n" + " }\n" + " use(*p);\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:9] -> [test.cpp:14:10]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p. [nullPointerRedundantCheck]\n", + errout_str()); + } + void nullpointer_addressOf() { // address of check("void f() {\n" " struct X *x = 0;\n" diff --git a/test/testother.cpp b/test/testother.cpp index 085b39cfffb..5c91927f9ec 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -936,6 +936,43 @@ class TestOther : public TestFixture { " return 0;\n" "}\n"); ASSERT_EQUALS("[test.cpp:4:26]: (warning) Division by zero. [zerodivcond]\n", errout_str()); + + // #15264 - only the path that sets both flags leaves the block + check("bool g();\n" + "bool h();\n" + "int f(int a) {\n" + " if (a == 0) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " bool v = false;\n" + " if (h())\n" + " v = true;\n" + " if (!w || !v)\n" + " return 0;\n" + " }\n" + " return 10 / a;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:11] -> [test.cpp:14:15]: (warning) Either the condition 'a==0' is redundant or there is division by zero at line 14. [zerodivcond]\n", + errout_str()); + + // TODO #15264: the second call of g() is assumed to return what the first call returned + check("bool g();\n" + "int f(int a) {\n" + " if (a == 0) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return 0;\n" + " if (g())\n" + " return 1;\n" + " }\n" + " return 10 / a;\n" + "}\n"); + TODO_ASSERT_EQUALS("[test.cpp:3:11] -> [test.cpp:12:15]: (warning) Either the condition 'a==0' is redundant or there is division by zero at line 12. [zerodivcond]\n", + "", + errout_str()); } void zeroDivErrorPath() { diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index 60807e49bf8..eb0b1df8300 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -4766,7 +4766,7 @@ class TestValueFlow : public TestFixture { "}\n"; ASSERT_EQUALS(false, testValueOfX(code, 5U, 0)); - // no fork: the main path still knows the condition is false + // no fork: the then block makes the condition false, so it is false on both outcomes /*const*/ Settings s(settings); s.vfOptions.maxForwardConditionForkDepth = 0; code = "void f(int n) {\n" @@ -4777,6 +4777,16 @@ class TestValueFlow : public TestFixture { "}\n"; ASSERT_EQUALS(false, testValueOfX(code, 4U, 1, &s)); ASSERT_EQUALS(true, testValueOfX(code, 5U, 1, &s)); + + // no fork: a condition that is false on one outcome only is not recorded + code = "bool g();\n" + "void f() {\n" + " int x = 1;\n" + " bool w = false;\n" + " if (g()) w = true;\n" + " if (w) { int a = x; }\n" + "}\n"; + ASSERT_EQUALS(true, testValueOfX(code, 6U, 1, &s)); } void valueFlowForwardAfterCondition() From 289bbc917a330c9bce226a49f06d57b9aaae3e31 Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 28 Nov 2026 18:54:16 -0600 Subject: [PATCH 03/12] Use a split flag --- lib/forwardanalyzer.cpp | 510 +++++++++++++++------------------------- test/testvalueflow.cpp | 24 ++ 2 files changed, 220 insertions(+), 314 deletions(-) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 91285fc6c20..7ee59a67630 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -38,10 +38,8 @@ #include #include #include -#include #include #include -#include #include #include #include @@ -49,42 +47,13 @@ #include namespace { - // One way through the code: the tracked value with the state assumed on the way. The traversal - // walks one path at a time; the others are kept aside and swapped in. - struct Path { - explicit Path(const ValuePtr& analyzer) : analyzer(analyzer) {} - ValuePtr analyzer; - Analyzer::Action actions; - bool analyzeOnly{}; - bool analyzeTerminate{}; - Analyzer::Terminate terminate = Analyzer::Terminate::None; - int branchCount = 0; - // Nested condition-fork depth of this path; bounds the fan-out. - int forkDepth = 0; - }; - - struct ForwardTraversal : Path { - // Forked: the path was replaced by the paths of a fork, which are counted in the range - enum class Progress : std::uint8_t { Continue, Break, Skip, Forked }; + // A traversal walks one path through the code: the tracked value with the state assumed on the + // way. Where the paths part, another path is walked on a fork(). + struct ForwardTraversal { + enum class Progress : std::uint8_t { Continue, Break, Skip }; ForwardTraversal(const ValuePtr& analyzer, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings) - : Path(analyzer), tokenList(tokenList), errorLogger(errorLogger), settings(settings) + : analyzer(analyzer), tokenList(tokenList), errorLogger(errorLogger), settings(settings) {} - RefThunk tokenList; - RefThunk errorLogger; - RefThunk settings; - std::vector loopEnds; - // Total forks of the traversal (shared via the fork() copy); backstop past the depth bound. - std::shared_ptr forkBudget = std::make_shared(0); - - Path& path() { - return *this; - } - - Progress Break(Analyzer::Terminate t = Analyzer::Terminate::None) { - if ((!analyzeOnly || analyzeTerminate) && t != Analyzer::Terminate::None) - terminate = t; - return Progress::Break; - } // What became of the paths through a range struct Outcome { @@ -111,6 +80,11 @@ namespace { stops.push_back(t); } } + // Paths that were followed to the end of the same range + void join(const Outcome& paths) { + add(paths, false); + reached += paths.reached; + } bool hasEscape() const { return std::find(stops.cbegin(), stops.cend(), Analyzer::Terminate::Escape) != stops.cend(); } @@ -149,22 +123,38 @@ namespace { } }; - // One way through a statement that forks, e.g. the then block of an if + ValuePtr analyzer; + RefThunk tokenList; + RefThunk errorLogger; + RefThunk settings; + Analyzer::Action actions; + bool analyzeOnly{}; + bool analyzeTerminate{}; + Analyzer::Terminate terminate = Analyzer::Terminate::None; + std::vector loopEnds; + int branchCount = 0; + // Nested condition-fork depth on this lineage (copied by fork()); bounds the fan-out. + int forkDepth = 0; + // Total forks of the traversal (shared via the fork() copy); backstop past the depth bound. + std::shared_ptr forkBudget = std::make_shared(0); + // The paths that parted from this one in the range being walked and do not go on with it + Outcome parted; + + Progress Break(Analyzer::Terminate t = Analyzer::Terminate::None) { + if ((!analyzeOnly || analyzeTerminate) && t != Analyzer::Terminate::None) + terminate = t; + return Progress::Break; + } + struct Branch { explicit Branch(Token* tok = nullptr) : endBlock(tok) {} // nullptr if there is nothing to walk, e.g. an if without else Token* endBlock = nullptr; - // The condition that holds on the way in. nullptr for the rest of a fork, where no - // condition of its alternatives holds. - const Token* condTok = nullptr; Analyzer::Action action = Analyzer::Action::None; bool escape = false; bool escapeUnknown = false; + // The path that walked the block is at its end bool reachesEnd = true; - // The condition is false at the end of the block on every path (e.g. 'if (x > 5) x = 5;') - bool falseAtEnd = false; - // The paths at the end of the block - std::vector paths; bool isEscape() const { return escape || escapeUnknown; } @@ -185,30 +175,6 @@ namespace { } }; - // A statement where the paths part, e.g. an if whose condition is undecided. Each alternative - // is walked with walkAlternative(), what is left of the incoming path with walkRest(), and - // joinFork() lets the paths go on. - struct ForkPoint { - // The paths of the alternatives go on past the statement. Otherwise they stop at the end - // of their block and the rest stands for every alternative. - bool split = false; - bool conditional = false; - int branchCount = 0; - }; - - // The paths of the range being walked, apart from the one in the traversal - struct Range { - // Whether the paths may part for good at a fork. They may not if the traversal goes on - // after the range: then one path has to stand for all of them at its end. - bool canSplit = false; - // Paths that go on from a token, last one first - std::vector> waiting; - // Paths at the end of the range - std::vector reached; - Outcome outcome; - }; - Range range; - bool stopUpdates() { analyzeOnly = true; return actions.isModified(); @@ -224,13 +190,9 @@ namespace { } std::pair evalCond(const Token* tok, const Token* ctx = nullptr) const { - return evalCond(*analyzer, tok, ctx); - } - - static std::pair evalCond(const Analyzer& a, const Token* tok, const Token* ctx) { if (!tok) return std::make_pair(false, false); - std::vector result = a.evaluate(tok, ctx); + std::vector result = analyzer->evaluate(tok, ctx); // TODO: We should convert to bool const bool checkThen = std::any_of(result.cbegin(), result.cend(), [](MathLib::bigint x) { return x != 0; @@ -245,6 +207,11 @@ namespace { return evalCond(tok, ctx).first; } + bool isConditionFalse(const Token* tok, const Token* ctx = nullptr) const { + const std::pair check = evalCond(tok, ctx); + return !check.first && check.second; + } + template )> Progress traverseTok(T* tok, const F &f, bool traverseUnknown, T** out = nullptr) { if (Token::Match(tok, "asm|goto")) @@ -427,13 +394,9 @@ namespace { } Analyzer::Action analyzeRange(const Token* start, const Token* end) const { - return analyzeRange(*analyzer, start, end); - } - - static Analyzer::Action analyzeRange(const Analyzer& a, const Token* start, const Token* end) { Analyzer::Action result = Analyzer::Action::None; for (const Token* tok = start; tok && tok != end; tok = tok->next()) { - Analyzer::Action action = a.analyze(tok, Analyzer::Direction::Forward); + Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Forward); if (action.isModified() || action.isInconclusive()) return action; result |= action; @@ -442,15 +405,13 @@ namespace { } ForwardTraversal fork(bool analyze = false) const { - ForwardTraversal ft{analyzer, tokenList, errorLogger, settings}; - ft.path() = *this; - ft.loopEnds = loopEnds; - ft.forkBudget = forkBudget; + ForwardTraversal ft = *this; if (analyze) { ft.analyzeOnly = true; ft.analyzeTerminate = true; } ft.actions = Analyzer::Action::None; + ft.parted = Outcome{}; return ft; } @@ -465,10 +426,10 @@ namespace { // A value changed in either branch is only possible past the if, on both paths. False if // it cannot be lowered. - static bool lowerAfterBranches(Analyzer& a, const std::vector& branches) { - if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isModified)) && !a.lowerToPossible()) + static bool lowerAfterBranches(Analyzer& a, const Branch& thenBranch, const Branch& elseBranch) { + if ((thenBranch.isModified() || elseBranch.isModified()) && !a.lowerToPossible()) return false; - if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isInconclusive)) && !a.lowerToInconclusive()) + if ((thenBranch.isInconclusive() || elseBranch.isInconclusive()) && !a.lowerToInconclusive()) return false; return true; } @@ -519,25 +480,34 @@ namespace { return a; } - // Walk a block on the path in the traversal. The paths do not part for good inside it: each - // one would have to be followed past the block to the end of the range, which costs too much. - // A path that stops in the block has stopped in the range; covered: another path goes on for - // it past the block. - Branch walkBranch(Token* endBlock, int depth, bool covered) + // What became of this path and of the paths that parted from it + Outcome outcome(Progress p) const + { + Outcome paths = parted; + if (p == Progress::Break) + paths.stop(actions, terminate); + else + paths.reach(actions); + return paths; + } + + // Walk a block on this traversal. The paths do not part for good inside it: each one would + // have to be followed past the block to the end of the range, which costs too much. + Branch updateBranch(Token* endBlock, int depth) { const Analyzer::Action outerActions = actions; actions = Analyzer::Action::None; - Range block = walkPaths(endBlock->link(), endBlock, depth, false); - range.outcome.add(block.outcome, covered); - // The path walked last is no longer in the traversal if it is at the end of the block - Branch branch = resolve(endBlock, block.outcome, analyzer ? *analyzer : *block.reached.back().analyzer); - branch.paths = std::move(block.reached); - for (Path& p : branch.paths) - p.actions |= outerActions; + Outcome outer = std::move(parted); + parted = Outcome{}; + const Progress p = updateRange(endBlock->link(), endBlock, depth); + const Branch branch = resolve(endBlock, outcome(p)); + outer.add(parted, false); + parted = std::move(outer); + actions |= outerActions; return branch; } - Branch resolve(Token* endBlock, const Outcome& paths, const Analyzer& a) const + Branch resolve(Token* endBlock, const Outcome& paths) const { Branch branch{endBlock}; branch.action = paths.action; @@ -551,34 +521,19 @@ namespace { const bool structuralEscape = isEscapeScope(endBlock, structuralUnknown); branch.escapeUnknown = !structuralEscape || structuralUnknown; if (branch.escapeUnknown) - branch.action |= analyzeRange(a, endBlock->link(), endBlock); + branch.action |= analyzeScope(endBlock); return branch; } // Detect an escape the paths did not flag (e.g. an unknown noreturn call); // escapeUnknown reports a possible (unknown) escape. branch.escape = isEscapeScope(endBlock, branch.escapeUnknown); if (paths.unwalked()) - branch.action |= analyzeRange(a, endBlock->link(), endBlock); + branch.action |= analyzeScope(endBlock); return branch; } - // The path in the traversal stops before the end of the range - void stopPath(Analyzer::Terminate t = Analyzer::Terminate::None) - { - Break(t); - range.outcome.stop(actions, terminate); - } - - // The paths go on after tok, the first one first - Progress resume(std::vector paths, Token* tok) - { - for (auto it = paths.rbegin(); it != paths.rend(); ++it) - range.waiting.emplace_back(std::move(*it), tok->next()); - return Progress::Forked; - } - // Walk the block that the evaluated condition takes - Progress updateTakenBranch(Token* endBlock, const Token* skippedBlock, const Token* condTok, Token* ifEnd, int depth) + Progress updateTakenBranch(Token* endBlock, const Token* skippedBlock, const Token* condTok, const Token* ifEnd, int depth) { // The condition is only "known" because of an earlier assumption, so the // skipped block could still modify the value -> lower to possible @@ -593,162 +548,119 @@ namespace { return Progress::Continue; } updateScopeState(endBlock); - Branch branch = walkBranch(endBlock, depth - 1, false); - std::vector paths; - for (Path& p : branch.paths) { - path() = std::move(p); - // The branch was entered because of the tracked value; if it might not - // return (it ends in a call to an unknown, possibly noreturn function) - // then the value might not flow past the branch. - if (!condTok->hasKnownIntValue() && !branch.escape && branch.escapeUnknown && !analyzer->lowerToInconclusive()) - stopPath(Analyzer::Terminate::Bail); - else - paths.push_back(std::move(path())); - } - return resume(std::move(paths), ifEnd); + const Branch branch = updateBranch(endBlock, depth - 1); + if (!branch.reachesEnd) + return Progress::Break; + // The branch was entered because of the tracked value; if it might not + // return (it ends in a call to an unknown, possibly noreturn function) + // then the value might not flow past the branch. + if (!condTok->hasKnownIntValue() && !branch.escape && branch.escapeUnknown && !analyzer->lowerToInconclusive()) + return Break(Analyzer::Terminate::Bail); + return Progress::Continue; } - // The paths part at the path in the traversal - ForkPoint startFork(const Token* condTok) const + // A path that parted from this one stops + void stopFork(ForwardTraversal& ft, Analyzer::Terminate t = Analyzer::Terminate::None) { - ForkPoint point; - point.split = range.canSplit && canFork(); - point.conditional = stopOnCondition(condTok); - point.branchCount = branchCount; - return point; + ft.Break(t); + parted.stop(ft.actions, ft.terminate); } - // Walk a block on a copy of the incoming path, where condTok holds - Branch walkAlternative(const ForkPoint& point, const Path& incoming, const Token* condTok, Token* endBlock, int depth) + // This path stopped; the path of a fork goes on in its place + void replaceWith(ForwardTraversal ft) { - path() = incoming; - // The value only flows into the block when the condition can split it; for an opaque or - // correlated condition (e.g. 'if (f(x))') it does not, so the path is analyze-only: the - // block's effect is still tracked but nothing is reported in it. - if (!analyzer->updateScope(endBlock, false)) { - analyzeOnly = true; - analyzeTerminate = true; - } - if (point.split) { - ++(*forkBudget); - ++forkDepth; - } - analyzer->assume(condTok, true, Analyzer::Assume::Pending); - Branch branch = walkBranch(endBlock, depth, !point.split); - branch.condTok = condTok; - branch.falseAtEnd = !point.split && std::all_of(branch.paths.cbegin(), branch.paths.cend(), [&](const Path& p) { - const std::pair check = evalCond(*p.analyzer, condTok, endBlock->previous()); - return !check.first && check.second; - }); - return branch; + Outcome paths = std::move(parted); + paths.stop(actions, terminate); + *this = std::move(ft); + parted = std::move(paths); } - // Walk the incoming path where no condition of the alternatives holds. endBlock is the block - // for that, if any. The path goes on after forkEnd. - Branch walkRest(const ForkPoint& point, - Path incoming, - const std::vector& alternatives, - Token* endBlock, - const Token* forkEnd, - int depth) + // Neither outcome of the condition is known: the then block is walked on a fork, the else + // block on this traversal. split: the then path goes on to the end of the range on its own. + // Otherwise one path goes on past the if for both. + Progress updateBothBranches(const Token* condTok, Token* thenEnd, Token* elseEnd, const Token* end, int depth, bool split) { - path() = std::move(incoming); - const unsigned int pending = endBlock ? Analyzer::Assume::Pending : Analyzer::Assume::None; - bool assumed = false; - for (const Branch& alt : alternatives) { - actions |= alt.action; - // The condition is an assumption on this path if the alternative drops the value. If - // its paths go on past the fork the value is the same with and without it. Otherwise - // this path stands for the alternative as well and records that the condition is - // false only if that holds on both. With a block the state is recorded after it. - if (alt.isDead()) - analyzer->assume(alt.condTok, false, Analyzer::Assume::None | pending); - else if (alt.reachesEnd && (point.split || alt.falseAtEnd)) - analyzer->assume(alt.condTok, false, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute | pending); - else - continue; - assumed = true; + const bool conditional = stopOnCondition(condTok); + const int outerBranchCount = branchCount; + Token* ifEnd = elseEnd ? elseEnd : thenEnd; + // The value only flows into the then block when the condition can split it; for an opaque + // or correlated condition (e.g. 'if (f(x))') it does not, so the fork is analyze-only: the + // block's effect is still tracked but nothing is reported in it. + ForwardTraversal ft = fork(!analyzer->updateScope(thenEnd, false)); + ft.actions = actions; + if (split) { + ++(*forkBudget); + ++ft.forkDepth; } - // An assumption records the state where the path goes on. Without one the state stays - // at an earlier token, and every condition evaluated later looks for changes from there. - if (!endBlock) { - if (!assumed && forkEnd->next()) - analyzer->updateState(forkEnd->next()); - Branch rest; - rest.paths.push_back(std::move(path())); - return rest; + ft.analyzer->assume(condTok, true, Analyzer::Assume::Pending); + const Branch thenBranch = ft.updateBranch(thenEnd, depth - 1); + actions |= thenBranch.action; + // A path that stopped in the then block is covered if this path goes on for it + Outcome thenStops = std::move(ft.parted); + ft.parted = Outcome{}; + if (!thenBranch.reachesEnd) + thenStops.stop(ft.actions, ft.terminate); + parted.add(thenStops, !split); + + // The condition is an assumption on this path if the then path drops the value. If the + // then path goes on past the if, the value is the same with and without it. Otherwise + // this path stands for the then path as well and records that the condition is false + // only if that holds on both (e.g. 'if (x > 5) x = 5;'). With an else block the state is + // recorded after it. + const unsigned int pending = elseEnd ? Analyzer::Assume::Pending : Analyzer::Assume::None; + bool assumed = true; + if (thenBranch.isDead()) + analyzer->assume(condTok, false, Analyzer::Assume::None | pending); + else if (thenBranch.reachesEnd && (split || ft.isConditionFalse(condTok, thenEnd->previous()))) + analyzer->assume(condTok, false, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute | pending); + else + assumed = false; + Branch elseBranch; + if (elseEnd) { + if (!assumed) + updateScopeState(elseEnd); + elseBranch = updateBranch(elseEnd, depth - 1); + if (elseBranch.reachesEnd) + analyzer->updateState(elseEnd->previous()); + } else if (!assumed && ifEnd->next()) { + // An assumption records the state where the path goes on. Without one the state stays + // at an earlier token, and every condition evaluated later looks for changes from there. + analyzer->updateState(ifEnd->next()); } - if (!assumed) - updateScopeState(endBlock); - Branch rest = walkBranch(endBlock, depth, false); - for (Path& p : rest.paths) - p.analyzer->updateState(endBlock->previous()); - return rest; - } - // Let the paths at the end of the branches go on after tok - Progress joinFork(const ForkPoint& point, std::vector alternatives, Branch rest, Token* tok) - { - std::vector branches{&rest}; - std::transform(alternatives.cbegin(), alternatives.cend(), std::back_inserter(branches), [](const Branch& alt) { - return &alt; - }); - const Analyzer::Action action = - std::accumulate(branches.cbegin(), branches.cend(), Analyzer::Action{Analyzer::Action::None}, [](Analyzer::Action a, const Branch* branch) { - return a | branch->action; - }); - const bool dead = std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isDead)); - const bool jumps = std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::hasGoto)); - std::vector paths; - for (Branch& alt : alternatives) { - for (Path& p : alt.paths) { - path() = std::move(p); - actions |= action; - if (jumps) { - stopPath(Analyzer::Terminate::Bail); - } else if (alt.isEscape()) { - stopPath(Analyzer::Terminate::Escape); - } else if (!point.split) { - // The rest goes on for this path. If the rest stopped, nothing does. - if (!rest.reachesEnd) - stopPath(); - } else if (!lowerAfterBranches(*analyzer, branches)) { - stopPath(); - } else { - // The branch limit counts the branches on the way past the fork, as it does - // for the rest - branchCount = point.branchCount; - // Anchor the state (and the block's assignments) at the block end - analyzer->assume(alt.condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute); - paths.push_back(std::move(path())); - } - } + const bool jumps = thenBranch.hasGoto() || elseBranch.hasGoto(); + Progress progress = elseBranch.reachesEnd ? Progress::Continue : Progress::Break; + if (progress != Progress::Break) { + if ((thenBranch.isDead() || elseBranch.isDead()) && conditional && stopUpdates()) + progress = Break(Analyzer::Terminate::Conditional); + else if (!lowerAfterBranches(*analyzer, thenBranch, elseBranch) || jumps) + progress = Break(Analyzer::Terminate::Bail); } - for (Path& p : rest.paths) { - path() = std::move(p); - actions |= action; - if (dead && point.conditional && stopUpdates()) - stopPath(Analyzer::Terminate::Conditional); - else if (!lowerAfterBranches(*analyzer, branches)) - stopPath(Analyzer::Terminate::Bail); - else if (jumps) - stopPath(Analyzer::Terminate::Bail); - else - paths.push_back(std::move(path())); + if (!thenBranch.reachesEnd) + return progress; + // Without a split this path goes on for the then path. If it stopped, the then path + // goes on in its place. + const bool thenGoesOn = split || progress == Progress::Break; + ft.actions |= elseBranch.action; + if (jumps) { + stopFork(ft, Analyzer::Terminate::Bail); + } else if (thenBranch.isEscape()) { + stopFork(ft, Analyzer::Terminate::Escape); + } else if (thenGoesOn && !lowerAfterBranches(*ft.analyzer, thenBranch, elseBranch)) { + stopFork(ft); + } else if (thenGoesOn) { + // The branch limit counts the branches on the way past the if, as it does for this path + ft.branchCount = outerBranchCount; + // Anchor the state (and the block's assignments) at the block end + ft.analyzer->assume(condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute); + if (split) { + parted.join(ft.updatePaths(ifEnd->next(), end, depth - 1)); + } else { + replaceWith(std::move(ft)); + progress = Progress::Continue; + } } - return resume(std::move(paths), tok); - } - - // Neither outcome of the condition is known: walk each on its own paths - Progress forkIf(const Token* condTok, Token* thenEnd, Token* elseEnd, int depth) - { - const ForkPoint point = startFork(condTok); - Token* ifEnd = elseEnd ? elseEnd : thenEnd; - Path incoming = std::move(path()); - std::vector alternatives; - alternatives.push_back(walkAlternative(point, incoming, condTok, thenEnd, depth - 1)); - Branch rest = walkRest(point, std::move(incoming), alternatives, elseEnd, ifEnd, depth - 1); - return joinFork(point, std::move(alternatives), std::move(rest), ifEnd); + return progress; } bool reentersLoop(Token* endBlock, const Token* condTok, const Token* stepTok) const { @@ -928,65 +840,32 @@ namespace { return updateAllPaths(endBlock->link(), endBlock, depth); } - // This traversal goes on after the range, so the paths do not part for good in it: at a fork - // one path stands for every alternative. - Progress updateRange(Token* start, const Token* end, int depth = 20) { - Range walked = walkPaths(start, end, depth, false); - setResult(walked.outcome, end); - if (walked.reached.empty()) - return Progress::Break; - path() = std::move(walked.reached.front()); - return Progress::Continue; + // Walk this path and every path that parts from it to the end of the range + Outcome updatePaths(Token* start, const Token* end, int depth) + { + return outcome(updateRange(start, end, depth, true)); } - // Follow every path to the end of the range. This traversal gets their joint result and must - // not go on after the range. + // As updatePaths(), and this traversal gets the joint result of the paths. It must not go on + // after the range. Progress updateAllPaths(Token* start, const Token* end, int depth = 20) { - const Range walked = walkPaths(start, end, depth, true); - setResult(walked.outcome, end); - return walked.reached.empty() ? Progress::Break : Progress::Continue; - } - - void setResult(const Outcome& outcome, const Token* end) { + const Outcome paths = updatePaths(start, end, depth); // A path that stopped without an escape was not followed to one, but the code can show // that there is no way to the end of the range - const bool escapes = outcome.allEscape() || - (outcome.reached == 0 && outcome.hasEscape() && isReturnScope(end, settings().library)); - actions = outcome.action; - terminate = escapes ? Analyzer::Terminate::Escape : outcome.worst(); - } - - // Walk the path in the traversal and the paths that fork off it from start to end. No path is - // left in the traversal: the ones that go on are in the result. - Range walkPaths(Token* start, const Token* end, int depth, bool split) { - Range outer = std::move(range); - range = Range{}; - range.canSplit = split; - Token* tok = start; - for (;;) { - const Progress p = walkRange(tok, end, depth); - if (p == Progress::Continue) { - range.outcome.reach(actions); - range.reached.push_back(std::move(path())); - } else if (p == Progress::Break) { - range.outcome.stop(actions, terminate); - } - if (range.waiting.empty()) - break; - path() = std::move(range.waiting.back().first); - tok = range.waiting.back().second; - range.waiting.pop_back(); - } - Range walked = std::move(range); - range = std::move(outer); - return walked; + const bool escapes = paths.allEscape() || + (paths.reached == 0 && paths.hasEscape() && isReturnScope(end, settings().library)); + actions = paths.action; + terminate = escapes ? Analyzer::Terminate::Escape : paths.worst(); + return paths.reached == 0 ? Progress::Break : Progress::Continue; } /** - * Walk the path in the traversal until it stops, reaches the end of the range or forks + * Walk this path from start to end. + * @param split the paths may part for good at an undecided if: nothing goes on after the + * range on this traversal. Otherwise one path has to stand for all of them at its end. * @throws InternalError thrown on cyclic analysis */ - Progress walkRange(Token* start, const Token* end, int depth) { + Progress updateRange(Token* start, const Token* end, int depth = 20, bool split = false) { if (depth < 0) return Break(Analyzer::Terminate::Bail); std::size_t i = 0; @@ -1148,12 +1027,15 @@ namespace { return Break(Analyzer::Terminate::Conditional); Token* elseEnd = Token::simpleMatch(endBlock, "} else {") ? endBlock->linkAt(2) : nullptr; tok = elseEnd ? elseEnd : endBlock; - if (!checkThen && !checkElse) - return forkIf(condTok, endBlock, elseEnd, depth); - const Progress p = - updateTakenBranch(checkThen ? endBlock : elseEnd, checkThen ? elseEnd : endBlock, condTok, tok, depth); - if (p != Progress::Continue) - return p; + if (checkThen) { + if (updateTakenBranch(endBlock, elseEnd, condTok, tok, depth) == Progress::Break) + return Break(); + } else if (checkElse) { + if (updateTakenBranch(elseEnd, endBlock, condTok, tok, depth) == Progress::Break) + return Break(); + } else if (updateBothBranches(condTok, endBlock, elseEnd, end, depth, split && canFork()) == Progress::Break) { + return Break(); + } } } else if (Token::simpleMatch(tok, "try {")) { Token* endBlock = tok->linkAt(1); @@ -1302,7 +1184,7 @@ Analyzer::Result valueFlowGenericForward(Token* start, const Token* end, const V if (start) ft.analyzer->updateState(start); ft.updateAllPaths(start, end); - return Analyzer::Result{ft.actions, ft.terminate}; + return Analyzer::Result{ ft.actions, ft.terminate }; } Analyzer::Result valueFlowGenericForward(Token* start, const ValuePtr& a, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings) diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index eb0b1df8300..c8d9d9c42ce 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -4662,6 +4662,30 @@ class TestValueFlow : public TestFixture { ASSERT_EQUALS(true, testValueOfX(code, 4U, 1)); ASSERT_EQUALS(false, testValueOfX(code, 5U, 1)); + // inside a block one path goes on past the if: the then path, as the else path stopped + code = "void f(int n, bool d) {\n" + " int x = 1;\n" + " if (d) {\n" + " if (n > 5) { n = 5; } else { return; }\n" + " if (n == 5) { int a = x; }\n" + " if (n != 5) { int b = x; }\n" + " }\n" + " int c = x;\n" + "}\n"; + ASSERT_EQUALS(true, testValueOfX(code, 5U, 1)); + ASSERT_EQUALS(false, testValueOfX(code, 6U, 1)); + ASSERT_EQUALS(true, testValueOfXKnown(code, 8U, 1)); + + code = "void f(int n, bool d) {\n" + " int x = 1;\n" + " while (d) {\n" + " if (n > 5) {} else { return; }\n" + " int a = x;\n" + " d = g();\n" + " }\n" + "}\n"; + ASSERT_EQUALS(true, testValueOfX(code, 5U, 1)); + // the main path continues with the else block's assignments (then escapes) code = "void f(int n) {\n" " int x = 1;\n" From 1031954eca03aeba035d00ef4ef161520a9db677 Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 28 Nov 2026 22:05:28 -0600 Subject: [PATCH 04/12] Handle a list of branches --- lib/forwardanalyzer.cpp | 119 +++++++++++++++++++++++++--------------- 1 file changed, 74 insertions(+), 45 deletions(-) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 7ee59a67630..37869e6f7a9 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -40,6 +40,7 @@ #include #include #include +#include #include #include #include @@ -155,6 +156,10 @@ namespace { bool escapeUnknown = false; // The path that walked the block is at its end bool reachesEnd = true; + // The fork that walked the block, and the condition that holds on it. Without a fork + // this traversal walked the block. + std::shared_ptr path; + const Token* condTok = nullptr; bool isEscape() const { return escape || escapeUnknown; } @@ -424,12 +429,13 @@ namespace { return (depthLimit < 0 || forkDepth < depthLimit) && (budgetLimit < 0 || *forkBudget < budgetLimit); } - // A value changed in either branch is only possible past the if, on both paths. False if - // it cannot be lowered. - static bool lowerAfterBranches(Analyzer& a, const Branch& thenBranch, const Branch& elseBranch) { - if ((thenBranch.isModified() || elseBranch.isModified()) && !a.lowerToPossible()) + // A value changed in one of the branches is only possible past them, on every path. False + // if it cannot be lowered. + static bool lowerAfterBranches(Analyzer& a, const std::vector& branches) { + if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isModified)) && !a.lowerToPossible()) return false; - if ((thenBranch.isInconclusive() || elseBranch.isInconclusive()) && !a.lowerToInconclusive()) + if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isInconclusive)) && + !a.lowerToInconclusive()) return false; return true; } @@ -576,30 +582,32 @@ namespace { } // Neither outcome of the condition is known: the then block is walked on a fork, the else - // block on this traversal. split: the then path goes on to the end of the range on its own. - // Otherwise one path goes on past the if for both. + // block on this traversal. Progress updateBothBranches(const Token* condTok, Token* thenEnd, Token* elseEnd, const Token* end, int depth, bool split) { const bool conditional = stopOnCondition(condTok); - const int outerBranchCount = branchCount; Token* ifEnd = elseEnd ? elseEnd : thenEnd; // The value only flows into the then block when the condition can split it; for an opaque // or correlated condition (e.g. 'if (f(x))') it does not, so the fork is analyze-only: the // block's effect is still tracked but nothing is reported in it. - ForwardTraversal ft = fork(!analyzer->updateScope(thenEnd, false)); - ft.actions = actions; + const std::shared_ptr ft = + std::make_shared(fork(!analyzer->updateScope(thenEnd, false))); + ft->actions = actions; if (split) { ++(*forkBudget); - ++ft.forkDepth; + ++ft->forkDepth; } - ft.analyzer->assume(condTok, true, Analyzer::Assume::Pending); - const Branch thenBranch = ft.updateBranch(thenEnd, depth - 1); - actions |= thenBranch.action; + ft->analyzer->assume(condTok, true, Analyzer::Assume::Pending); + Branch thenBranch = ft->updateBranch(thenEnd, depth - 1); + thenBranch.path = ft; + thenBranch.condTok = condTok; + // The branch limit counts the branches on the way past the if, as it does for this path + ft->branchCount = branchCount; // A path that stopped in the then block is covered if this path goes on for it - Outcome thenStops = std::move(ft.parted); - ft.parted = Outcome{}; + Outcome thenStops = std::move(ft->parted); + ft->parted = Outcome{}; if (!thenBranch.reachesEnd) - thenStops.stop(ft.actions, ft.terminate); + thenStops.stop(ft->actions, ft->terminate); parted.add(thenStops, !split); // The condition is an assumption on this path if the then path drops the value. If the @@ -611,7 +619,7 @@ namespace { bool assumed = true; if (thenBranch.isDead()) analyzer->assume(condTok, false, Analyzer::Assume::None | pending); - else if (thenBranch.reachesEnd && (split || ft.isConditionFalse(condTok, thenEnd->previous()))) + else if (thenBranch.reachesEnd && (split || ft->isConditionFalse(condTok, thenEnd->previous()))) analyzer->assume(condTok, false, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute | pending); else assumed = false; @@ -627,39 +635,60 @@ namespace { // at an earlier token, and every condition evaluated later looks for changes from there. analyzer->updateState(ifEnd->next()); } + return updatePastBranches({thenBranch, elseBranch}, conditional, ifEnd->next(), end, depth, split); + } - const bool jumps = thenBranch.hasGoto() || elseBranch.hasGoto(); - Progress progress = elseBranch.reachesEnd ? Progress::Continue : Progress::Break; - if (progress != Progress::Break) { - if ((thenBranch.isDead() || elseBranch.isDead()) && conditional && stopUpdates()) + // The blocks of a branching statement were walked, each on its fork or on this traversal. + // split: every path goes on to the end of the range on its own. Otherwise one path goes on + // past the statement for all of them. + Progress updatePastBranches(const std::vector& branches, bool conditional, Token* next, const Token* end, int depth, bool split) + { + const Analyzer::Action action = + std::accumulate(branches.cbegin(), branches.cend(), Analyzer::Action{}, [](Analyzer::Action a, const Branch& branch) { + return a | branch.action; + }); + actions |= action; + const bool jumps = std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::hasGoto)); + const bool reachesEnd = std::all_of(branches.cbegin(), branches.cend(), [](const Branch& branch) { + return branch.path || branch.reachesEnd; + }); + Progress progress = reachesEnd ? Progress::Continue : Progress::Break; + if (reachesEnd) { + if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isDead)) && conditional && stopUpdates()) progress = Break(Analyzer::Terminate::Conditional); - else if (!lowerAfterBranches(*analyzer, thenBranch, elseBranch) || jumps) + else if (!lowerAfterBranches(*analyzer, branches) || jumps) progress = Break(Analyzer::Terminate::Bail); } - if (!thenBranch.reachesEnd) - return progress; - // Without a split this path goes on for the then path. If it stopped, the then path - // goes on in its place. - const bool thenGoesOn = split || progress == Progress::Break; - ft.actions |= elseBranch.action; - if (jumps) { - stopFork(ft, Analyzer::Terminate::Bail); - } else if (thenBranch.isEscape()) { - stopFork(ft, Analyzer::Terminate::Escape); - } else if (thenGoesOn && !lowerAfterBranches(*ft.analyzer, thenBranch, elseBranch)) { - stopFork(ft); - } else if (thenGoesOn) { - // The branch limit counts the branches on the way past the if, as it does for this path - ft.branchCount = outerBranchCount; - // Anchor the state (and the block's assignments) at the block end - ft.analyzer->assume(condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute); - if (split) { - parted.join(ft.updatePaths(ifEnd->next(), end, depth - 1)); - } else { - replaceWith(std::move(ft)); - progress = Progress::Continue; + // Without a split this path goes on for the forks. If it stopped, a fork goes on in its place. + const bool forksGoOn = split || progress == Progress::Break; + std::vector successors; + for (const Branch& branch : branches) { + if (!branch.path || !branch.reachesEnd) + continue; + ForwardTraversal& ft = *branch.path; + ft.actions |= action; + if (jumps) { + stopFork(ft, Analyzer::Terminate::Bail); + } else if (branch.isEscape()) { + stopFork(ft, Analyzer::Terminate::Escape); + } else if (forksGoOn && !lowerAfterBranches(*ft.analyzer, branches)) { + stopFork(ft); + } else if (forksGoOn) { + // Anchor the state (and the block's assignments) at the block end + ft.analyzer->assume(branch.condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute); + if (split) + parted.join(ft.updatePaths(next, end, depth - 1)); + else + successors.push_back(&ft); } } + // Each fork holds its own condition, so one of several cannot go on for the others + if (successors.size() == 1) { + replaceWith(std::move(*successors.front())); + return Progress::Continue; + } + for (ForwardTraversal* ft : successors) + stopFork(*ft, Analyzer::Terminate::Bail); return progress; } From 903694a640e8a3be301cd54fbd90f415f1eaa4f5 Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 28 Nov 2026 22:14:33 -0600 Subject: [PATCH 05/12] Make the variable names clearer --- lib/forwardanalyzer.cpp | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 37869e6f7a9..a387e3347e0 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -156,9 +156,9 @@ namespace { bool escapeUnknown = false; // The path that walked the block is at its end bool reachesEnd = true; - // The fork that walked the block, and the condition that holds on it. Without a fork - // this traversal walked the block. - std::shared_ptr path; + // The traversal that walked the block + ForwardTraversal* traversal = nullptr; + // The condition that holds on it, if it is a fork const Token* condTok = nullptr; bool isEscape() const { return escape || escapeUnknown; @@ -590,24 +590,23 @@ namespace { // The value only flows into the then block when the condition can split it; for an opaque // or correlated condition (e.g. 'if (f(x))') it does not, so the fork is analyze-only: the // block's effect is still tracked but nothing is reported in it. - const std::shared_ptr ft = - std::make_shared(fork(!analyzer->updateScope(thenEnd, false))); - ft->actions = actions; + ForwardTraversal ft = fork(!analyzer->updateScope(thenEnd, false)); + ft.actions = actions; if (split) { ++(*forkBudget); - ++ft->forkDepth; + ++ft.forkDepth; } - ft->analyzer->assume(condTok, true, Analyzer::Assume::Pending); - Branch thenBranch = ft->updateBranch(thenEnd, depth - 1); - thenBranch.path = ft; + ft.analyzer->assume(condTok, true, Analyzer::Assume::Pending); + Branch thenBranch = ft.updateBranch(thenEnd, depth - 1); + thenBranch.traversal = &ft; thenBranch.condTok = condTok; // The branch limit counts the branches on the way past the if, as it does for this path - ft->branchCount = branchCount; + ft.branchCount = branchCount; // A path that stopped in the then block is covered if this path goes on for it - Outcome thenStops = std::move(ft->parted); - ft->parted = Outcome{}; + Outcome thenStops = std::move(ft.parted); + ft.parted = Outcome{}; if (!thenBranch.reachesEnd) - thenStops.stop(ft->actions, ft->terminate); + thenStops.stop(ft.actions, ft.terminate); parted.add(thenStops, !split); // The condition is an assumption on this path if the then path drops the value. If the @@ -619,7 +618,7 @@ namespace { bool assumed = true; if (thenBranch.isDead()) analyzer->assume(condTok, false, Analyzer::Assume::None | pending); - else if (thenBranch.reachesEnd && (split || ft->isConditionFalse(condTok, thenEnd->previous()))) + else if (thenBranch.reachesEnd && (split || ft.isConditionFalse(condTok, thenEnd->previous()))) analyzer->assume(condTok, false, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute | pending); else assumed = false; @@ -635,10 +634,11 @@ namespace { // at an earlier token, and every condition evaluated later looks for changes from there. analyzer->updateState(ifEnd->next()); } + elseBranch.traversal = this; return updatePastBranches({thenBranch, elseBranch}, conditional, ifEnd->next(), end, depth, split); } - // The blocks of a branching statement were walked, each on its fork or on this traversal. + // The blocks of a branching statement were walked, each on a fork or on this traversal. // split: every path goes on to the end of the range on its own. Otherwise one path goes on // past the statement for all of them. Progress updatePastBranches(const std::vector& branches, bool conditional, Token* next, const Token* end, int depth, bool split) @@ -649,8 +649,8 @@ namespace { }); actions |= action; const bool jumps = std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::hasGoto)); - const bool reachesEnd = std::all_of(branches.cbegin(), branches.cend(), [](const Branch& branch) { - return branch.path || branch.reachesEnd; + const bool reachesEnd = std::all_of(branches.cbegin(), branches.cend(), [this](const Branch& branch) { + return branch.traversal != this || branch.reachesEnd; }); Progress progress = reachesEnd ? Progress::Continue : Progress::Break; if (reachesEnd) { @@ -663,9 +663,9 @@ namespace { const bool forksGoOn = split || progress == Progress::Break; std::vector successors; for (const Branch& branch : branches) { - if (!branch.path || !branch.reachesEnd) + if (branch.traversal == this || !branch.reachesEnd) continue; - ForwardTraversal& ft = *branch.path; + ForwardTraversal& ft = *branch.traversal; ft.actions |= action; if (jumps) { stopFork(ft, Analyzer::Terminate::Bail); From 2c0bdae7951f6c56974a7b943374bf6ee7c831c3 Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 28 Nov 2026 22:21:18 -0600 Subject: [PATCH 06/12] Simplify --- lib/forwardanalyzer.cpp | 59 ++++++++++++++++++++++------------------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index a387e3347e0..739d47c0ac7 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -506,15 +506,11 @@ namespace { Outcome outer = std::move(parted); parted = Outcome{}; const Progress p = updateRange(endBlock->link(), endBlock, depth); - const Branch branch = resolve(endBlock, outcome(p)); + const Outcome paths = outcome(p); outer.add(parted, false); parted = std::move(outer); actions |= outerActions; - return branch; - } - Branch resolve(Token* endBlock, const Outcome& paths) const - { Branch branch{endBlock}; branch.action = paths.action; branch.reachesEnd = paths.reached > 0; @@ -528,13 +524,13 @@ namespace { branch.escapeUnknown = !structuralEscape || structuralUnknown; if (branch.escapeUnknown) branch.action |= analyzeScope(endBlock); - return branch; + } else { + // Detect an escape the paths did not flag (e.g. an unknown noreturn call); + // escapeUnknown reports a possible (unknown) escape. + branch.escape = isEscapeScope(endBlock, branch.escapeUnknown); + if (paths.unwalked()) + branch.action |= analyzeScope(endBlock); } - // Detect an escape the paths did not flag (e.g. an unknown noreturn call); - // escapeUnknown reports a possible (unknown) escape. - branch.escape = isEscapeScope(endBlock, branch.escapeUnknown); - if (paths.unwalked()) - branch.action |= analyzeScope(endBlock); return branch; } @@ -581,6 +577,29 @@ namespace { parted = std::move(paths); } + // Walk a block on a fork of this traversal, on which the condition holds + Branch updateForkedBranch(ForwardTraversal& ft, const Token* condTok, Token* endBlock, int depth, bool split) + { + ft.actions = actions; + if (split) { + ++(*forkBudget); + ++ft.forkDepth; + } + ft.analyzer->assume(condTok, true, Analyzer::Assume::Pending); + Branch branch = ft.updateBranch(endBlock, depth); + branch.traversal = &ft; + branch.condTok = condTok; + // The branch limit counts the branches on the way past the block, as it does for this path + ft.branchCount = branchCount; + // A path that stopped in the block is covered if this path goes on for it + Outcome stops = std::move(ft.parted); + ft.parted = Outcome{}; + if (!branch.reachesEnd) + stops.stop(ft.actions, ft.terminate); + parted.add(stops, !split); + return branch; + } + // Neither outcome of the condition is known: the then block is walked on a fork, the else // block on this traversal. Progress updateBothBranches(const Token* condTok, Token* thenEnd, Token* elseEnd, const Token* end, int depth, bool split) @@ -591,23 +610,7 @@ namespace { // or correlated condition (e.g. 'if (f(x))') it does not, so the fork is analyze-only: the // block's effect is still tracked but nothing is reported in it. ForwardTraversal ft = fork(!analyzer->updateScope(thenEnd, false)); - ft.actions = actions; - if (split) { - ++(*forkBudget); - ++ft.forkDepth; - } - ft.analyzer->assume(condTok, true, Analyzer::Assume::Pending); - Branch thenBranch = ft.updateBranch(thenEnd, depth - 1); - thenBranch.traversal = &ft; - thenBranch.condTok = condTok; - // The branch limit counts the branches on the way past the if, as it does for this path - ft.branchCount = branchCount; - // A path that stopped in the then block is covered if this path goes on for it - Outcome thenStops = std::move(ft.parted); - ft.parted = Outcome{}; - if (!thenBranch.reachesEnd) - thenStops.stop(ft.actions, ft.terminate); - parted.add(thenStops, !split); + const Branch thenBranch = updateForkedBranch(ft, condTok, thenEnd, depth - 1, split); // The condition is an assumption on this path if the then path drops the value. If the // then path goes on past the if, the value is the same with and without it. Otherwise From 4d4426e0cdf7280d199620673d0ad16c42dc6f54 Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 28 Nov 2026 22:27:29 -0600 Subject: [PATCH 07/12] Add the rename --- lib/forwardanalyzer.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 739d47c0ac7..9b760599d1d 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -638,13 +638,13 @@ namespace { analyzer->updateState(ifEnd->next()); } elseBranch.traversal = this; - return updatePastBranches({thenBranch, elseBranch}, conditional, ifEnd->next(), end, depth, split); + return continueAfterBranches({thenBranch, elseBranch}, conditional, ifEnd->next(), end, depth, split); } // The blocks of a branching statement were walked, each on a fork or on this traversal. - // split: every path goes on to the end of the range on its own. Otherwise one path goes on - // past the statement for all of them. - Progress updatePastBranches(const std::vector& branches, bool conditional, Token* next, const Token* end, int depth, bool split) + // Decide which of the paths go on past the statement. split: every path goes on to the end + // of the range on its own. Otherwise one path goes on for all of them. + Progress continueAfterBranches(const std::vector& branches, bool conditional, Token* next, const Token* end, int depth, bool split) { const Analyzer::Action action = std::accumulate(branches.cbegin(), branches.cend(), Analyzer::Action{}, [](Analyzer::Action a, const Branch& branch) { From 7895bd3d37038eafea75f4af287dea57cead0319 Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 28 Nov 2026 22:42:45 -0600 Subject: [PATCH 08/12] Rename --- lib/forwardanalyzer.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 9b760599d1d..293a3849c8c 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -534,8 +534,8 @@ namespace { return branch; } - // Walk the block that the evaluated condition takes - Progress updateTakenBranch(Token* endBlock, const Token* skippedBlock, const Token* condTok, const Token* ifEnd, int depth) + // The condition was evaluated: walk the one block of the if that it selects + Progress updateSingleIfBranch(Token* endBlock, const Token* skippedBlock, const Token* condTok, const Token* ifEnd, int depth) { // The condition is only "known" because of an earlier assumption, so the // skipped block could still modify the value -> lower to possible @@ -602,7 +602,7 @@ namespace { // Neither outcome of the condition is known: the then block is walked on a fork, the else // block on this traversal. - Progress updateBothBranches(const Token* condTok, Token* thenEnd, Token* elseEnd, const Token* end, int depth, bool split) + Progress updateIfBranches(const Token* condTok, Token* thenEnd, Token* elseEnd, const Token* end, int depth, bool split) { const bool conditional = stopOnCondition(condTok); Token* ifEnd = elseEnd ? elseEnd : thenEnd; @@ -1060,12 +1060,12 @@ namespace { Token* elseEnd = Token::simpleMatch(endBlock, "} else {") ? endBlock->linkAt(2) : nullptr; tok = elseEnd ? elseEnd : endBlock; if (checkThen) { - if (updateTakenBranch(endBlock, elseEnd, condTok, tok, depth) == Progress::Break) + if (updateSingleIfBranch(endBlock, elseEnd, condTok, tok, depth) == Progress::Break) return Break(); } else if (checkElse) { - if (updateTakenBranch(elseEnd, endBlock, condTok, tok, depth) == Progress::Break) + if (updateSingleIfBranch(elseEnd, endBlock, condTok, tok, depth) == Progress::Break) return Break(); - } else if (updateBothBranches(condTok, endBlock, elseEnd, end, depth, split && canFork()) == Progress::Break) { + } else if (updateIfBranches(condTok, endBlock, elseEnd, end, depth, split && canFork()) == Progress::Break) { return Break(); } } From 27b81e6ba93c842c0c19239d8c6f67f9aa1622fa Mon Sep 17 00:00:00 2001 From: Paul Date: Sun, 29 Nov 2026 14:58:29 -0600 Subject: [PATCH 09/12] Improve forking limit --- lib/forwardanalyzer.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 293a3849c8c..7a9699f29d8 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -591,6 +591,10 @@ namespace { branch.condTok = condTok; // The branch limit counts the branches on the way past the block, as it does for this path ft.branchCount = branchCount; + // A fork that does not split uses up the fork limit as well. Otherwise the whole limit is + // left for the forks that walk to the end of the range, which are the expensive ones. + if (!split && branch.reachesEnd && canFork()) + ++(*forkBudget); // A path that stopped in the block is covered if this path goes on for it Outcome stops = std::move(ft.parted); ft.parted = Outcome{}; From 7736b29c9ac137e28a10e79a9008aeb839ad86a3 Mon Sep 17 00:00:00 2001 From: Paul Date: Sun, 29 Nov 2026 15:04:26 -0600 Subject: [PATCH 10/12] Make depth the last parameter --- lib/forwardanalyzer.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 7a9699f29d8..f784251391f 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -505,7 +505,7 @@ namespace { actions = Analyzer::Action::None; Outcome outer = std::move(parted); parted = Outcome{}; - const Progress p = updateRange(endBlock->link(), endBlock, depth); + const Progress p = updateRange(endBlock->link(), endBlock, false, depth); const Outcome paths = outcome(p); outer.add(parted, false); parted = std::move(outer); @@ -578,7 +578,7 @@ namespace { } // Walk a block on a fork of this traversal, on which the condition holds - Branch updateForkedBranch(ForwardTraversal& ft, const Token* condTok, Token* endBlock, int depth, bool split) + Branch updateForkedBranch(ForwardTraversal& ft, const Token* condTok, Token* endBlock, bool split, int depth) { ft.actions = actions; if (split) { @@ -606,7 +606,7 @@ namespace { // Neither outcome of the condition is known: the then block is walked on a fork, the else // block on this traversal. - Progress updateIfBranches(const Token* condTok, Token* thenEnd, Token* elseEnd, const Token* end, int depth, bool split) + Progress updateIfBranches(const Token* condTok, Token* thenEnd, Token* elseEnd, const Token* end, bool split, int depth) { const bool conditional = stopOnCondition(condTok); Token* ifEnd = elseEnd ? elseEnd : thenEnd; @@ -614,7 +614,7 @@ namespace { // or correlated condition (e.g. 'if (f(x))') it does not, so the fork is analyze-only: the // block's effect is still tracked but nothing is reported in it. ForwardTraversal ft = fork(!analyzer->updateScope(thenEnd, false)); - const Branch thenBranch = updateForkedBranch(ft, condTok, thenEnd, depth - 1, split); + const Branch thenBranch = updateForkedBranch(ft, condTok, thenEnd, split, depth - 1); // The condition is an assumption on this path if the then path drops the value. If the // then path goes on past the if, the value is the same with and without it. Otherwise @@ -642,13 +642,13 @@ namespace { analyzer->updateState(ifEnd->next()); } elseBranch.traversal = this; - return continueAfterBranches({thenBranch, elseBranch}, conditional, ifEnd->next(), end, depth, split); + return continueAfterBranches({thenBranch, elseBranch}, conditional, ifEnd->next(), end, split, depth); } // The blocks of a branching statement were walked, each on a fork or on this traversal. // Decide which of the paths go on past the statement. split: every path goes on to the end // of the range on its own. Otherwise one path goes on for all of them. - Progress continueAfterBranches(const std::vector& branches, bool conditional, Token* next, const Token* end, int depth, bool split) + Progress continueAfterBranches(const std::vector& branches, bool conditional, Token* next, const Token* end, bool split, int depth) { const Analyzer::Action action = std::accumulate(branches.cbegin(), branches.cend(), Analyzer::Action{}, [](Analyzer::Action a, const Branch& branch) { @@ -865,7 +865,7 @@ namespace { if (!endBlock) return Break(); updateScopeState(endBlock); - return updateRange(endBlock->link(), endBlock, depth); + return updateRange(endBlock->link(), endBlock, false, depth); } Progress updateAllScopePaths(Token* endBlock, int depth = 20) @@ -879,7 +879,7 @@ namespace { // Walk this path and every path that parts from it to the end of the range Outcome updatePaths(Token* start, const Token* end, int depth) { - return outcome(updateRange(start, end, depth, true)); + return outcome(updateRange(start, end, true, depth)); } // As updatePaths(), and this traversal gets the joint result of the paths. It must not go on @@ -901,7 +901,7 @@ namespace { * range on this traversal. Otherwise one path has to stand for all of them at its end. * @throws InternalError thrown on cyclic analysis */ - Progress updateRange(Token* start, const Token* end, int depth = 20, bool split = false) { + Progress updateRange(Token* start, const Token* end, bool split, int depth = 20) { if (depth < 0) return Break(Analyzer::Terminate::Bail); std::size_t i = 0; @@ -1069,7 +1069,7 @@ namespace { } else if (checkElse) { if (updateSingleIfBranch(elseEnd, endBlock, condTok, tok, depth) == Progress::Break) return Break(); - } else if (updateIfBranches(condTok, endBlock, elseEnd, end, depth, split && canFork()) == Progress::Break) { + } else if (updateIfBranches(condTok, endBlock, elseEnd, end, split && canFork(), depth) == Progress::Break) { return Break(); } } @@ -1124,7 +1124,7 @@ namespace { return Break(); // Since the call could be an unknown macro, traverse the tokens as a range instead of recursively if (!Token::simpleMatch(callTok, "( )") && - updateRange(callTok->next(), callTok->link(), depth - 1) == Progress::Break) + updateRange(callTok->next(), callTok->link(), false, depth - 1) == Progress::Break) return Break(); if (updateTok(callTok) == Progress::Break) return Break(); From e3280470c2547aba8d29bc6881a7327ec11c1557 Mon Sep 17 00:00:00 2001 From: Paul Date: Sun, 29 Nov 2026 15:44:04 -0600 Subject: [PATCH 11/12] Simplify --- lib/forwardanalyzer.cpp | 37 ++++++++++++++++++------------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index f784251391f..c14d1bd314e 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -34,7 +34,6 @@ #include #include -#include #include #include #include @@ -87,11 +86,12 @@ namespace { reached += paths.reached; } bool hasEscape() const { - return std::find(stops.cbegin(), stops.cend(), Analyzer::Terminate::Escape) != stops.cend(); + return contains(stops, Analyzer::Terminate::Escape); } bool allEscape() const { - return reached == 0 && !stops.empty() && - std::count(stops.cbegin(), stops.cend(), Analyzer::Terminate::Escape) == static_cast(stops.size()); + return reached == 0 && !stops.empty() && std::all_of(stops.cbegin(), stops.cend(), [](Analyzer::Terminate t) { + return t == Analyzer::Terminate::Escape; + }); } Analyzer::Terminate worst() const { Analyzer::Terminate result = Analyzer::Terminate::None; @@ -535,7 +535,7 @@ namespace { } // The condition was evaluated: walk the one block of the if that it selects - Progress updateSingleIfBranch(Token* endBlock, const Token* skippedBlock, const Token* condTok, const Token* ifEnd, int depth) + Progress updateSingleIfBranch(Token* endBlock, const Token* skippedBlock, const Token* condTok, int depth) { // The condition is only "known" because of an earlier assumption, so the // skipped block could still modify the value -> lower to possible @@ -545,8 +545,8 @@ namespace { if (!endBlock) { // Record the state past the skipped block, so that the conditions evaluated later do // not each look for changes in it - if (ifEnd->next()) - analyzer->updateState(ifEnd->next()); + if (skippedBlock->next()) + analyzer->updateState(skippedBlock->next()); return Progress::Continue; } updateScopeState(endBlock); @@ -606,9 +606,8 @@ namespace { // Neither outcome of the condition is known: the then block is walked on a fork, the else // block on this traversal. - Progress updateIfBranches(const Token* condTok, Token* thenEnd, Token* elseEnd, const Token* end, bool split, int depth) + Progress updateIfBranches(const Token* condTok, Token* thenEnd, Token* elseEnd, const Token* end, bool conditional, bool split, int depth) { - const bool conditional = stopOnCondition(condTok); Token* ifEnd = elseEnd ? elseEnd : thenEnd; // The value only flows into the then block when the condition can split it; for an opaque // or correlated condition (e.g. 'if (f(x))') it does not, so the fork is analyze-only: the @@ -624,7 +623,7 @@ namespace { const unsigned int pending = elseEnd ? Analyzer::Assume::Pending : Analyzer::Assume::None; bool assumed = true; if (thenBranch.isDead()) - analyzer->assume(condTok, false, Analyzer::Assume::None | pending); + analyzer->assume(condTok, false, pending); else if (thenBranch.reachesEnd && (split || ft.isConditionFalse(condTok, thenEnd->previous()))) analyzer->assume(condTok, false, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute | pending); else @@ -868,12 +867,12 @@ namespace { return updateRange(endBlock->link(), endBlock, false, depth); } - Progress updateAllScopePaths(Token* endBlock, int depth = 20) + void updateAllScopePaths(Token* endBlock, int depth = 20) { if (!endBlock) - return Break(); + return; updateScopeState(endBlock); - return updateAllPaths(endBlock->link(), endBlock, depth); + updateAllPaths(endBlock->link(), endBlock, depth); } // Walk this path and every path that parts from it to the end of the range @@ -884,7 +883,7 @@ namespace { // As updatePaths(), and this traversal gets the joint result of the paths. It must not go on // after the range. - Progress updateAllPaths(Token* start, const Token* end, int depth = 20) { + void updateAllPaths(Token* start, const Token* end, int depth = 20) { const Outcome paths = updatePaths(start, end, depth); // A path that stopped without an escape was not followed to one, but the code can show // that there is no way to the end of the range @@ -892,7 +891,6 @@ namespace { (paths.reached == 0 && paths.hasEscape() && isReturnScope(end, settings().library)); actions = paths.action; terminate = escapes ? Analyzer::Terminate::Escape : paths.worst(); - return paths.reached == 0 ? Progress::Break : Progress::Continue; } /** @@ -1059,17 +1057,18 @@ namespace { // Check if condition is true or false bool checkThen, checkElse; std::tie(checkThen, checkElse) = evalCond(condTok); - if (!checkThen && !checkElse && stopOnCondition(condTok) && stopUpdates()) + const bool conditional = !checkThen && !checkElse && stopOnCondition(condTok); + if (conditional && stopUpdates()) return Break(Analyzer::Terminate::Conditional); Token* elseEnd = Token::simpleMatch(endBlock, "} else {") ? endBlock->linkAt(2) : nullptr; tok = elseEnd ? elseEnd : endBlock; if (checkThen) { - if (updateSingleIfBranch(endBlock, elseEnd, condTok, tok, depth) == Progress::Break) + if (updateSingleIfBranch(endBlock, elseEnd, condTok, depth) == Progress::Break) return Break(); } else if (checkElse) { - if (updateSingleIfBranch(elseEnd, endBlock, condTok, tok, depth) == Progress::Break) + if (updateSingleIfBranch(elseEnd, endBlock, condTok, depth) == Progress::Break) return Break(); - } else if (updateIfBranches(condTok, endBlock, elseEnd, end, split && canFork(), depth) == Progress::Break) { + } else if (updateIfBranches(condTok, endBlock, elseEnd, end, conditional, split && canFork(), depth) == Progress::Break) { return Break(); } } From 820153aa72276d7c06ef404354d9a3feae52e8d8 Mon Sep 17 00:00:00 2001 From: Paul Date: Sun, 29 Nov 2026 16:28:11 -0600 Subject: [PATCH 12/12] Fix FP with normal level --- lib/forwardanalyzer.cpp | 18 ++++++++++++------ test/testvalueflow.cpp | 23 +++++++++++++++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index c14d1bd314e..eb64d8c6e0d 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -160,6 +160,8 @@ namespace { ForwardTraversal* traversal = nullptr; // The condition that holds on it, if it is a fork const Token* condTok = nullptr; + // The paths that stopped in the block, if it was walked on a fork + Outcome stoppedPaths; bool isEscape() const { return escape || escapeUnknown; } @@ -578,7 +580,7 @@ namespace { } // Walk a block on a fork of this traversal, on which the condition holds - Branch updateForkedBranch(ForwardTraversal& ft, const Token* condTok, Token* endBlock, bool split, int depth) + Branch updateForkedBranch(ForwardTraversal& ft, const Token* condTok, Token* endBlock, bool split, int depth) const { ft.actions = actions; if (split) { @@ -595,12 +597,10 @@ namespace { // left for the forks that walk to the end of the range, which are the expensive ones. if (!split && branch.reachesEnd && canFork()) ++(*forkBudget); - // A path that stopped in the block is covered if this path goes on for it - Outcome stops = std::move(ft.parted); + branch.stoppedPaths = std::move(ft.parted); ft.parted = Outcome{}; if (!branch.reachesEnd) - stops.stop(ft.actions, ft.terminate); - parted.add(stops, !split); + branch.stoppedPaths.stop(ft.actions, ft.terminate); return branch; } @@ -689,7 +689,13 @@ namespace { } } // Each fork holds its own condition, so one of several cannot go on for the others - if (successors.size() == 1) { + const bool replaced = successors.size() == 1; + // A path that stopped in a block is covered only if a path goes on for it past the + // statement. Otherwise nothing walks the code that follows on its way. + const bool covered = !split && (replaced || progress == Progress::Continue); + for (const Branch& branch : branches) + parted.add(branch.stoppedPaths, covered); + if (replaced) { replaceWith(std::move(*successors.front())); return Progress::Continue; } diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index c8d9d9c42ce..5d02b90276d 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -4811,6 +4811,29 @@ class TestValueFlow : public TestFixture { " if (w) { int a = x; }\n" "}\n"; ASSERT_EQUALS(true, testValueOfX(code, 6U, 1, &s)); + + // the path through 'if (c)' stops at the branch limit and the other path returns, so no + // path walks 'x = 5' + const Settings normal = settingsBuilder(settings).checkLevel(Settings::CheckLevel::normal).build(); + code = "void use();\n" + "void f(bool o, bool c, bool d1, bool d2, bool d3, bool d4) {\n" + " int x = 0;\n" + " if (o) {\n" + " if (c) {\n" + " if (d1) { use(); }\n" + " if (d2) { use(); }\n" + " if (d3) { use(); }\n" + " if (d4) { use(); }\n" + " } else {\n" + " return;\n" + " }\n" + " x = 5;\n" + " }\n" + " if (x == 0) {}\n" + "}\n"; + const ValueFlow::Value value = valueOfTok(code, "x ==", &normal); + ASSERT_EQUALS(0, value.intvalue); + ASSERT(value.isPossible()); } void valueFlowForwardAfterCondition()