[clang] [llvm] [CSA] Add Unsequenced Variable Access Checker (PR #239272)

Áron Hárnási via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 5 07:56:22 PST 2026


https://github.com/ConcreteCactus created https://github.com/llvm/llvm-project/pull/239272

This checker will detect unsequenced variable accesses due to missing sequence points of happens-before relations. It will be able to detect violations even behind function calls or aliased variables.

>From ef93b4f57c8e2a340bce7581328695bc6dc24ba6 Mon Sep 17 00:00:00 2001
From: ConcreteCactus <aron.harnasi at gmail.com>
Date: Wed, 4 Nov 2026 15:25:19 +0100
Subject: [PATCH 01/12] VPlan: Add sequence point between getUID calls

Technically, if compiled with a pre-C++17 standard, the getUID
calls could be evaluated in a different order than written in
code. This could result in different UIDs being assigned to
different blocks.
---
 llvm/lib/Transforms/Vectorize/VPlan.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Transforms/Vectorize/VPlan.cpp b/llvm/lib/Transforms/Vectorize/VPlan.cpp
index f0e88bff63c252..b67295397fe2fe 100644
--- a/llvm/lib/Transforms/Vectorize/VPlan.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlan.cpp
@@ -1376,7 +1376,8 @@ void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
   // exiting basic block and the entry basic of the respective regions.
   const VPBlockBase *Tail = From->getExitingBasicBlock();
   const VPBlockBase *Head = To->getEntryBasicBlock();
-  OS << Indent << getUID(Tail) << " -> " << getUID(Head);
+  OS << Indent << getUID(Tail);
+  OS << " -> " << getUID(Head);
   OS << " [ label=\"" << Label << '\"';
   if (Tail != From)
     OS << " ltail=" << getUID(From);

>From 28c1ec2c1b65049eeb0c54bea359c368df080a8d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= <aron.harnasi at gmail.com>
Date: Sun, 6 Jul 2025 15:03:15 +0200
Subject: [PATCH 02/12] poc

---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   3 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt    |   1 +
 .../Checkers/UnsequencedAccessChecker.cpp     | 188 ++++++++++++++++++
 3 files changed, 192 insertions(+)
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 9905649801e85b..10189078db8d66 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -231,6 +231,9 @@ def NonnullGlobalConstantsChecker: Checker<"NonnilStringConstants">,
   Documentation<NotDocumented>,
   Hidden;
 
+def UnsequencedAccessChecker : Checker<"UnsequencedAccess">,
+   Documentation<NotDocumented>;
+
 } // end "core"
 
 let ParentPackage = CoreAlpha in {
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index f136bd5434113b..c6b9fa6cc44af6 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -129,6 +129,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   UninitializedObject/UninitializedPointee.cpp
   UnixAPIChecker.cpp
   UnreachableCodeChecker.cpp
+  UnsequencedAccessChecker.cpp
   UseAfterLifetimeEnd.cpp
   VforkChecker.cpp
   VLASizeChecker.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
new file mode 100644
index 00000000000000..dc41137454ac3a
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
@@ -0,0 +1,188 @@
+//=== UnsequencedAccessChecker.cpp - Unsequenced access checker ---*- C++ -*--//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defined a checker for finding unsequenced accesses on the same
+// memory region.
+//
+//===----------------------------------------------------------------------===//
+
+
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+
+#include "clang/AST/ParentMapContext.h"
+
+#include <iostream>
+
+using namespace clang;
+using namespace ento;
+
+using StmtVec = llvm::SmallVector<const Stmt*>;
+
+namespace {
+class UnsequencedAccessChecker
+    : public Checker<check::Location> {
+
+    static StmtVec getAllASTAncestors(const Stmt* CurrentS,
+                                      const StackFrameContext* CurrentFrame,
+                                      ParentMapContext& ParentMap);
+    static const Stmt* findCommonAncestor(const StmtVec& A, const StmtVec& B);
+
+    void reportBug(CheckerContext& C, const Stmt* A, const Stmt* B) const;
+
+    BugType BT{this, "Unsequenced-access", categories::LogicError};
+
+public:
+    void checkLocation(SVal Location, bool isLoad, const Stmt *S,
+                       CheckerContext &C) const;
+};
+
+class AccessStmt {
+    llvm::PointerIntPair<const Stmt*, 1, bool> StmtAndIsStore;
+    const StackFrameContext* StackFrame;
+    friend bool operator==(const AccessStmt& A, const AccessStmt& B);
+public:
+    AccessStmt(const Stmt* Stmt, bool isStore,
+               const StackFrameContext* StackFrame)
+        : StmtAndIsStore(Stmt, isStore), StackFrame(StackFrame) {}
+
+    bool isStore() const { return StmtAndIsStore.getInt(); }
+    const Stmt* getStmt() const { return StmtAndIsStore.getPointer(); }
+    const StackFrameContext* getFrame() const { return StackFrame; }
+
+    void Profile(llvm::FoldingSetNodeID &ID) const {
+        ID.AddBoolean(isStore());
+        ID.AddPointer(getStmt());
+        ID.AddPointer(getFrame());
+    }
+};
+
+bool operator==(const AccessStmt& A, const AccessStmt& B) {
+    return A.StmtAndIsStore == B.StmtAndIsStore &&
+           A.StackFrame == B.StackFrame;
+}
+
+bool operator<(const AccessStmt& A, const AccessStmt& B) {
+    return A.isStore() < B.isStore() || 
+        (A.isStore() == B.isStore() && (A.getStmt() < B.getStmt() || 
+            (A.getStmt() == B.getStmt() && A.getFrame() < B.getFrame())));
+}
+
+} // namespace
+
+REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(AccessStmtSet, AccessStmt);
+REGISTER_MAP_WITH_PROGRAMSTATE(Accesses, const MemRegion*, AccessStmtSet);
+
+StmtVec UnsequencedAccessChecker::getAllASTAncestors(
+            const Stmt* CurrentS, const StackFrameContext* CurrentFrame,
+            ParentMapContext& ParentMap) {
+
+    StmtVec Ancestors;
+
+    while (CurrentS) {
+        Ancestors.push_back(CurrentS);
+
+        DynTypedNodeList PL = ParentMap.getParents(*CurrentS);
+        if (PL.size() != 1)
+            break;
+
+        CurrentS = PL[0].get<Stmt>();
+
+        if (!CurrentS) {
+            if (CurrentFrame->inTopFrame())
+                break;
+
+            CurrentS = CurrentFrame->getCallSite();
+            CurrentFrame = CurrentFrame->getParent()->getStackFrame();
+        }
+    }
+
+    return Ancestors;
+}
+
+void UnsequencedAccessChecker::checkLocation(
+        SVal Location, bool isLoad, const Stmt *S, CheckerContext &C) const {
+
+    ASTContext& ASTCtx = C.getASTContext();
+    ParentMapContext& ParentMap = ASTCtx.getParentMapContext();
+    ProgramStateRef State = C.getState();
+    AccessStmtSet::Factory& SetFactory = State->get_context<AccessStmtSet>();
+    auto& MapFactory = State->get_context<Accesses>();
+
+    const MemRegion* Region = Location.getAsRegion();
+    StmtVec Ancestors = getAllASTAncestors(S, C.getStackFrame(), ParentMap);
+
+    if (State->contains<Accesses>(Region)) {
+
+        const AccessStmtSet* Accs = State->get<Accesses>(Region);
+
+        for (AccessStmt AS : *Accs) {
+            if (AS.isStore() || !isLoad) {
+                StmtVec OtherAncestors = 
+                    getAllASTAncestors(AS.getStmt(), AS.getFrame(), ParentMap);
+                const Stmt* Common = 
+                    findCommonAncestor(Ancestors, OtherAncestors);
+
+                if (!Common) {
+                    State = State->set<Accesses>(MapFactory.getEmptyMap());
+                    break;
+                }
+
+                if (const auto* BO = dyn_cast<BinaryOperator>(Common)) {
+                    if (BO->isAdditiveOp()) {
+                        reportBug(C, S, AS.getStmt());
+                    }
+                }
+            }
+        }
+        AccessStmtSet Updated =
+            SetFactory.add(*Accs, AccessStmt(S, !isLoad, C.getStackFrame()));
+
+        C.addTransition(State->set<Accesses>(Region, Updated));
+    } else {
+        AccessStmtSet NewSet = SetFactory.add(
+                SetFactory.getEmptySet(),
+                AccessStmt(S, !isLoad, C.getStackFrame()));
+
+        ProgramStateRef LocAdded = State->set<Accesses>(Region, NewSet);
+        C.addTransition(LocAdded);
+    }
+}
+
+const Stmt* UnsequencedAccessChecker::findCommonAncestor(const StmtVec& A,
+                                                         const StmtVec& B) {
+    unsigned I = 1;
+    while (I <= std::min(A.size(), B.size())) {
+        if (A[A.size() - I] != B[B.size() - I]) {
+            break;
+        }
+        I++;
+    }
+
+    if (I == 1)
+        return nullptr;
+
+    return A[A.size() - (I - 1)];
+}
+
+void UnsequencedAccessChecker::reportBug(CheckerContext& C, const Stmt* A,
+                                         const Stmt* B) const {
+    if (ExplodedNode* N = C.generateErrorNode()) {
+        auto BR = std::make_unique<PathSensitiveBugReport>(BT, "hello", N);
+        C.emitReport(std::move(BR));
+    }
+}
+
+void ento::registerUnsequencedAccessChecker(CheckerManager &mgr) {
+  mgr.registerChecker<UnsequencedAccessChecker>();
+}
+
+bool ento::shouldRegisterUnsequencedAccessChecker(const CheckerManager &mgr) {
+  return true;
+}

>From 41d8a571bca4b19dff82f89289fb8cad6c13f014 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= <aron.harnasi at gmail.com>
Date: Mon, 7 Jul 2025 23:12:00 +0200
Subject: [PATCH 03/12] better warning message

---
 .../Checkers/UnsequencedAccessChecker.cpp     | 75 +++++++++++++------
 1 file changed, 51 insertions(+), 24 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
index dc41137454ac3a..31909fd62fcd72 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
@@ -26,22 +26,6 @@ using namespace ento;
 using StmtVec = llvm::SmallVector<const Stmt*>;
 
 namespace {
-class UnsequencedAccessChecker
-    : public Checker<check::Location> {
-
-    static StmtVec getAllASTAncestors(const Stmt* CurrentS,
-                                      const StackFrameContext* CurrentFrame,
-                                      ParentMapContext& ParentMap);
-    static const Stmt* findCommonAncestor(const StmtVec& A, const StmtVec& B);
-
-    void reportBug(CheckerContext& C, const Stmt* A, const Stmt* B) const;
-
-    BugType BT{this, "Unsequenced-access", categories::LogicError};
-
-public:
-    void checkLocation(SVal Location, bool isLoad, const Stmt *S,
-                       CheckerContext &C) const;
-};
 
 class AccessStmt {
     llvm::PointerIntPair<const Stmt*, 1, bool> StmtAndIsStore;
@@ -74,6 +58,26 @@ bool operator<(const AccessStmt& A, const AccessStmt& B) {
             (A.getStmt() == B.getStmt() && A.getFrame() < B.getFrame())));
 }
 
+class UnsequencedAccessChecker
+    : public Checker<check::Location> {
+
+    static StmtVec getAllASTAncestors(const Stmt* CurrentS,
+                                      const StackFrameContext* CurrentFrame,
+                                      ParentMapContext& ParentMap);
+    static const Stmt* findCommonAncestor(const StmtVec& A, const StmtVec& B);
+
+    void checkCommonAncestor(const Stmt* Common, AccessStmt A, AccessStmt B,
+                             CheckerContext& C) const;
+
+    void reportBug(CheckerContext& C, const Stmt* Common, AccessStmt A,
+                   AccessStmt B) const;
+
+    BugType BT{this, "Unsequenced-access", categories::LogicError};
+
+public:
+    void checkLocation(SVal Location, bool isLoad, const Stmt *S,
+                       CheckerContext &C) const;
+};
 } // namespace
 
 REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(AccessStmtSet, AccessStmt);
@@ -134,11 +138,8 @@ void UnsequencedAccessChecker::checkLocation(
                     break;
                 }
 
-                if (const auto* BO = dyn_cast<BinaryOperator>(Common)) {
-                    if (BO->isAdditiveOp()) {
-                        reportBug(C, S, AS.getStmt());
-                    }
-                }
+                checkCommonAncestor(Common, AccessStmt(S, !isLoad, C.getStackFrame()), AS, C);
+
             }
         }
         AccessStmtSet Updated =
@@ -171,10 +172,36 @@ const Stmt* UnsequencedAccessChecker::findCommonAncestor(const StmtVec& A,
     return A[A.size() - (I - 1)];
 }
 
-void UnsequencedAccessChecker::reportBug(CheckerContext& C, const Stmt* A,
-                                         const Stmt* B) const {
+void UnsequencedAccessChecker::checkCommonAncestor(
+        const Stmt* Common, AccessStmt A, AccessStmt B,
+        CheckerContext& C) const {
+
+    if (const auto* BO = dyn_cast<BinaryOperator>(Common)) {
+        if (BO->isAdditiveOp()) {
+            reportBug(C, Common, A, B);
+        }
+    }
+
+    if (const auto* CE = dyn_cast<CallExpr>(Common)) {
+        reportBug(C, Common, A, B);
+    }
+}
+
+void UnsequencedAccessChecker::reportBug(CheckerContext& C, const Stmt* Common,
+                                         AccessStmt A, AccessStmt B) const {
     if (ExplodedNode* N = C.generateErrorNode()) {
-        auto BR = std::make_unique<PathSensitiveBugReport>(BT, "hello", N);
+        auto BR = std::make_unique<PathSensitiveBugReport>(BT,
+                A.isStore() ? "unsequenced write to variable" 
+                            : "unsequenced read from variable", N);
+
+        PathDiagnosticLocation BLoc(B.getStmt(), C.getSourceManager(),
+                                    C.getLocationContext());
+        BR->addNote(B.isStore() ? "variable is written to here" 
+                                : "variable is read from here", BLoc);
+
+        PathDiagnosticLocation CommLoc(Common, C.getSourceManager(),
+                                       C.getLocationContext());
+        BR->addNote("unsequenced expression here", CommLoc);
         C.emitReport(std::move(BR));
     }
 }

>From a5153f2a7f849d5ae8b53fd18c0490c7f40320a1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= <aron.harnasi at gmail.com>
Date: Sat, 12 Jul 2025 09:10:01 +0200
Subject: [PATCH 04/12] pain suffering functions

---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   6 +
 .../Checkers/UnsequencedAccessChecker.cpp     | 182 ++++++++++++++----
 clang/test/Analysis/unsequenced.c             | 105 ++++++++++
 3 files changed, 252 insertions(+), 41 deletions(-)
 create mode 100644 clang/test/Analysis/unsequenced.c

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 10189078db8d66..35e8ea05273f84 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -232,6 +232,12 @@ def NonnullGlobalConstantsChecker: Checker<"NonnilStringConstants">,
   Hidden;
 
 def UnsequencedAccessChecker : Checker<"UnsequencedAccess">,
+    CheckerOptions<[
+    CmdLineOption<Boolean,
+                  "PrintDebugLog",
+                  "Print debug logs for checkers.",
+                  "false",
+                  Released>]>,
    Documentation<NotDocumented>;
 
 } // end "core"
diff --git a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
index 31909fd62fcd72..2efd188607591e 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
@@ -23,10 +23,10 @@
 using namespace clang;
 using namespace ento;
 
-using StmtVec = llvm::SmallVector<const Stmt*>;
-
 namespace {
 
+using StmtVec = llvm::SmallVector<const Stmt*>;
+
 class AccessStmt {
     llvm::PointerIntPair<const Stmt*, 1, bool> StmtAndIsStore;
     const StackFrameContext* StackFrame;
@@ -62,21 +62,27 @@ class UnsequencedAccessChecker
     : public Checker<check::Location> {
 
     static StmtVec getAllASTAncestors(const Stmt* CurrentS,
-                                      const StackFrameContext* CurrentFrame,
-                                      ParentMapContext& ParentMap);
-    static const Stmt* findCommonAncestor(const StmtVec& A, const StmtVec& B);
+                                        const StackFrameContext* CurrentFrame,
+                                        ParentMapContext& ParentMap);
+    static int findCommonAncestorIdx(const StmtVec& A, const StmtVec& B);
 
-    void checkCommonAncestor(const Stmt* Common, AccessStmt A, AccessStmt B,
-                             CheckerContext& C) const;
+    bool checkAncestors(int Common, AccessStmt A, const StmtVec& AVec,
+                        AccessStmt B, const StmtVec& BVec,
+                        const LangOptions& Opts) const;
 
     void reportBug(CheckerContext& C, const Stmt* Common, AccessStmt A,
                    AccessStmt B) const;
 
+    ProgramStateRef resetState(ProgramStateRef S) const;
+
     BugType BT{this, "Unsequenced-access", categories::LogicError};
 
 public:
     void checkLocation(SVal Location, bool isLoad, const Stmt *S,
                        CheckerContext &C) const;
+
+    // Checker Options
+    bool PrintDebugLog;
 };
 } // namespace
 
@@ -90,26 +96,45 @@ StmtVec UnsequencedAccessChecker::getAllASTAncestors(
     StmtVec Ancestors;
 
     while (CurrentS) {
-        Ancestors.push_back(CurrentS);
 
         DynTypedNodeList PL = ParentMap.getParents(*CurrentS);
         if (PL.size() != 1)
             break;
 
-        CurrentS = PL[0].get<Stmt>();
+        const Stmt* ParentS = PL[0].get<Stmt>();
 
-        if (!CurrentS) {
+        if (!ParentS) {
             if (CurrentFrame->inTopFrame())
                 break;
 
-            CurrentS = CurrentFrame->getCallSite();
+            ParentS = CurrentFrame->getCallSite();
             CurrentFrame = CurrentFrame->getParent()->getStackFrame();
         }
+
+        Ancestors.push_back(CurrentS);
+
+        CurrentS = ParentS;
     }
 
+    Ancestors.push_back(CurrentS);
+
     return Ancestors;
 }
 
+static void print_ancestors(const StmtVec& ancestors) {
+    for (const Stmt* S : ancestors) {
+        std::cout << S->getStmtClassName() << " " << S << std::endl;
+    }
+}
+
+ProgramStateRef UnsequencedAccessChecker::resetState(ProgramStateRef S) const {
+    if (PrintDebugLog) {
+        std::cout << "Reset State\n\n";
+    }
+    auto& MapFactory = S->get_context<Accesses>();
+    return S->set<Accesses>(MapFactory.getEmptyMap());
+}
+
 void UnsequencedAccessChecker::checkLocation(
         SVal Location, bool isLoad, const Stmt *S, CheckerContext &C) const {
 
@@ -117,28 +142,41 @@ void UnsequencedAccessChecker::checkLocation(
     ParentMapContext& ParentMap = ASTCtx.getParentMapContext();
     ProgramStateRef State = C.getState();
     AccessStmtSet::Factory& SetFactory = State->get_context<AccessStmtSet>();
-    auto& MapFactory = State->get_context<Accesses>();
 
     const MemRegion* Region = Location.getAsRegion();
+    AccessStmt Current(S, !isLoad, C.getStackFrame());
     StmtVec Ancestors = getAllASTAncestors(S, C.getStackFrame(), ParentMap);
 
+    if (PrintDebugLog) {
+        SourceLocation Loc = S->getBeginLoc();
+        int Line = C.getSourceManager().getSpellingLineNumber(Loc);
+        std::cout << (isLoad ? "Load" : "Store") << " on line " << Line
+                  << std::endl;
+        print_ancestors(Ancestors);
+        std::cout << std::endl;
+    }
+
     if (State->contains<Accesses>(Region)) {
 
         const AccessStmtSet* Accs = State->get<Accesses>(Region);
 
         for (AccessStmt AS : *Accs) {
             if (AS.isStore() || !isLoad) {
-                StmtVec OtherAncestors = 
+                StmtVec CurrentAncestors =
                     getAllASTAncestors(AS.getStmt(), AS.getFrame(), ParentMap);
-                const Stmt* Common = 
-                    findCommonAncestor(Ancestors, OtherAncestors);
 
-                if (!Common) {
-                    State = State->set<Accesses>(MapFactory.getEmptyMap());
-                    break;
-                }
+                int CommonIdx =
+                    findCommonAncestorIdx(Ancestors, CurrentAncestors);
+
+                if (CommonIdx == -1)
+                    continue;
 
-                checkCommonAncestor(Common, AccessStmt(S, !isLoad, C.getStackFrame()), AS, C);
+                if(checkAncestors(CommonIdx, AS, Ancestors, Current,
+                                  CurrentAncestors, C.getLangOpts())) {
+                    const Stmt* CommonS =
+                        Ancestors[Ancestors.size() - CommonIdx];
+                    reportBug(C, CommonS, AS, Current);
+                }
 
             }
         }
@@ -156,8 +194,8 @@ void UnsequencedAccessChecker::checkLocation(
     }
 }
 
-const Stmt* UnsequencedAccessChecker::findCommonAncestor(const StmtVec& A,
-                                                         const StmtVec& B) {
+int UnsequencedAccessChecker::findCommonAncestorIdx(const StmtVec& A,
+                                                    const StmtVec& B) {
     unsigned I = 1;
     while (I <= std::min(A.size(), B.size())) {
         if (A[A.size() - I] != B[B.size() - I]) {
@@ -167,49 +205,111 @@ const Stmt* UnsequencedAccessChecker::findCommonAncestor(const StmtVec& A,
     }
 
     if (I == 1)
-        return nullptr;
+        return -1;
 
-    return A[A.size() - (I - 1)];
+    return (I - 1);
 }
 
-void UnsequencedAccessChecker::checkCommonAncestor(
-        const Stmt* Common, AccessStmt A, AccessStmt B,
-        CheckerContext& C) const {
+bool UnsequencedAccessChecker::checkAncestors(
+        int CommonIdx, AccessStmt A, const StmtVec& AVec, AccessStmt B,
+        const StmtVec& BVec, const LangOptions& Opts) const {
+
+    const Stmt* CommonS = AVec[AVec.size() - CommonIdx];
+
+    if (const auto* BO = dyn_cast<BinaryOperator>(CommonS)) {
+        if (BO->isLogicalOp() || BO->isCommaOp() || BO->isPtrMemOp())
+            return false;
 
-    if (const auto* BO = dyn_cast<BinaryOperator>(Common)) {
-        if (BO->isAdditiveOp()) {
-            reportBug(C, Common, A, B);
+        if (Opts.CPlusPlus17 && BO->isShiftOp()) {
+            return false;
         }
+
+        if (BO->isAssignmentOp()) {
+            const Stmt* Accessed = BO->getLHS()->IgnoreParens();
+            if (Accessed == A.getStmt() && !B.isStore())
+                return false;
+
+            if (Accessed == B.getStmt() && !A.isStore())
+                return false;
+        }
+
+        return true;
     }
 
-    if (const auto* CE = dyn_cast<CallExpr>(Common)) {
-        reportBug(C, Common, A, B);
+    if (const auto* CE = dyn_cast<CallExpr>(CommonS)) {
+        if (A.getStmt() == CommonS || B.getStmt() == CommonS) {
+            // i.e. CommonS is the first element of one or both vectors.
+            return false;
+        }
+
+        int MinSize = std::min(AVec.size(), BVec.size());
+        assert(CommonIdx < MinSize);
+
+        bool AFound = false;
+        bool BFound = false;
+
+        const Stmt* AFirstChild = AVec[AVec.size() - CommonIdx - 1];
+        const Stmt* BFirstChild = BVec[BVec.size() - CommonIdx - 1];
+
+        if (!Opts.CPlusPlus17 && AFirstChild == CE->getCallee())
+            AFound = true;
+
+        if (!Opts.CPlusPlus17 && BFirstChild == CE->getCallee())
+            BFound = true;
+
+        for (const Stmt* Arg : CE->arguments()) {
+            if (Arg == AFirstChild)
+                AFound = true;
+
+            if (Arg == BFirstChild)
+                BFound = true;
+
+            if (AFound && BFound)
+                return true;
+        }
+
+        return false;
     }
+
+    return false;
 }
 
 void UnsequencedAccessChecker::reportBug(CheckerContext& C, const Stmt* Common,
                                          AccessStmt A, AccessStmt B) const {
-    if (ExplodedNode* N = C.generateErrorNode()) {
-        auto BR = std::make_unique<PathSensitiveBugReport>(BT,
-                A.isStore() ? "unsequenced write to variable" 
-                            : "unsequenced read from variable", N);
+    if (ExplodedNode* N = C.generateNonFatalErrorNode()) {
+        PathDiagnosticLocation CommonLoc(Common, C.getSourceManager(),
+                                         C.getLocationContext());
+
+        PathDiagnosticLocation ALoc(A.getStmt(), C.getSourceManager(),
+                                    C.getLocationContext());
 
         PathDiagnosticLocation BLoc(B.getStmt(), C.getSourceManager(),
                                     C.getLocationContext());
+
+        bool bothStore = A.isStore() && B.isStore();
+
+        auto BR = std::make_unique<PathSensitiveBugReport>(BT,
+                bothStore ? "unsequenced writes to variable" 
+                          : "unsequenced write to and read from variable", N,
+                CommonLoc, nullptr);
+
+        BR->addNote(A.isStore() ? "variable is written to here" 
+                                : "variable is read from here", ALoc);
+
         BR->addNote(B.isStore() ? "variable is written to here" 
                                 : "variable is read from here", BLoc);
 
-        PathDiagnosticLocation CommLoc(Common, C.getSourceManager(),
-                                       C.getLocationContext());
-        BR->addNote("unsequenced expression here", CommLoc);
         C.emitReport(std::move(BR));
     }
 }
 
 void ento::registerUnsequencedAccessChecker(CheckerManager &mgr) {
-  mgr.registerChecker<UnsequencedAccessChecker>();
+  auto* Checker = mgr.registerChecker<UnsequencedAccessChecker>();
+  const AnalyzerOptions &Opts = mgr.getAnalyzerOptions();
+  Checker->PrintDebugLog = Opts.getCheckerBooleanOption(Checker,
+                                                        "PrintDebugLog");
 }
 
 bool ento::shouldRegisterUnsequencedAccessChecker(const CheckerManager &mgr) {
-  return true;
+  return !mgr.getLangOpts().ObjC;
 }
diff --git a/clang/test/Analysis/unsequenced.c b/clang/test/Analysis/unsequenced.c
new file mode 100644
index 00000000000000..3b13c31550ca9d
--- /dev/null
+++ b/clang/test/Analysis/unsequenced.c
@@ -0,0 +1,105 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core
+
+static void binary_op_checks_inline(void) {
+    int a1 = 0;
+    int b = 0;
+    int* ip;
+    
+    b = a1 + (a1++);
+    // expected-warning at -1{{unsequenced modification and access}}
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+
+    a1 = a1++;
+    // expected-warning at -1{{multiple unsequenced modifications}}
+    // expected-warning at -2{{unsequenced writes to variable}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-note at -4{{variable is written to here}}
+
+    b = a1 + b + (a1++);
+    // expected-warning at -1{{unsequenced modification and access}}
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+    
+    b = (a1++) - a1;
+    // expected-warning at -1{{unsequenced modification and access}}
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-note at -4{{variable is read from here}}
+    
+    if (a1 + (a1++) == b) {}
+    // expected-warning at -1{{unsequenced modification and access}}
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+
+    while (a1 + a1 == b) {}
+    a1 = a1 + 1;
+    a1 += a1;
+    b = (a1++, a1);
+
+    ip = &b;
+
+    if (*ip + (a1++)) {}
+    
+    ip = &a1;
+
+    if (*ip == (a1++)) {}
+    // expected-warning at -1{{unsequenced write to and read from variable}}
+    // expected-note at -2{{variable is read from here}}
+    // expected-note at -3{{variable is written to here}}
+
+    *(ip + a1) = a1++;
+    // expected-warning at -1{{unsequenced modification and access}}
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-note at -4{{variable is read from here}}
+    
+    (void)a1; (void)b;
+}
+
+static void* id(void* param) {
+    return param;
+}
+
+static void binary_op_checks_with_functions(void) {
+    int a = 0;
+
+    *(int*)id(&a) = a++; // Equivalent to a = (a++);
+    // expected-warning at -1{{unsequenced writes to variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+
+    *(int*)id(&a) = a + 1; // Equivalent to a = a + 1;
+}
+
+static void does_nothing2(int a, int b) {
+}
+
+static void function_checks_inline(void) {
+    int a = 0;
+
+    does_nothing2(a, a++);
+    // expected-warning at -1{{unsequenced modification and access}}
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+    
+    does_nothing2(a++, a++);
+    // expected-warning at -1{{multiple unsequenced modifications}}
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-note at -4{{variable is read from here}}
+}
+
+static int* inc_and_return(int* a) {
+    ++*a;
+    return a;
+}
+
+static void function_checks(void) {
+    
+}

>From d0b79c996d8050fe854c681d1ae642145c5b6a30 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= <aron.harnasi at gmail.com>
Date: Sat, 12 Jul 2025 12:42:18 +0200
Subject: [PATCH 05/12] added array thingys

---
 .../Checkers/UnsequencedAccessChecker.cpp     | 164 ++++++++++++++----
 clang/test/Analysis/unsequenced.c             |  22 ++-
 2 files changed, 149 insertions(+), 37 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
index 2efd188607591e..aa80da1380c2b1 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
@@ -57,6 +57,13 @@ bool operator<(const AccessStmt& A, const AccessStmt& B) {
         (A.isStore() == B.isStore() && (A.getStmt() < B.getStmt() || 
             (A.getStmt() == B.getStmt() && A.getFrame() < B.getFrame())));
 }
+} // namespace
+
+REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(AccessStmtSet, AccessStmt);
+REGISTER_MAP_WITH_PROGRAMSTATE(Loads, const MemRegion*, AccessStmtSet);
+REGISTER_MAP_WITH_PROGRAMSTATE(Stores, const MemRegion*, AccessStmtSet);
+
+namespace {
 
 class UnsequencedAccessChecker
     : public Checker<check::Location> {
@@ -66,6 +73,9 @@ class UnsequencedAccessChecker
                                         ParentMapContext& ParentMap);
     static int findCommonAncestorIdx(const StmtVec& A, const StmtVec& B);
 
+    void checkAgainstSet(const AccessStmtSet* Set, AccessStmt CurrentAccess,
+                         const StmtVec& Ancestors, CheckerContext& C,
+                         bool* FoundSame) const;
     bool checkAncestors(int Common, AccessStmt A, const StmtVec& AVec,
                         AccessStmt B, const StmtVec& BVec,
                         const LangOptions& Opts) const;
@@ -86,9 +96,6 @@ class UnsequencedAccessChecker
 };
 } // namespace
 
-REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(AccessStmtSet, AccessStmt);
-REGISTER_MAP_WITH_PROGRAMSTATE(Accesses, const MemRegion*, AccessStmtSet);
-
 StmtVec UnsequencedAccessChecker::getAllASTAncestors(
             const Stmt* CurrentS, const StackFrameContext* CurrentFrame,
             ParentMapContext& ParentMap) {
@@ -127,12 +134,19 @@ static void print_ancestors(const StmtVec& ancestors) {
     }
 }
 
+static int get_stmt_line_num(const Stmt* S, CheckerContext& C) {
+    SourceLocation Loc = S->getBeginLoc();
+    int Line = C.getSourceManager().getSpellingLineNumber(Loc);
+    return Line;
+}
+
 ProgramStateRef UnsequencedAccessChecker::resetState(ProgramStateRef S) const {
     if (PrintDebugLog) {
         std::cout << "Reset State\n\n";
     }
-    auto& MapFactory = S->get_context<Accesses>();
-    return S->set<Accesses>(MapFactory.getEmptyMap());
+    auto& MapFactory = S->get_context<Loads>();
+    return S->set<Loads>(MapFactory.getEmptyMap())
+            ->set<Stores>(MapFactory.getEmptyMap());
 }
 
 void UnsequencedAccessChecker::checkLocation(
@@ -144,53 +158,123 @@ void UnsequencedAccessChecker::checkLocation(
     AccessStmtSet::Factory& SetFactory = State->get_context<AccessStmtSet>();
 
     const MemRegion* Region = Location.getAsRegion();
-    AccessStmt Current(S, !isLoad, C.getStackFrame());
+    AccessStmt CurrentAccess(S, !isLoad, C.getStackFrame());
     StmtVec Ancestors = getAllASTAncestors(S, C.getStackFrame(), ParentMap);
 
     if (PrintDebugLog) {
-        SourceLocation Loc = S->getBeginLoc();
-        int Line = C.getSourceManager().getSpellingLineNumber(Loc);
-        std::cout << (isLoad ? "Load" : "Store") << " on line " << Line
-                  << std::endl;
+        std::cout << (isLoad ? "Load" : "Store") << " on line "
+                  << get_stmt_line_num(S, C) << std::endl;
         print_ancestors(Ancestors);
         std::cout << std::endl;
     }
 
-    if (State->contains<Accesses>(Region)) {
+    bool FoundSameLoad = false;
+    bool FoundSameStore = false;
+
+    if (!isLoad && State->contains<Loads>(Region))
+        checkAgainstSet(State->get<Loads>(Region), CurrentAccess, Ancestors, C, 
+                        &FoundSameLoad);
+
+    if (State->contains<Stores>(Region))
+        checkAgainstSet(State->get<Stores>(Region), CurrentAccess, Ancestors, C, 
+                        &FoundSameStore);
+
+    if (!isLoad && !State->contains<Stores>(Region)) {
+
+        AccessStmtSet Updated = SetFactory.add(SetFactory.getEmptySet(),
+                                               CurrentAccess);
+
+        C.addTransition(State->set<Stores>(Region, Updated));
+        if (PrintDebugLog) {
+            std::cout << "Region is new, adding.\n\n";
+        }
+        return;
+    }
+
+    if (isLoad && !FoundSameLoad && !FoundSameStore) {
 
-        const AccessStmtSet* Accs = State->get<Accesses>(Region);
+        AccessStmtSet CurrSet = State->contains<Loads>(Region) 
+            ? *State->get<Loads>(Region) : SetFactory.getEmptySet();
 
-        for (AccessStmt AS : *Accs) {
-            if (AS.isStore() || !isLoad) {
-                StmtVec CurrentAncestors =
-                    getAllASTAncestors(AS.getStmt(), AS.getFrame(), ParentMap);
+        AccessStmtSet Updated = SetFactory.add(CurrSet, CurrentAccess);
 
-                int CommonIdx =
-                    findCommonAncestorIdx(Ancestors, CurrentAncestors);
+        C.addTransition(State->set<Loads>(Region, Updated));
+    } 
 
-                if (CommonIdx == -1)
-                    continue;
+    if (PrintDebugLog && isLoad) {
+        std::cout << "Not adding load: " << CurrentAccess.getStmt()
+                  << std::endl << std::endl;
+    }
 
-                if(checkAncestors(CommonIdx, AS, Ancestors, Current,
-                                  CurrentAncestors, C.getLangOpts())) {
-                    const Stmt* CommonS =
-                        Ancestors[Ancestors.size() - CommonIdx];
-                    reportBug(C, CommonS, AS, Current);
-                }
+    if (!isLoad && !FoundSameStore) {
 
+        if (FoundSameLoad) {
+            if (PrintDebugLog) {
+                std::cout << "Removing load: " << CurrentAccess.getStmt()
+                          << std::endl << std::endl;
             }
+
+            AccessStmt LoadAccess(CurrentAccess.getStmt(), /*isStore*/false,
+                                  CurrentAccess.getFrame());
+            AccessStmtSet LoadRemoved =
+                SetFactory.remove(*State->get<Loads>(Region), LoadAccess);
+            State = State->set<Loads>(Region, LoadRemoved);
         }
-        AccessStmtSet Updated =
-            SetFactory.add(*Accs, AccessStmt(S, !isLoad, C.getStackFrame()));
 
-        C.addTransition(State->set<Accesses>(Region, Updated));
-    } else {
-        AccessStmtSet NewSet = SetFactory.add(
-                SetFactory.getEmptySet(),
-                AccessStmt(S, !isLoad, C.getStackFrame()));
+        AccessStmtSet CurrSet = State->contains<Stores>(Region) 
+            ? *State->get<Stores>(Region) : SetFactory.getEmptySet();
+
+        AccessStmtSet Updated = SetFactory.add(CurrSet, CurrentAccess);
+
+        C.addTransition(State->set<Stores>(Region, Updated));
+    }
 
-        ProgramStateRef LocAdded = State->set<Accesses>(Region, NewSet);
-        C.addTransition(LocAdded);
+    if (PrintDebugLog && !isLoad) {
+        std::cout << "Not adding store: " << CurrentAccess.getStmt()
+                  << std::endl << std::endl;
+    }
+}
+
+void UnsequencedAccessChecker::checkAgainstSet(
+        const AccessStmtSet* Set, AccessStmt CurrentAccess,
+        const StmtVec& Ancestors, CheckerContext& C, bool* FoundSame) const {
+
+    ASTContext& ASTCtx = C.getASTContext();
+    ParentMapContext& ParentMap = ASTCtx.getParentMapContext();
+
+    for (AccessStmt OtherAccess : *Set) {
+
+        if (CurrentAccess.getStmt() == OtherAccess.getStmt() &&
+            CurrentAccess.getFrame() == OtherAccess.getFrame()) {
+            *FoundSame = true;
+            if (PrintDebugLog) {
+                std::cout << "Found same, continuing.\n";
+            }
+            continue;
+        }
+
+        StmtVec CurrentAncestors =
+            getAllASTAncestors(OtherAccess.getStmt(), OtherAccess.getFrame(),
+                               ParentMap);
+
+        int CommonIdx = findCommonAncestorIdx(Ancestors, CurrentAncestors);
+        if (CommonIdx == -1)
+            continue;
+
+        if(checkAncestors(CommonIdx, OtherAccess, Ancestors, CurrentAccess,
+                          CurrentAncestors, C.getLangOpts())) {
+
+            const Stmt* CommonS = Ancestors[Ancestors.size() - CommonIdx];
+
+            if (PrintDebugLog) {
+                std::cout << "Common found: " << CommonS << " "
+                          << CommonS->getStmtClassName() << " Line " 
+                          << get_stmt_line_num(CommonS, C) << std::endl
+                          << std::endl;
+            }
+
+            reportBug(C, CommonS, OtherAccess, CurrentAccess);
+        }
     }
 }
 
@@ -236,6 +320,16 @@ bool UnsequencedAccessChecker::checkAncestors(
         return true;
     }
 
+    if (const auto* AS = dyn_cast<ArraySubscriptExpr>(CommonS)) {
+        if (Opts.CPlusPlus17)
+            return false;
+
+        if (A.getStmt() == AS || B.getStmt() == AS)
+            return false;
+
+        return true;
+    }
+
     if (const auto* CE = dyn_cast<CallExpr>(CommonS)) {
         if (A.getStmt() == CommonS || B.getStmt() == CommonS) {
             // i.e. CommonS is the first element of one or both vectors.
diff --git a/clang/test/Analysis/unsequenced.c b/clang/test/Analysis/unsequenced.c
index 3b13c31550ca9d..f9a60665148fd0 100644
--- a/clang/test/Analysis/unsequenced.c
+++ b/clang/test/Analysis/unsequenced.c
@@ -5,6 +5,7 @@ static void binary_op_checks_inline(void) {
     int a1 = 0;
     int b = 0;
     int* ip;
+    int arr[10];
     
     b = a1 + (a1++);
     // expected-warning at -1{{unsequenced modification and access}}
@@ -57,6 +58,20 @@ static void binary_op_checks_inline(void) {
     // expected-warning at -2{{unsequenced write to and read from variable}}
     // expected-note at -3{{variable is written to here}}
     // expected-note at -4{{variable is read from here}}
+
+    // Array subscript expressions are essentially just addition
+
+    (arr + a1)[a1++] = 0;
+    // expected-warning at -1{{unsequenced modification and access}}
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-note at -4{{variable is read from here}}
+    
+    (arr + --a1)[a1] = 1;
+    // expected-warning at -1{{unsequenced modification and access}}
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-note at -4{{variable is read from here}}
     
     (void)a1; (void)b;
 }
@@ -91,8 +106,11 @@ static void function_checks_inline(void) {
     does_nothing2(a++, a++);
     // expected-warning at -1{{multiple unsequenced modifications}}
     // expected-warning at -2{{unsequenced write to and read from variable}}
-    // expected-note at -3{{variable is written to here}}
-    // expected-note at -4{{variable is read from here}}
+    // expected-warning at -3{{unsequenced writes to variable}}
+    // expected-note at -4{{variable is written to here}}
+    // expected-note at -5{{variable is read from here}}
+    // expected-note at -6{{variable is written to here}}
+    // expected-note at -7{{variable is written to here}}
 }
 
 static int* inc_and_return(int* a) {

>From 7ef8593323f134876f98b5366411ea3f167c2f24 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= <aron.harnasi at gmail.com>
Date: Sat, 12 Jul 2025 20:10:49 +0200
Subject: [PATCH 06/12] optimization nr. 1

---
 .../Checkers/UnsequencedAccessChecker.cpp     | 232 +++++++++++++-----
 clang/test/Analysis/unsequenced.c             |  84 +++++++
 2 files changed, 257 insertions(+), 59 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
index aa80da1380c2b1..5aa75890a6c0a2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
@@ -63,23 +63,40 @@ REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(AccessStmtSet, AccessStmt);
 REGISTER_MAP_WITH_PROGRAMSTATE(Loads, const MemRegion*, AccessStmtSet);
 REGISTER_MAP_WITH_PROGRAMSTATE(Stores, const MemRegion*, AccessStmtSet);
 
+// Keep these around to make sure we don't walk too far up the stack too often.
+// These are also useful for state resets.
+REGISTER_TRAIT_WITH_PROGRAMSTATE(HighestUnseqFrame, const StackFrameContext*);
+REGISTER_TRAIT_WITH_PROGRAMSTATE(HighestUnseqStmt, const Stmt*);
+
 namespace {
 
 class UnsequencedAccessChecker
     : public Checker<check::Location> {
 
-    static StmtVec getAllASTAncestors(const Stmt* CurrentS,
-                                        const StackFrameContext* CurrentFrame,
-                                        ParentMapContext& ParentMap);
+    static StmtVec getAllASTAncestors(
+            const Stmt* CurrentS, const StackFrameContext* CurrentFrame,
+            ParentMapContext& ParentMap, const Stmt* HighestS,
+            const StackFrameContext* HighestFrame,
+            bool* DidHitHighest = nullptr);
     static int findCommonAncestorIdx(const StmtVec& A, const StmtVec& B);
 
     void checkAgainstSet(const AccessStmtSet* Set, AccessStmt CurrentAccess,
-                         const StmtVec& Ancestors, CheckerContext& C,
-                         bool* FoundSame) const;
+                         const StmtVec& Ancestors, const Stmt* HighestStmt,
+                         const StackFrameContext* HighestFrame,
+                         CheckerContext& C, bool* FoundSame) const;
+
     bool checkAncestors(int Common, AccessStmt A, const StmtVec& AVec,
                         AccessStmt B, const StmtVec& BVec,
                         const LangOptions& Opts) const;
 
+    std::pair<const Stmt*, const StackFrameContext*>
+    findHighestUnsequencedStmt(const Stmt* CurrentS,
+                               const StackFrameContext* CurrentFrame,
+                               const LangOptions& Opts, 
+                               ParentMapContext& ParentMap) const;
+
+    bool isUnsequencedStmt(const Stmt* S, const LangOptions& Opts) const;
+
     void reportBug(CheckerContext& C, const Stmt* Common, AccessStmt A,
                    AccessStmt B) const;
 
@@ -98,25 +115,47 @@ class UnsequencedAccessChecker
 
 StmtVec UnsequencedAccessChecker::getAllASTAncestors(
             const Stmt* CurrentS, const StackFrameContext* CurrentFrame,
-            ParentMapContext& ParentMap) {
+            ParentMapContext& ParentMap, const Stmt* HighestS,
+            const StackFrameContext* HighestFrame, bool* DidHitHighest) {
+
+    assert(CurrentS != nullptr);
+    assert(CurrentFrame != nullptr);
 
     StmtVec Ancestors;
 
-    while (CurrentS) {
+    while (true) {
 
-        DynTypedNodeList PL = ParentMap.getParents(*CurrentS);
-        if (PL.size() != 1)
+        if (CurrentS == HighestS && CurrentFrame == HighestFrame) {
+            if (DidHitHighest != nullptr)
+                *DidHitHighest = true;
             break;
+        }
+
+        DynTypedNodeList PL = ParentMap.getParents(*CurrentS);
+        const Stmt* ParentS;
 
-        const Stmt* ParentS = PL[0].get<Stmt>();
+        if (PL.size() == 1) {
+            // This could also yield a nullptr
+            ParentS = PL[0].get<Stmt>();
+        } else {
+            ParentS = nullptr;
+        }
 
         if (!ParentS) {
-            if (CurrentFrame->inTopFrame())
+            // A call can originate from a declaration and therefore the call
+            // site may be null. Treat that as top level for now.
+            if (CurrentFrame->inTopFrame() || 
+                    CurrentFrame->getCallSite() == nullptr) {
+
+                if (DidHitHighest != nullptr)
+                    *DidHitHighest = false;
                 break;
+            }
 
             ParentS = CurrentFrame->getCallSite();
             CurrentFrame = CurrentFrame->getParent()->getStackFrame();
         }
+        assert(ParentS != nullptr);
 
         Ancestors.push_back(CurrentS);
 
@@ -128,6 +167,71 @@ StmtVec UnsequencedAccessChecker::getAllASTAncestors(
     return Ancestors;
 }
 
+std::pair<const Stmt*, const StackFrameContext*>
+UnsequencedAccessChecker::findHighestUnsequencedStmt(
+        const Stmt* CurrentS, const StackFrameContext* CurrentFrame,
+        const LangOptions& Opts, ParentMapContext& ParentMap) const {
+
+    assert(CurrentS != nullptr);
+    assert(CurrentFrame != nullptr);
+
+    const Stmt* HighestUnseqS = CurrentS;
+    const StackFrameContext* HighestUnseqFrame = CurrentFrame;
+
+    while (true) {
+
+        if (isUnsequencedStmt(CurrentS, Opts)) {
+            HighestUnseqS = CurrentS;
+            HighestUnseqFrame = CurrentFrame;
+        }
+
+        DynTypedNodeList PL = ParentMap.getParents(*CurrentS);
+        const Stmt* ParentS;
+
+        if (PL.size() == 1) {
+            // This could also yield a nullptr
+            ParentS = PL[0].get<Stmt>();
+        } else {
+            ParentS = nullptr;
+        }
+
+        if (!ParentS) {
+            // A call can originate from a declaration and therefore the call
+            // site may be null. Treat that as top level for now.
+            if (CurrentFrame->inTopFrame() || 
+                    CurrentFrame->getCallSite() == nullptr)
+                break;
+
+            ParentS = CurrentFrame->getCallSite();
+            CurrentFrame = CurrentFrame->getParent()->getStackFrame();
+        }
+
+        assert(ParentS != nullptr);
+        CurrentS = ParentS;
+    }
+
+    return std::make_pair(HighestUnseqS, HighestUnseqFrame);
+}
+
+bool UnsequencedAccessChecker::isUnsequencedStmt(
+        const Stmt* S, const LangOptions& Opts) const {
+
+    if (isa<CallExpr>(S))
+        return true;
+
+    if (const auto* BO = dyn_cast<BinaryOperator>(S)) {
+        if (BO->isLogicalOp() || BO->isCommaOp() || BO->isPtrMemOp())
+            return false;
+
+        if (Opts.CPlusPlus17 && BO->isShiftOp())
+            return false;
+        
+        return true;
+    }
+
+    return false;
+}
+
 static void print_ancestors(const StmtVec& ancestors) {
     for (const Stmt* S : ancestors) {
         std::cout << S->getStmtClassName() << " " << S << std::endl;
@@ -141,12 +245,14 @@ static int get_stmt_line_num(const Stmt* S, CheckerContext& C) {
 }
 
 ProgramStateRef UnsequencedAccessChecker::resetState(ProgramStateRef S) const {
-    if (PrintDebugLog) {
+    if (PrintDebugLog)
         std::cout << "Reset State\n\n";
-    }
+
     auto& MapFactory = S->get_context<Loads>();
     return S->set<Loads>(MapFactory.getEmptyMap())
-            ->set<Stores>(MapFactory.getEmptyMap());
+            ->set<Stores>(MapFactory.getEmptyMap())
+            ->set<HighestUnseqStmt>(nullptr)
+            ->set<HighestUnseqFrame>(nullptr);
 }
 
 void UnsequencedAccessChecker::checkLocation(
@@ -159,7 +265,31 @@ void UnsequencedAccessChecker::checkLocation(
 
     const MemRegion* Region = Location.getAsRegion();
     AccessStmt CurrentAccess(S, !isLoad, C.getStackFrame());
-    StmtVec Ancestors = getAllASTAncestors(S, C.getStackFrame(), ParentMap);
+
+    const Stmt* HighestStmt = State->get<HighestUnseqStmt>();
+    const StackFrameContext* HighestFrame = State->get<HighestUnseqFrame>();
+
+    bool DidHitHighest = false;
+
+    StmtVec Ancestors = getAllASTAncestors(S, C.getStackFrame(), ParentMap,
+                                           HighestStmt, HighestFrame,
+                                           &DidHitHighest);
+
+    if (!DidHitHighest) {
+        std::pair<const Stmt*, const StackFrameContext*> Highest =
+            findHighestUnsequencedStmt(S, C.getStackFrame(), C.getLangOpts(),
+                                       ParentMap);
+        HighestStmt = Highest.first;
+        HighestFrame = Highest.second;
+
+        // This could be optimized.
+        Ancestors = getAllASTAncestors(S, C.getStackFrame(), ParentMap,
+                                       HighestStmt, HighestFrame);
+
+        State = resetState(State);
+        State = State->set<HighestUnseqStmt>(HighestStmt)
+                     ->set<HighestUnseqFrame>(HighestFrame);
+    }
 
     if (PrintDebugLog) {
         std::cout << (isLoad ? "Load" : "Store") << " on line "
@@ -172,24 +302,12 @@ void UnsequencedAccessChecker::checkLocation(
     bool FoundSameStore = false;
 
     if (!isLoad && State->contains<Loads>(Region))
-        checkAgainstSet(State->get<Loads>(Region), CurrentAccess, Ancestors, C, 
-                        &FoundSameLoad);
+        checkAgainstSet(State->get<Loads>(Region), CurrentAccess, Ancestors,
+                        HighestStmt, HighestFrame, C, &FoundSameLoad);
 
     if (State->contains<Stores>(Region))
-        checkAgainstSet(State->get<Stores>(Region), CurrentAccess, Ancestors, C, 
-                        &FoundSameStore);
-
-    if (!isLoad && !State->contains<Stores>(Region)) {
-
-        AccessStmtSet Updated = SetFactory.add(SetFactory.getEmptySet(),
-                                               CurrentAccess);
-
-        C.addTransition(State->set<Stores>(Region, Updated));
-        if (PrintDebugLog) {
-            std::cout << "Region is new, adding.\n\n";
-        }
-        return;
-    }
+        checkAgainstSet(State->get<Stores>(Region), CurrentAccess, Ancestors,
+                        HighestStmt, HighestFrame, C, &FoundSameStore);
 
     if (isLoad && !FoundSameLoad && !FoundSameStore) {
 
@@ -199,9 +317,8 @@ void UnsequencedAccessChecker::checkLocation(
         AccessStmtSet Updated = SetFactory.add(CurrSet, CurrentAccess);
 
         C.addTransition(State->set<Loads>(Region, Updated));
-    } 
 
-    if (PrintDebugLog && isLoad) {
+    } else if (PrintDebugLog && isLoad) {
         std::cout << "Not adding load: " << CurrentAccess.getStmt()
                   << std::endl << std::endl;
     }
@@ -227,9 +344,8 @@ void UnsequencedAccessChecker::checkLocation(
         AccessStmtSet Updated = SetFactory.add(CurrSet, CurrentAccess);
 
         C.addTransition(State->set<Stores>(Region, Updated));
-    }
 
-    if (PrintDebugLog && !isLoad) {
+    } else if (PrintDebugLog && !isLoad) {
         std::cout << "Not adding store: " << CurrentAccess.getStmt()
                   << std::endl << std::endl;
     }
@@ -237,7 +353,9 @@ void UnsequencedAccessChecker::checkLocation(
 
 void UnsequencedAccessChecker::checkAgainstSet(
         const AccessStmtSet* Set, AccessStmt CurrentAccess,
-        const StmtVec& Ancestors, CheckerContext& C, bool* FoundSame) const {
+        const StmtVec& Ancestors, const Stmt* HighestStmt,
+        const StackFrameContext* HighestFrame, CheckerContext& C,
+        bool* FoundSame) const {
 
     ASTContext& ASTCtx = C.getASTContext();
     ParentMapContext& ParentMap = ASTCtx.getParentMapContext();
@@ -247,15 +365,14 @@ void UnsequencedAccessChecker::checkAgainstSet(
         if (CurrentAccess.getStmt() == OtherAccess.getStmt() &&
             CurrentAccess.getFrame() == OtherAccess.getFrame()) {
             *FoundSame = true;
-            if (PrintDebugLog) {
+            if (PrintDebugLog)
                 std::cout << "Found same, continuing.\n";
-            }
             continue;
         }
 
         StmtVec CurrentAncestors =
             getAllASTAncestors(OtherAccess.getStmt(), OtherAccess.getFrame(),
-                               ParentMap);
+                               ParentMap, HighestStmt, HighestFrame);
 
         int CommonIdx = findCommonAncestorIdx(Ancestors, CurrentAncestors);
         if (CommonIdx == -1)
@@ -282,9 +399,8 @@ int UnsequencedAccessChecker::findCommonAncestorIdx(const StmtVec& A,
                                                     const StmtVec& B) {
     unsigned I = 1;
     while (I <= std::min(A.size(), B.size())) {
-        if (A[A.size() - I] != B[B.size() - I]) {
+        if (A[A.size() - I] != B[B.size() - I])
             break;
-        }
         I++;
     }
 
@@ -370,31 +486,29 @@ bool UnsequencedAccessChecker::checkAncestors(
 
 void UnsequencedAccessChecker::reportBug(CheckerContext& C, const Stmt* Common,
                                          AccessStmt A, AccessStmt B) const {
-    if (ExplodedNode* N = C.generateNonFatalErrorNode()) {
-        PathDiagnosticLocation CommonLoc(Common, C.getSourceManager(),
-                                         C.getLocationContext());
+    PathDiagnosticLocation CommonLoc(Common, C.getSourceManager(),
+                                     C.getLocationContext());
 
-        PathDiagnosticLocation ALoc(A.getStmt(), C.getSourceManager(),
-                                    C.getLocationContext());
+    PathDiagnosticLocation ALoc(A.getStmt(), C.getSourceManager(),
+                                C.getLocationContext());
 
-        PathDiagnosticLocation BLoc(B.getStmt(), C.getSourceManager(),
-                                    C.getLocationContext());
+    PathDiagnosticLocation BLoc(B.getStmt(), C.getSourceManager(),
+                                C.getLocationContext());
 
-        bool bothStore = A.isStore() && B.isStore();
+    bool bothStore = A.isStore() && B.isStore();
 
-        auto BR = std::make_unique<PathSensitiveBugReport>(BT,
-                bothStore ? "unsequenced writes to variable" 
-                          : "unsequenced write to and read from variable", N,
-                CommonLoc, nullptr);
+    auto BR = std::make_unique<BasicBugReport>(BT,
+            bothStore ? "unsequenced writes to variable" 
+                      : "unsequenced write to and read from variable",
+            CommonLoc);
 
-        BR->addNote(A.isStore() ? "variable is written to here" 
-                                : "variable is read from here", ALoc);
+    BR->addNote(A.isStore() ? "variable is written to here" 
+                            : "variable is read from here", ALoc);
 
-        BR->addNote(B.isStore() ? "variable is written to here" 
-                                : "variable is read from here", BLoc);
+    BR->addNote(B.isStore() ? "variable is written to here" 
+                            : "variable is read from here", BLoc);
 
-        C.emitReport(std::move(BR));
-    }
+    C.emitReport(std::move(BR));
 }
 
 void ento::registerUnsequencedAccessChecker(CheckerManager &mgr) {
diff --git a/clang/test/Analysis/unsequenced.c b/clang/test/Analysis/unsequenced.c
index f9a60665148fd0..09eeafa21e8eae 100644
--- a/clang/test/Analysis/unsequenced.c
+++ b/clang/test/Analysis/unsequenced.c
@@ -72,6 +72,15 @@ static void binary_op_checks_inline(void) {
     // expected-warning at -2{{unsequenced write to and read from variable}}
     // expected-note at -3{{variable is written to here}}
     // expected-note at -4{{variable is read from here}}
+
+    if (((*ip = 1 || b == 2) ? 0 : 3) + a1) {}
+    // expected-warning at -1{{unsequenced write to and read from variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is read from here}}
+
+    (arr + sizeof(a1))[1] = a1++;
+
+    b = a1 + (long)&a1;
     
     (void)a1; (void)b;
 }
@@ -115,9 +124,84 @@ static void function_checks_inline(void) {
 
 static int* inc_and_return(int* a) {
     ++*a;
+    // expected-note at -1{{variable is written to here}}
     return a;
 }
 
+int globalInt;
+
 static void function_checks(void) {
+
+    float a2 = 0.1f;
+    float* fp = &a2;
+
+    if (inc_and_return(&globalInt) + globalInt) {}
+    // expected-warning at -1{{unsequenced write to and read from variable}}
+    // expected-note at -2{{variable is read from here}}
     
+    if (inc_and_return(&globalInt) || globalInt) {}
+
+    a2 = ++a2;
+    // expected-warning at -1{{unsequenced writes to variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-warning at -4{{multiple unsequenced modifications}}
+    
+    *fp = ++*fp;
+    // expected-warning at -1{{unsequenced writes to variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+    
+    a2 = ++*fp;
+    // expected-warning at -1{{unsequenced writes to variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+}
+
+static void loop_checks(void) {
+    char* str[3] = {0, 0, 0};
+
+    char c = 'c';
+
+    unsigned i;
+
+    str[2] = &c;
+
+    for (i = 0; i < sizeof(str) / sizeof(*str); i++) {
+        if (str[i]) {
+            *(str[i]) = c++;
+            // expected-warning at -1{{unsequenced writes to variable}}
+            // expected-note at -2{{variable is written to here}}
+            // expected-note at -3{{variable is written to here}}
+        }
+    }
+}
+
+int globalI1;
+int globalI2;
+
+static int incGlobalI1(void) {
+    return ++globalI1;
+    // expected-note at -1{{variable is written to here}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-note at -4{{variable is read from here}}
+}
+
+static int incGlobalI2(void) {
+    return ++globalI2;
+}
+
+static int branch1(void) {
+    return incGlobalI1();
+}
+
+static int branch2(void) {
+    return incGlobalI2(), incGlobalI1();
+}
+
+static int branching_function_check(void) {
+    return branch1() + branch2();
+    // expected-warning at -1{{unsequenced write to and read from variable}}
+    // expected-warning at -2{{unsequenced writes to variable}}
 }

>From 08b34faae8e8b3bbe77498db998f1cf2d7c9568f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= <aron.harnasi at gmail.com>
Date: Sun, 13 Jul 2025 12:33:08 +0200
Subject: [PATCH 07/12] more tests and fixes

---
 .../Checkers/UnsequencedAccessChecker.cpp     | 63 +++++++++++++---
 clang/test/Analysis/unsequenced.c             | 68 +++++++++++++++++-
 clang/test/Analysis/unsequenced.cpp           | 71 +++++++++++++++++++
 3 files changed, 189 insertions(+), 13 deletions(-)
 create mode 100644 clang/test/Analysis/unsequenced.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
index 5aa75890a6c0a2..29ae8571ec3e7c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
@@ -38,6 +38,7 @@ class AccessStmt {
 
     bool isStore() const { return StmtAndIsStore.getInt(); }
     const Stmt* getStmt() const { return StmtAndIsStore.getPointer(); }
+    const Expr* getExpr() const { return dyn_cast<Expr>(getStmt()); }
     const StackFrameContext* getFrame() const { return StackFrame; }
 
     void Profile(llvm::FoldingSetNodeID &ID) const {
@@ -80,6 +81,8 @@ class UnsequencedAccessChecker
             bool* DidHitHighest = nullptr);
     static int findCommonAncestorIdx(const StmtVec& A, const StmtVec& B);
 
+    static bool hasClosePreUnaryOperatorAncestor(const StmtVec& S);
+
     void checkAgainstSet(const AccessStmtSet* Set, AccessStmt CurrentAccess,
                          const StmtVec& Ancestors, const Stmt* HighestStmt,
                          const StackFrameContext* HighestFrame,
@@ -370,16 +373,15 @@ void UnsequencedAccessChecker::checkAgainstSet(
             continue;
         }
 
-        StmtVec CurrentAncestors =
+        StmtVec OtherAncestors =
             getAllASTAncestors(OtherAccess.getStmt(), OtherAccess.getFrame(),
                                ParentMap, HighestStmt, HighestFrame);
 
-        int CommonIdx = findCommonAncestorIdx(Ancestors, CurrentAncestors);
-        if (CommonIdx == -1)
-            continue;
+        int CommonIdx = findCommonAncestorIdx(Ancestors, OtherAncestors);
+        assert(CommonIdx != -1);
 
-        if(checkAncestors(CommonIdx, OtherAccess, Ancestors, CurrentAccess,
-                          CurrentAncestors, C.getLangOpts())) {
+        if(checkAncestors(CommonIdx, OtherAccess, OtherAncestors, CurrentAccess,
+                          Ancestors, C.getLangOpts())) {
 
             const Stmt* CommonS = Ancestors[Ancestors.size() - CommonIdx];
 
@@ -425,12 +427,35 @@ bool UnsequencedAccessChecker::checkAncestors(
         }
 
         if (BO->isAssignmentOp()) {
-            const Stmt* Accessed = BO->getLHS()->IgnoreParens();
-            if (Accessed == A.getStmt() && !B.isStore())
+            if (Opts.CPlusPlus17)
                 return false;
 
-            if (Accessed == B.getStmt() && !A.isStore())
-                return false;
+            const Stmt* Accessed = BO->getLHS()->IgnoreParenCasts();
+            if (PrintDebugLog) {
+                std::cout << "Accessed is: " << Accessed << " "
+                          << Accessed->getStmtClassName() << std::endl;
+                const Stmt* ASide = A.getExpr()->IgnoreParenCasts();
+                const Stmt* BSide = B.getExpr()->IgnoreParenCasts();
+                std::cout << "ASide is: " << ASide << " "
+                          << ASide->getStmtClassName() << std::endl;
+                std::cout << "BSide is: " << BSide << " "
+                          << BSide->getStmtClassName() << std::endl;
+            }
+            if (Accessed == A.getExpr()->IgnoreParenCasts()) {
+                if (!B.isStore())
+                    return false;
+
+                if (Opts.CPlusPlus11 && hasClosePreUnaryOperatorAncestor(BVec))
+                    return false;
+            }
+
+            if (Accessed == B.getExpr()->IgnoreParenCasts()) {
+                if (!A.isStore())
+                    return false;
+
+                if (Opts.CPlusPlus11 && hasClosePreUnaryOperatorAncestor(AVec))
+                    return false;
+            }
         }
 
         return true;
@@ -484,6 +509,24 @@ bool UnsequencedAccessChecker::checkAncestors(
     return false;
 }
 
+bool UnsequencedAccessChecker::hasClosePreUnaryOperatorAncestor(
+        const StmtVec& Vec) {
+
+    int VecSize = Vec.size();
+    for (int I = 1; I < VecSize; I++) {
+        if (isa<ParenExpr>(Vec[I]) || isa<CastExpr>(Vec[I]))
+            continue;
+
+        if (const auto* Op = dyn_cast<UnaryOperator>(Vec[I]))
+            return Op->isPrefix();
+
+        break;
+    }
+    std::cout << std::endl;
+
+    return false;
+}
+
 void UnsequencedAccessChecker::reportBug(CheckerContext& C, const Stmt* Common,
                                          AccessStmt A, AccessStmt B) const {
     PathDiagnosticLocation CommonLoc(Common, C.getSourceManager(),
diff --git a/clang/test/Analysis/unsequenced.c b/clang/test/Analysis/unsequenced.c
index 09eeafa21e8eae..9965ae7332a425 100644
--- a/clang/test/Analysis/unsequenced.c
+++ b/clang/test/Analysis/unsequenced.c
@@ -18,8 +18,14 @@ static void binary_op_checks_inline(void) {
     // expected-warning at -2{{unsequenced writes to variable}}
     // expected-note at -3{{variable is written to here}}
     // expected-note at -4{{variable is written to here}}
+    
+    a1 = ++a1;
+    // expected-warning at -1{{multiple unsequenced modifications}}
+    // expected-warning at -2{{unsequenced writes to variable}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-note at -4{{variable is written to here}}
 
-    b = a1 + b + (a1++);
+    b = a1 + b + (++a1);
     // expected-warning at -1{{unsequenced modification and access}}
     // expected-warning at -2{{unsequenced write to and read from variable}}
     // expected-note at -3{{variable is read from here}}
@@ -31,7 +37,7 @@ static void binary_op_checks_inline(void) {
     // expected-note at -3{{variable is written to here}}
     // expected-note at -4{{variable is read from here}}
     
-    if (a1 + (a1++) == b) {}
+    if (a1 + (a1 = 0) == b) {}
     // expected-warning at -1{{unsequenced modification and access}}
     // expected-warning at -2{{unsequenced write to and read from variable}}
     // expected-note at -3{{variable is read from here}}
@@ -53,7 +59,7 @@ static void binary_op_checks_inline(void) {
     // expected-note at -2{{variable is read from here}}
     // expected-note at -3{{variable is written to here}}
 
-    *(ip + a1) = a1++;
+    *(ip + a1) = a1 -= 1;
     // expected-warning at -1{{unsequenced modification and access}}
     // expected-warning at -2{{unsequenced write to and read from variable}}
     // expected-note at -3{{variable is written to here}}
@@ -81,6 +87,24 @@ static void binary_op_checks_inline(void) {
     (arr + sizeof(a1))[1] = a1++;
 
     b = a1 + (long)&a1;
+
+    b = a1 << (++a1);
+    // expected-warning at -1{{unsequenced modification and access}}
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-note at -4{{variable is read from here}}
+
+    *ip = a1 = a1 + 1;
+    // expected-warning at -1{{unsequenced writes to variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+
+    a1 = 2 + (a1 = 0);
+    // expected-warning at -1{{unsequenced writes to variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-warning at -4{{multiple unsequenced modifications}}
+
     
     (void)a1; (void)b;
 }
@@ -120,6 +144,12 @@ static void function_checks_inline(void) {
     // expected-note at -5{{variable is read from here}}
     // expected-note at -6{{variable is written to here}}
     // expected-note at -7{{variable is written to here}}
+
+    does_nothing2(a = 0, a = 1);
+    // expected-warning at -1{{unsequenced writes to variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-warning at -4{{multiple unsequenced modifications}}
 }
 
 static int* inc_and_return(int* a) {
@@ -205,3 +235,35 @@ static int branching_function_check(void) {
     // expected-warning at -1{{unsequenced write to and read from variable}}
     // expected-warning at -2{{unsequenced writes to variable}}
 }
+
+static int function_with_auto_lifetimes(void) {
+    int a = 0;
+    int b[2] = {0};
+    float c = 2;
+
+    a++;
+    b[1]--;
+    c = c + a;
+    b[--a] = c;
+
+    return b[0];
+}
+
+static int unsequenced_but_no_ub(void) {
+    return function_with_auto_lifetimes() + function_with_auto_lifetimes();
+}
+
+static unsigned function_with_static_lifetimes(void) {
+    static unsigned a = 0;
+    return a++;
+    // expected-note at -1{{variable is read from here}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-note at -4{{variable is written to here}}
+}
+
+static unsigned unsequenced_with_ub(void) {
+    return function_with_static_lifetimes() - function_with_static_lifetimes();
+    // expected-warning at -1{{unsequenced write to and read from variable}}
+    // expected-warning at -2{{unsequenced writes to variable}}
+}
diff --git a/clang/test/Analysis/unsequenced.cpp b/clang/test/Analysis/unsequenced.cpp
new file mode 100644
index 00000000000000..75a6043abb7fe7
--- /dev/null
+++ b/clang/test/Analysis/unsequenced.cpp
@@ -0,0 +1,71 @@
+// RUN: %clang_analyze_cc1 -verify %s -std=c++11 -analyzer-checker=core
+// RUN: %clang_analyze_cc1 -verify %s -std=c++17 -analyzer-checker=core
+// RUN: %clang_analyze_cc1 -verify %s -analyzer-checker=core
+
+#if __cplusplus >= 201703L
+#   define CPP17
+#endif
+
+void does_nothing2(int, int) {}
+
+void shift_tests() {
+    int a = 1;
+    int b;
+    (void)b;
+
+    b = a++ << a;
+#ifndef CPP17
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+    // expected-warning at -5{{unsequenced modification and access}}
+#endif
+
+    if (a << (++a) != 0) {}
+#ifndef CPP17
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+    // expected-warning at -5{{unsequenced modification and access}}
+#endif
+}
+
+void std_tests() {
+    int a = 1;
+
+    a = a++;
+#ifndef CPP17
+    // expected-warning at -2{{unsequenced writes to variable}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-note at -4{{variable is written to here}}
+    // expected-warning at -5{{multiple unsequenced modifications}}
+#endif
+
+    a = ++a; // No undefined behavior since C++11
+
+    int s[3] = {0};
+    int* sp = s;
+    int j = 0;
+    while(j < 3) (sp + j)[j++] = 1;
+#ifndef CPP17
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+    // expected-warning at -5{{unsequenced modification and access}}
+#endif
+    
+    int r[3];
+    int i = 0;
+    while (i < 3) r[i] = i++;
+#ifndef CPP17
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+    // expected-warning at -5{{unsequenced modification and access}}
+#endif
+
+}
+
+#ifdef CPP17
+    // expected-no-diagnostics
+#endif

>From d3bb8f8100e06fb11ceb75f0ed24341325481944 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= <aron.harnasi at gmail.com>
Date: Sun, 13 Jul 2025 14:53:26 +0200
Subject: [PATCH 08/12] different frame checking

---
 .../Checkers/UnsequencedAccessChecker.cpp     | 48 +++++++++++++------
 clang/test/Analysis/unsequenced.c             |  3 ++
 2 files changed, 37 insertions(+), 14 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
index 29ae8571ec3e7c..089aa963e16eeb 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
@@ -25,7 +25,8 @@ using namespace ento;
 
 namespace {
 
-using StmtVec = llvm::SmallVector<const Stmt*>;
+using AncestorStmt = llvm::PointerIntPair<const Stmt*, 1, bool>;
+using StmtVec = llvm::SmallVector<AncestorStmt>;
 
 class AccessStmt {
     llvm::PointerIntPair<const Stmt*, 1, bool> StmtAndIsStore;
@@ -125,6 +126,7 @@ StmtVec UnsequencedAccessChecker::getAllASTAncestors(
     assert(CurrentFrame != nullptr);
 
     StmtVec Ancestors;
+    bool HasChangedStackFrame = false;
 
     while (true) {
 
@@ -157,15 +159,16 @@ StmtVec UnsequencedAccessChecker::getAllASTAncestors(
 
             ParentS = CurrentFrame->getCallSite();
             CurrentFrame = CurrentFrame->getParent()->getStackFrame();
+            HasChangedStackFrame = true;
         }
         assert(ParentS != nullptr);
 
-        Ancestors.push_back(CurrentS);
+        Ancestors.emplace_back(CurrentS, HasChangedStackFrame);
 
         CurrentS = ParentS;
     }
 
-    Ancestors.push_back(CurrentS);
+    Ancestors.emplace_back(CurrentS, HasChangedStackFrame);
 
     return Ancestors;
 }
@@ -236,8 +239,9 @@ bool UnsequencedAccessChecker::isUnsequencedStmt(
 }
 
 static void print_ancestors(const StmtVec& ancestors) {
-    for (const Stmt* S : ancestors) {
-        std::cout << S->getStmtClassName() << " " << S << std::endl;
+    for (AncestorStmt S : ancestors) {
+        std::cout << S.getPointer()->getStmtClassName() << " " << S.getPointer() 
+                  << std::endl;
     }
 }
 
@@ -383,7 +387,8 @@ void UnsequencedAccessChecker::checkAgainstSet(
         if(checkAncestors(CommonIdx, OtherAccess, OtherAncestors, CurrentAccess,
                           Ancestors, C.getLangOpts())) {
 
-            const Stmt* CommonS = Ancestors[Ancestors.size() - CommonIdx];
+            const Stmt* CommonS =
+                Ancestors[Ancestors.size() - CommonIdx].getPointer();
 
             if (PrintDebugLog) {
                 std::cout << "Common found: " << CommonS << " "
@@ -401,7 +406,7 @@ int UnsequencedAccessChecker::findCommonAncestorIdx(const StmtVec& A,
                                                     const StmtVec& B) {
     unsigned I = 1;
     while (I <= std::min(A.size(), B.size())) {
-        if (A[A.size() - I] != B[B.size() - I])
+        if (A[A.size() - I].getPointer() != B[B.size() - I].getPointer())
             break;
         I++;
     }
@@ -416,15 +421,17 @@ bool UnsequencedAccessChecker::checkAncestors(
         int CommonIdx, AccessStmt A, const StmtVec& AVec, AccessStmt B,
         const StmtVec& BVec, const LangOptions& Opts) const {
 
-    const Stmt* CommonS = AVec[AVec.size() - CommonIdx];
+    const Stmt* CommonS = AVec[AVec.size() - CommonIdx].getPointer();
+
+    bool IsAInDifferentFrame = AVec[AVec.size() - CommonIdx].getInt();
+    bool IsBInDifferentFrame = BVec[BVec.size() - CommonIdx].getInt();
 
     if (const auto* BO = dyn_cast<BinaryOperator>(CommonS)) {
         if (BO->isLogicalOp() || BO->isCommaOp() || BO->isPtrMemOp())
             return false;
 
-        if (Opts.CPlusPlus17 && BO->isShiftOp()) {
+        if (Opts.CPlusPlus17 && BO->isShiftOp())
             return false;
-        }
 
         if (BO->isAssignmentOp()) {
             if (Opts.CPlusPlus17)
@@ -441,7 +448,12 @@ bool UnsequencedAccessChecker::checkAncestors(
                 std::cout << "BSide is: " << BSide << " "
                           << BSide->getStmtClassName() << std::endl;
             }
+
             if (Accessed == A.getExpr()->IgnoreParenCasts()) {
+
+                if (IsBInDifferentFrame)
+                    return false;
+
                 if (!B.isStore())
                     return false;
 
@@ -450,6 +462,10 @@ bool UnsequencedAccessChecker::checkAncestors(
             }
 
             if (Accessed == B.getExpr()->IgnoreParenCasts()) {
+
+                if (IsAInDifferentFrame)
+                    return false;
+
                 if (!A.isStore())
                     return false;
 
@@ -483,8 +499,11 @@ bool UnsequencedAccessChecker::checkAncestors(
         bool AFound = false;
         bool BFound = false;
 
-        const Stmt* AFirstChild = AVec[AVec.size() - CommonIdx - 1];
-        const Stmt* BFirstChild = BVec[BVec.size() - CommonIdx - 1];
+        const Stmt* AFirstChild = 
+            AVec[AVec.size() - CommonIdx - 1].getPointer();
+
+        const Stmt* BFirstChild = 
+            BVec[BVec.size() - CommonIdx - 1].getPointer();
 
         if (!Opts.CPlusPlus17 && AFirstChild == CE->getCallee())
             AFound = true;
@@ -514,10 +533,11 @@ bool UnsequencedAccessChecker::hasClosePreUnaryOperatorAncestor(
 
     int VecSize = Vec.size();
     for (int I = 1; I < VecSize; I++) {
-        if (isa<ParenExpr>(Vec[I]) || isa<CastExpr>(Vec[I]))
+        if (isa<ParenExpr>(Vec[I].getPointer()) ||
+                isa<CastExpr>(Vec[I].getPointer()))
             continue;
 
-        if (const auto* Op = dyn_cast<UnaryOperator>(Vec[I]))
+        if (const auto* Op = dyn_cast<UnaryOperator>(Vec[I].getPointer()))
             return Op->isPrefix();
 
         break;
diff --git a/clang/test/Analysis/unsequenced.c b/clang/test/Analysis/unsequenced.c
index 9965ae7332a425..ccb5dd68e1b68e 100644
--- a/clang/test/Analysis/unsequenced.c
+++ b/clang/test/Analysis/unsequenced.c
@@ -164,6 +164,7 @@ static void function_checks(void) {
 
     float a2 = 0.1f;
     float* fp = &a2;
+    int a3 = 22;
 
     if (inc_and_return(&globalInt) + globalInt) {}
     // expected-warning at -1{{unsequenced write to and read from variable}}
@@ -186,6 +187,8 @@ static void function_checks(void) {
     // expected-warning at -1{{unsequenced writes to variable}}
     // expected-note at -2{{variable is written to here}}
     // expected-note at -3{{variable is written to here}}
+
+    a3 = *inc_and_return(&a3);
 }
 
 static void loop_checks(void) {

>From 0b5e3dff60745f9afb5b2c2529a2075a74259848 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= <aron.harnasi at gmail.com>
Date: Sun, 13 Jul 2025 21:33:42 +0200
Subject: [PATCH 09/12] bit more tests

---
 clang/test/Analysis/unsequenced.cpp | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/clang/test/Analysis/unsequenced.cpp b/clang/test/Analysis/unsequenced.cpp
index 75a6043abb7fe7..f6b887f30e9710 100644
--- a/clang/test/Analysis/unsequenced.cpp
+++ b/clang/test/Analysis/unsequenced.cpp
@@ -28,6 +28,15 @@ void shift_tests() {
     // expected-note at -4{{variable is written to here}}
     // expected-warning at -5{{unsequenced modification and access}}
 #endif
+
+    int i = 0;
+    if(a << (i || (i = a++)) == 0) {}
+#ifndef CPP17
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+    // expected-warning at -5{{unsequenced modification and access}}
+#endif
 }
 
 void std_tests() {
@@ -64,6 +73,14 @@ void std_tests() {
     // expected-warning at -5{{unsequenced modification and access}}
 #endif
 
+    i = 0;
+    r[i] = ++i;
+#ifndef CPP17
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+    // expected-warning at -5{{unsequenced modification and access}}
+#endif
 }
 
 #ifdef CPP17

>From 6314ce4f22cda77cc0367296b12fe7c183a0a225 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= <aron.harnasi at gmail.com>
Date: Mon, 21 Jul 2025 22:43:26 +0200
Subject: [PATCH 10/12] moar tests

---
 .../Checkers/UnsequencedAccessChecker.cpp     | 44 ++++++-----
 clang/test/Analysis/unsequenced.c             | 75 ++++++++++++++++++-
 clang/test/Analysis/unsequenced.cpp           | 54 +++++++++++++
 3 files changed, 155 insertions(+), 18 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
index 089aa963e16eeb..97387bdb7979b2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnsequencedAccessChecker.cpp
@@ -25,6 +25,7 @@ using namespace ento;
 
 namespace {
 
+// The bool in AncestorStmt is set to true if we are indeterminately sequenced.
 using AncestorStmt = llvm::PointerIntPair<const Stmt*, 1, bool>;
 using StmtVec = llvm::SmallVector<AncestorStmt>;
 
@@ -78,11 +79,11 @@ class UnsequencedAccessChecker
     static StmtVec getAllASTAncestors(
             const Stmt* CurrentS, const StackFrameContext* CurrentFrame,
             ParentMapContext& ParentMap, const Stmt* HighestS,
-            const StackFrameContext* HighestFrame,
+            const StackFrameContext* HighestFrame, const LangOptions& Opts,
             bool* DidHitHighest = nullptr);
     static int findCommonAncestorIdx(const StmtVec& A, const StmtVec& B);
 
-    static bool hasClosePreUnaryOperatorAncestor(const StmtVec& S);
+    static bool isStmtPreStore(const StmtVec& S);
 
     void checkAgainstSet(const AccessStmtSet* Set, AccessStmt CurrentAccess,
                          const StmtVec& Ancestors, const Stmt* HighestStmt,
@@ -120,13 +121,14 @@ class UnsequencedAccessChecker
 StmtVec UnsequencedAccessChecker::getAllASTAncestors(
             const Stmt* CurrentS, const StackFrameContext* CurrentFrame,
             ParentMapContext& ParentMap, const Stmt* HighestS,
-            const StackFrameContext* HighestFrame, bool* DidHitHighest) {
+            const StackFrameContext* HighestFrame, const LangOptions& Opts,
+            bool* DidHitHighest) {
 
     assert(CurrentS != nullptr);
     assert(CurrentFrame != nullptr);
 
     StmtVec Ancestors;
-    bool HasChangedStackFrame = false;
+    bool IsIndeterminate = false;
 
     while (true) {
 
@@ -159,16 +161,19 @@ StmtVec UnsequencedAccessChecker::getAllASTAncestors(
 
             ParentS = CurrentFrame->getCallSite();
             CurrentFrame = CurrentFrame->getParent()->getStackFrame();
-            HasChangedStackFrame = true;
+            IsIndeterminate = true;
         }
         assert(ParentS != nullptr);
 
-        Ancestors.emplace_back(CurrentS, HasChangedStackFrame);
+        if ((Opts.C99 || Opts.CPlusPlus17) && isa<CallExpr>(CurrentS))
+            IsIndeterminate = true;
+
+        Ancestors.emplace_back(CurrentS, IsIndeterminate);
 
         CurrentS = ParentS;
     }
 
-    Ancestors.emplace_back(CurrentS, HasChangedStackFrame);
+    Ancestors.emplace_back(CurrentS, IsIndeterminate);
 
     return Ancestors;
 }
@@ -280,7 +285,7 @@ void UnsequencedAccessChecker::checkLocation(
 
     StmtVec Ancestors = getAllASTAncestors(S, C.getStackFrame(), ParentMap,
                                            HighestStmt, HighestFrame,
-                                           &DidHitHighest);
+                                           C.getLangOpts(), &DidHitHighest);
 
     if (!DidHitHighest) {
         std::pair<const Stmt*, const StackFrameContext*> Highest =
@@ -291,7 +296,8 @@ void UnsequencedAccessChecker::checkLocation(
 
         // This could be optimized.
         Ancestors = getAllASTAncestors(S, C.getStackFrame(), ParentMap,
-                                       HighestStmt, HighestFrame);
+                                       HighestStmt, HighestFrame,
+                                       C.getLangOpts());
 
         State = resetState(State);
         State = State->set<HighestUnseqStmt>(HighestStmt)
@@ -379,7 +385,8 @@ void UnsequencedAccessChecker::checkAgainstSet(
 
         StmtVec OtherAncestors =
             getAllASTAncestors(OtherAccess.getStmt(), OtherAccess.getFrame(),
-                               ParentMap, HighestStmt, HighestFrame);
+                               ParentMap, HighestStmt, HighestFrame,
+                               C.getLangOpts());
 
         int CommonIdx = findCommonAncestorIdx(Ancestors, OtherAncestors);
         assert(CommonIdx != -1);
@@ -423,8 +430,8 @@ bool UnsequencedAccessChecker::checkAncestors(
 
     const Stmt* CommonS = AVec[AVec.size() - CommonIdx].getPointer();
 
-    bool IsAInDifferentFrame = AVec[AVec.size() - CommonIdx].getInt();
-    bool IsBInDifferentFrame = BVec[BVec.size() - CommonIdx].getInt();
+    bool IsAIndeterminate = AVec[AVec.size() - CommonIdx].getInt();
+    bool IsBIndeterminate = BVec[BVec.size() - CommonIdx].getInt();
 
     if (const auto* BO = dyn_cast<BinaryOperator>(CommonS)) {
         if (BO->isLogicalOp() || BO->isCommaOp() || BO->isPtrMemOp())
@@ -451,25 +458,25 @@ bool UnsequencedAccessChecker::checkAncestors(
 
             if (Accessed == A.getExpr()->IgnoreParenCasts()) {
 
-                if (IsBInDifferentFrame)
+                if (IsBIndeterminate)
                     return false;
 
                 if (!B.isStore())
                     return false;
 
-                if (Opts.CPlusPlus11 && hasClosePreUnaryOperatorAncestor(BVec))
+                if (Opts.CPlusPlus11 && isStmtPreStore(BVec))
                     return false;
             }
 
             if (Accessed == B.getExpr()->IgnoreParenCasts()) {
 
-                if (IsAInDifferentFrame)
+                if (IsAIndeterminate)
                     return false;
 
                 if (!A.isStore())
                     return false;
 
-                if (Opts.CPlusPlus11 && hasClosePreUnaryOperatorAncestor(AVec))
+                if (Opts.CPlusPlus11 && isStmtPreStore(AVec))
                     return false;
             }
         }
@@ -528,7 +535,7 @@ bool UnsequencedAccessChecker::checkAncestors(
     return false;
 }
 
-bool UnsequencedAccessChecker::hasClosePreUnaryOperatorAncestor(
+bool UnsequencedAccessChecker::isStmtPreStore(
         const StmtVec& Vec) {
 
     int VecSize = Vec.size();
@@ -540,6 +547,9 @@ bool UnsequencedAccessChecker::hasClosePreUnaryOperatorAncestor(
         if (const auto* Op = dyn_cast<UnaryOperator>(Vec[I].getPointer()))
             return Op->isPrefix();
 
+        if (const auto* Op = dyn_cast<BinaryOperator>(Vec[I].getPointer()))
+            return Op->isAssignmentOp();
+
         break;
     }
     std::cout << std::endl;
diff --git a/clang/test/Analysis/unsequenced.c b/clang/test/Analysis/unsequenced.c
index ccb5dd68e1b68e..313f3889afc6d0 100644
--- a/clang/test/Analysis/unsequenced.c
+++ b/clang/test/Analysis/unsequenced.c
@@ -24,6 +24,8 @@ static void binary_op_checks_inline(void) {
     // expected-warning at -2{{unsequenced writes to variable}}
     // expected-note at -3{{variable is written to here}}
     // expected-note at -4{{variable is written to here}}
+    
+    a1 = a1;
 
     b = a1 + b + (++a1);
     // expected-warning at -1{{unsequenced modification and access}}
@@ -104,8 +106,13 @@ static void binary_op_checks_inline(void) {
     // expected-note at -2{{variable is written to here}}
     // expected-note at -3{{variable is written to here}}
     // expected-warning at -4{{multiple unsequenced modifications}}
-
     
+    a1 = a1 = 1;
+    // expected-warning at -1{{unsequenced writes to variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+    // expected-warning at -4{{multiple unsequenced modifications}}
+
     (void)a1; (void)b;
 }
 
@@ -113,6 +120,10 @@ static void* id(void* param) {
     return param;
 }
 
+static int id_i(int param) {
+    return param;
+}
+
 static void binary_op_checks_with_functions(void) {
     int a = 0;
 
@@ -122,6 +133,8 @@ static void binary_op_checks_with_functions(void) {
     // expected-note at -3{{variable is written to here}}
 
     *(int*)id(&a) = a + 1; // Equivalent to a = a + 1;
+    
+    a = id_i(a++);
 }
 
 static void does_nothing2(int a, int b) {
@@ -160,12 +173,25 @@ static int* inc_and_return(int* a) {
 
 int globalInt;
 
+typedef int (*some_fun_t)(int);
+
+static int some_fun_impl(int x) {
+    return 0;
+}
+
+static int inc_global_int(int a) {
+    globalInt++;
+    return a + 1;
+}
+
 static void function_checks(void) {
 
     float a2 = 0.1f;
     float* fp = &a2;
     int a3 = 22;
 
+    some_fun_t some_funs[3] = {0};
+
     if (inc_and_return(&globalInt) + globalInt) {}
     // expected-warning at -1{{unsequenced write to and read from variable}}
     // expected-note at -2{{variable is read from here}}
@@ -189,6 +215,18 @@ static void function_checks(void) {
     // expected-note at -3{{variable is written to here}}
 
     a3 = *inc_and_return(&a3);
+
+    some_funs[1] = some_fun_impl;
+
+    a3 = 1;
+    some_funs[a3](a3++);
+    // expected-warning at -1{{unsequenced modification and access}}
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+    
+    if (inc_global_int(globalInt) == 0) {}
+
 }
 
 static void loop_checks(void) {
@@ -270,3 +308,38 @@ static unsigned unsequenced_with_ub(void) {
     // expected-warning at -1{{unsequenced write to and read from variable}}
     // expected-warning at -2{{unsequenced writes to variable}}
 }
+
+struct int_wrapper {
+    int data;
+};
+
+int post_inc_wrapper(struct int_wrapper* wrap) {
+    wrap->data += 1;
+    // expected-note at -1{{variable is written to here}}
+    return wrap->data;
+}
+
+static void dst_tests(void) {
+    struct int_wrapper wrap = {0};
+
+    if (wrap.data + post_inc_wrapper(&wrap)) {}
+    // expected-warning at -1{{unsequenced write to and read from variable}}
+    // expected-note at -2{{variable is read from here}}
+}
+
+struct two_ints {
+    int a, b;
+};
+
+static void struct_tests(void) {
+    struct two_ints two = { 1, 2 };
+
+    // -Wunsequenced doesn't yet support this
+    two.a = two.a++;
+    // expected-warning at -1{{unsequenced writes to variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+    
+    two = (struct two_ints){ two.a++, 0 };
+    // Not certain
+}
diff --git a/clang/test/Analysis/unsequenced.cpp b/clang/test/Analysis/unsequenced.cpp
index f6b887f30e9710..32f37782093769 100644
--- a/clang/test/Analysis/unsequenced.cpp
+++ b/clang/test/Analysis/unsequenced.cpp
@@ -37,6 +37,8 @@ void shift_tests() {
     // expected-note at -4{{variable is written to here}}
     // expected-warning at -5{{unsequenced modification and access}}
 #endif
+
+    a = a = 1;
 }
 
 void std_tests() {
@@ -83,6 +85,58 @@ void std_tests() {
 #endif
 }
 
+class IntWrapper {
+    int data;
+public:
+    IntWrapper(int d) : data(d) {}
+
+    // Prefix overload
+    IntWrapper operator++() {
+        data += 1;
+        return IntWrapper(data);
+    }
+
+    // Postfix overload
+    IntWrapper operator++(int) {
+        int old_data = data;
+        data += 1;
+        return IntWrapper(old_data);
+    }
+
+    IntWrapper operator+(const IntWrapper& Other) {
+        return IntWrapper(Other.data + data);
+    }
+};
+
+void some_wrapper_func(IntWrapper, IntWrapper);
+
+void object_tests() {
+    IntWrapper A(0);
+
+    IntWrapper I = A + A++;
+
+    some_wrapper_func(A, A++);
+}
+
+typedef int (*some_fun_t)(int);
+
+static int some_fun_impl(int x) {
+    return 0;
+}
+
+void function_tests() {
+    some_fun_t some_funs[2] = {0};
+    some_funs[0] = some_fun_impl;
+    int a = 0;
+    some_funs[a](a++);
+#ifndef CPP17
+    // expected-warning at -2{{unsequenced write to and read from variable}}
+    // expected-note at -3{{variable is read from here}}
+    // expected-note at -4{{variable is written to here}}
+    // expected-warning at -5{{unsequenced modification and access}}
+#endif
+}
+
 #ifdef CPP17
     // expected-no-diagnostics
 #endif

>From dad2aa25691d134ad303bde4cb4e11b966206ad0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= <aron.harnasi at gmail.com>
Date: Fri, 25 Jul 2025 18:25:46 +0200
Subject: [PATCH 11/12] more tests

---
 clang/test/Analysis/unsequenced.c | 27 ++++++++++-----------------
 1 file changed, 10 insertions(+), 17 deletions(-)

diff --git a/clang/test/Analysis/unsequenced.c b/clang/test/Analysis/unsequenced.c
index 313f3889afc6d0..e3456aa736be38 100644
--- a/clang/test/Analysis/unsequenced.c
+++ b/clang/test/Analysis/unsequenced.c
@@ -112,6 +112,16 @@ static void binary_op_checks_inline(void) {
     // expected-note at -2{{variable is written to here}}
     // expected-note at -3{{variable is written to here}}
     // expected-warning at -4{{multiple unsequenced modifications}}
+    
+    (*&a1) = ++a1;
+    // expected-warning at -1{{unsequenced writes to variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
+
+    (*&a1) = a1++;
+    // expected-warning at -1{{unsequenced writes to variable}}
+    // expected-note at -2{{variable is written to here}}
+    // expected-note at -3{{variable is written to here}}
 
     (void)a1; (void)b;
 }
@@ -326,20 +336,3 @@ static void dst_tests(void) {
     // expected-warning at -1{{unsequenced write to and read from variable}}
     // expected-note at -2{{variable is read from here}}
 }
-
-struct two_ints {
-    int a, b;
-};
-
-static void struct_tests(void) {
-    struct two_ints two = { 1, 2 };
-
-    // -Wunsequenced doesn't yet support this
-    two.a = two.a++;
-    // expected-warning at -1{{unsequenced writes to variable}}
-    // expected-note at -2{{variable is written to here}}
-    // expected-note at -3{{variable is written to here}}
-    
-    two = (struct two_ints){ two.a++, 0 };
-    // Not certain
-}

>From ae78250e4c0804440228b9c1dbd6c9e0ec021eb6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= <aron.harnasi at gmail.com>
Date: Sun, 25 Oct 2026 09:46:18 +0100
Subject: [PATCH 12/12] stats checker

---
 .../clang/StaticAnalyzer/Checkers/Checkers.td |  3 ++
 .../Core/PathSensitive/ExplodedGraph.h        |  2 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt    |  1 +
 .../StaticAnalyzer/Checkers/StatsChecker.cpp  | 38 +++++++++++++++++++
 .../lib/StaticAnalyzer/Core/ExplodedGraph.cpp |  1 +
 5 files changed, 45 insertions(+)
 create mode 100644 clang/lib/StaticAnalyzer/Checkers/StatsChecker.cpp

diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 35e8ea05273f84..0ba4f6846a8164 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -240,6 +240,9 @@ def UnsequencedAccessChecker : Checker<"UnsequencedAccess">,
                   Released>]>,
    Documentation<NotDocumented>;
 
+def StatsChecker : Checker<"Stats">,
+   Documentation<NotDocumented>;
+
 } // end "core"
 
 let ParentPackage = CoreAlpha in {
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
index 1a8cf6fc376676..4565ccd4376620 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
@@ -320,6 +320,7 @@ class ExplodedGraph {
 
   /// NumNodes - The number of nodes in the graph.
   int64_t NumNodes = 0;
+  int64_t NumReclaimedNodes = 0;
 
   /// A list of recently allocated nodes that can potentially be recycled.
   NodeVector ChangedNodes;
@@ -376,6 +377,7 @@ class ExplodedGraph {
 
   bool empty() const { return NumNodes == 0; }
   unsigned size() const { return NumNodes; }
+  unsigned reclaimedNodes() const { return NumReclaimedNodes; }
 
   void reserve(unsigned NodeCount) { Nodes.reserve(NodeCount); }
 
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index c6b9fa6cc44af6..fb9e9358b00067 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -131,6 +131,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   UnreachableCodeChecker.cpp
   UnsequencedAccessChecker.cpp
   UseAfterLifetimeEnd.cpp
+  StatsChecker.cpp
   VforkChecker.cpp
   VLASizeChecker.cpp
   VAListChecker.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/StatsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StatsChecker.cpp
new file mode 100644
index 00000000000000..43fb5346bad53f
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/StatsChecker.cpp
@@ -0,0 +1,38 @@
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
+
+#include <iostream>
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+class StatsChecker
+    : public Checker<check::EndAnalysis> {
+
+public:
+  void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
+                        ExprEngine &Engine) const;
+
+};
+} // namespace
+
+void StatsChecker::checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
+                                    ExprEngine &Engine) const
+{
+    std::cout << "END OF ANALYSIS" << std::endl;
+    std::cout << "Number of exploded nodes created: "
+              << G.size() + G.reclaimedNodes() << std::endl;
+    std::cout << "Number of exploded nodes at the end: "
+              << G.size() << std::endl;
+}
+
+
+void ento::registerStatsChecker(CheckerManager &mgr) {
+  auto* Checker = mgr.registerChecker<StatsChecker>();
+}
+
+bool ento::shouldRegisterStatsChecker(const CheckerManager &mgr) {
+  return true;
+}
diff --git a/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp b/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
index a73593baaa184e..e2cc7058e77de8 100644
--- a/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
@@ -160,6 +160,7 @@ void ExplodedGraph::collectNode(ExplodedNode *node) {
   FreeNodes.push_back(node);
   Nodes.erase(node);
   --NumNodes;
+  ++NumReclaimedNodes;
   node->~ExplodedNode();
 }
 



More information about the cfe-commits mailing list