[clang] [clang][StaticAnalyzer] Implement per checker suppression for CSA (PR #247788)

Rashmi Mudduluru via cfe-commits cfe-commits at lists.llvm.org
Tue Dec 1 12:58:56 PST 2026


https://github.com/t-rasmud created https://github.com/llvm/llvm-project/pull/247788

Suppress warnings for checkers that are passed as arguments to `clang::suppress`

rdar://190762170

Co-authored with claude.

>From 80f3503decd7c7dc00ba9bb1fcd69ae11269ca71 Mon Sep 17 00:00:00 2001
From: Rashmi Mudduluru <r_mudduluru at apple.com>
Date: Tue, 29 Sep 2026 10:58:28 -0700
Subject: [PATCH] [clang][StaticAnalyzer] Implement per checker suppression for
 CSA

Suppress warnings for checkers that are passed as arguments to `clang::suppress`

rdar://190762170

Co-authored with claude.
---
 .../Core/BugReporter/BugSuppression.h         |  24 ++--
 .../StaticAnalyzer/Core/BugSuppression.cpp    | 102 +++++++------
 .../clang-suppress/diagnostic-identifiers.cpp | 136 ++++++++++++++++--
 3 files changed, 195 insertions(+), 67 deletions(-)

diff --git a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugSuppression.h b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugSuppression.h
index 35ae06575eaa06..c6fe4019ed46f6 100644
--- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugSuppression.h
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugSuppression.h
@@ -17,6 +17,7 @@
 #include "clang/Basic/SourceLocation.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
 
 namespace clang {
 class ASTContext;
@@ -30,24 +31,29 @@ class BugSuppression {
 public:
   explicit BugSuppression(const ASTContext &ACtx) : ACtx(ACtx) {}
 
-  using DiagnosticIdentifierList = llvm::ArrayRef<llvm::StringRef>;
-
   /// Return true if the given bug report was explicitly suppressed by the user.
   bool isSuppressed(const BugReport &);
 
-  /// Return true if the bug reported at the given location was explicitly
-  /// suppressed by the user.
+  /// Return true if the bug reported at the given location, by the checker
+  /// with the given name, was explicitly suppressed by the user.
   bool isSuppressed(const PathDiagnosticLocation &Location,
-                    const Decl *DeclWithIssue,
-                    DiagnosticIdentifierList DiagnosticIdentification);
+                    const Decl *DeclWithIssue, llvm::StringRef CheckerName);
+
+  /// Struct representing a single `[[clang::suppress]]` attribute in the
+  /// source: the source range it covers and the checkers it applies to.
+  /// An empty `CheckerNames` means all checkers are suppressed in that range.
+  struct Suppression {
+    SourceRange Range;
+    llvm::SmallVector<llvm::StringRef, 2> CheckerNames;
+  };
 
 private:
   // Overly pessimistic number, to be honest.
   static constexpr unsigned EXPECTED_NUMBER_OF_SUPPRESSIONS = 8;
-  using CachedRanges =
-      llvm::SmallVector<SourceRange, EXPECTED_NUMBER_OF_SUPPRESSIONS>;
+  using CachedSuppressions =
+      llvm::SmallVector<Suppression, EXPECTED_NUMBER_OF_SUPPRESSIONS>;
 
-  llvm::DenseMap<const Decl *, CachedRanges> CachedSuppressionLocations;
+  llvm::DenseMap<const Decl *, CachedSuppressions> CachedSuppressionLocations;
 
   const ASTContext &ACtx;
 };
diff --git a/clang/lib/StaticAnalyzer/Core/BugSuppression.cpp b/clang/lib/StaticAnalyzer/Core/BugSuppression.cpp
index 70664c0a9063e6..2023cc07bd0300 100644
--- a/clang/lib/StaticAnalyzer/Core/BugSuppression.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugSuppression.cpp
@@ -19,24 +19,37 @@ using namespace ento;
 
 namespace {
 
-using Ranges = llvm::SmallVectorImpl<SourceRange>;
-
-inline bool hasSuppression(const Decl *D) {
-  // FIXME: Implement diagnostic identifier arguments
-  // (checker names, "hashtags").
-  if (const auto *Suppression = D->getAttr<SuppressAttr>())
-    return !Suppression->isGSL() &&
-           (Suppression->diagnosticIdentifiers().empty());
-  return false;
+using Suppressions = llvm::SmallVectorImpl<BugSuppression::Suppression>;
+
+// A checker name matches an identifier attached to `[[clang::suppress]]`
+// (e.g. "core.NullDereference") if the identifier names the checker exactly,
+// or names an enclosing package of it (e.g. "core" or "unix.Malloc" matching
+// "unix.MallocSizeof").
+inline bool checkerNameMatches(StringRef CheckerName, StringRef Identifier) {
+  if (!CheckerName.starts_with(Identifier))
+    return false;
+  return CheckerName.size() == Identifier.size() ||
+         CheckerName[Identifier.size()] == '.';
 }
-inline bool hasSuppression(const AttributedStmt *S) {
-  // FIXME: Implement diagnostic identifier arguments
-  // (checker names, "hashtags").
-  return llvm::any_of(S->getAttrs(), [](const Attr *A) {
-    const auto *Suppression = dyn_cast<SuppressAttr>(A);
-    return Suppression && !Suppression->isGSL() &&
-           (Suppression->diagnosticIdentifiers().empty());
-  });
+
+using SuppressAttrs = llvm::SmallVector<const SuppressAttr *, 2>;
+
+// A node may carry several [[clang::suppress]] attributes, and each of them
+// contributes its own identifiers.
+inline SuppressAttrs getSuppressions(const Decl *D) {
+  SuppressAttrs Result;
+  for (const auto *A : D->specific_attrs<SuppressAttr>())
+    if (!A->isGSL())
+      Result.push_back(A);
+  return Result;
+}
+inline SuppressAttrs getSuppressions(const AttributedStmt *S) {
+  SuppressAttrs Result;
+  for (const Attr *A : S->getAttrs())
+    if (const auto *Suppression = dyn_cast<SuppressAttr>(A))
+      if (!Suppression->isGSL())
+        Result.push_back(Suppression);
+  return Result;
 }
 
 template <class NodeType> inline SourceRange getRange(const NodeType *Node) {
@@ -82,7 +95,7 @@ inline bool fullyContains(SourceRange Larger, SourceRange Smaller,
 
 class CacheInitializer : public DynamicRecursiveASTVisitor {
 public:
-  static void initialize(const Decl *D, Ranges &ToInit) {
+  static void initialize(const Decl *D, Suppressions &ToInit) {
     CacheInitializer(ToInit).TraverseDecl(const_cast<Decl *>(D));
   }
 
@@ -103,29 +116,28 @@ class CacheInitializer : public DynamicRecursiveASTVisitor {
 
 private:
   template <class NodeType> bool VisitAttributedNode(NodeType *Node) {
-    if (hasSuppression(Node)) {
-      // TODO: In the future, when we come up with good stable IDs for checkers
-      //       we can return a list of kinds to ignore, or all if no arguments
-      //       were provided.
-      addRange(getRange(Node));
-    }
+    for (const SuppressAttr *Suppression : getSuppressions(Node))
+      addRange(getRange(Node),
+               ArrayRef(Suppression->diagnosticIdentifiers_begin(),
+                        Suppression->diagnosticIdentifiers_end()));
     // We should keep traversing AST.
     return true;
   }
 
-  void addRange(SourceRange R) {
+  void addRange(SourceRange R, ArrayRef<StringRef> Names) {
     if (R.isValid()) {
-      Result.push_back(R);
+      Result.push_back(
+          BugSuppression::Suppression{R, {Names.begin(), Names.end()}});
     }
   }
 
-  CacheInitializer(Ranges &R) : Result(R) {
+  CacheInitializer(Suppressions &R) : Result(R) {
     ShouldVisitTemplateInstantiations = true;
     ShouldWalkTypesOfTypeLocs = false;
     ShouldVisitImplicitCode = false;
     ShouldVisitLambdaBody = true;
   }
-  Ranges &Result;
+  Suppressions &Result;
 };
 
 std::string timeScopeName(const Decl *DeclWithIssue) {
@@ -153,18 +165,14 @@ llvm::TimeTraceMetadata getDeclTimeTraceMetadata(const Decl *DeclWithIssue) {
 
 } // end anonymous namespace
 
-// TODO: Introduce stable IDs for checkers and check for those here
-//       to be more specific.  Attribute without arguments should still
-//       be considered as "suppress all".
-//       It is already much finer granularity than what we have now
-//       (i.e. removing the whole function from the analysis).
 bool BugSuppression::isSuppressed(const BugReport &R) {
   PathDiagnosticLocation Location = R.getLocation();
   PathDiagnosticLocation UniqueingLocation = R.getUniqueingLocation();
   const Decl *DeclWithIssue = R.getDeclWithIssue();
+  StringRef CheckerName = R.getBugType().getCheckerName();
 
-  return isSuppressed(Location, DeclWithIssue, {}) ||
-         isSuppressed(UniqueingLocation, DeclWithIssue, {});
+  return isSuppressed(Location, DeclWithIssue, CheckerName) ||
+         isSuppressed(UniqueingLocation, DeclWithIssue, CheckerName);
 }
 
 static const ClassTemplateDecl *
@@ -269,7 +277,7 @@ preferTemplateDefinitionForTemplateSpecializations(const Decl *D) {
 
 bool BugSuppression::isSuppressed(const PathDiagnosticLocation &Location,
                                   const Decl *DeclWithIssue,
-                                  DiagnosticIdentifierList Hashtags) {
+                                  StringRef CheckerName) {
   if (!Location.isValid())
     return false;
 
@@ -317,21 +325,29 @@ bool BugSuppression::isSuppressed(const PathDiagnosticLocation &Location,
   // large functions with a lot of bugs it can make a dent in performance.
   // In order to avoid this scenario, we cache traversal results.
   auto InsertionResult = CachedSuppressionLocations.insert(
-      std::make_pair(DeclWithIssue, CachedRanges{}));
-  Ranges &SuppressionRanges = InsertionResult.first->second;
+      std::make_pair(DeclWithIssue, CachedSuppressions{}));
+  CachedSuppressions &DeclSuppressions = InsertionResult.first->second;
   if (InsertionResult.second) {
     llvm::TimeTraceScope TimeScope(
         timeScopeName(DeclWithIssue),
         [DeclWithIssue]() { return getDeclTimeTraceMetadata(DeclWithIssue); });
     // We haven't checked this declaration for suppressions yet!
-    CacheInitializer::initialize(DeclWithIssue, SuppressionRanges);
+    CacheInitializer::initialize(DeclWithIssue, DeclSuppressions);
   }
 
   SourceRange BugRange = Location.asRange();
   const SourceManager &SM = Location.getManager();
 
-  return llvm::any_of(SuppressionRanges,
-                      [BugRange, &SM](SourceRange Suppression) {
-                        return fullyContains(Suppression, BugRange, SM);
-                      });
+  return llvm::any_of(
+      DeclSuppressions, [&](const Suppression &S) {
+        if (!fullyContains(S.Range, BugRange, SM))
+          return false;
+        // An empty checker-name list means the suppression applies to
+        // every checker (the attribute's traditional argument-less form).
+        if (S.CheckerNames.empty())
+          return true;
+        return llvm::any_of(S.CheckerNames, [&](StringRef Identifier) {
+          return checkerNameMatches(CheckerName, Identifier);
+        });
+      });
 }
diff --git a/clang/test/Analysis/clang-suppress/diagnostic-identifiers.cpp b/clang/test/Analysis/clang-suppress/diagnostic-identifiers.cpp
index 293f6fe12021c5..916d8fe31d2f18 100644
--- a/clang/test/Analysis/clang-suppress/diagnostic-identifiers.cpp
+++ b/clang/test/Analysis/clang-suppress/diagnostic-identifiers.cpp
@@ -15,16 +15,13 @@ void bare_suppress() {
 }
 
 void suppress_with_identifier() {
-  // FIXME: This should suppress debug.ExprInspection warnings, but currently
-  // any identifier makes the suppression a no-op.
   [[clang::suppress("debug.ExprInspection")]] {
-    clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+    clang_analyzer_warnIfReached(); // no-warning: checker name matches
   }
 }
 
 void suppress_with_wrong_identifier() {
-  // Even with the wrong checker name, the current behavior is the same:
-  // any identifier makes the suppression a no-op.
+  // A non-matching checker name does not suppress the report.
   [[clang::suppress("alpha.SomeOtherChecker")]] {
     clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
   }
@@ -38,9 +35,8 @@ void suppress_with_wrong_identifier() {
   clang_analyzer_warnIfReached(); // no-warning
 }
 
-// FIXME: Should suppress, but currently identifiers disable suppression.
 [[clang::suppress("debug.ExprInspection")]] void decl_with_identifier() {
-  clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+  clang_analyzer_warnIfReached(); // no-warning
 }
 
 // ============================================================================
@@ -53,7 +49,7 @@ struct [[clang::suppress]] C_BareSuppressedClass {
   }
 };
 
-// FIXME: Should suppress, but identifiers disable suppression.
+// "core" does not name debug.ExprInspection's package, so no suppression.
 struct [[clang::suppress("core")]] C_IdentifierSuppressedClass {
   void method() {
     clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
@@ -65,10 +61,14 @@ struct [[clang::suppress("core")]] C_IdentifierSuppressedClass {
 // ============================================================================
 
 void multiple_identifiers() {
-  // FIXME: Multiple identifiers — currently treated as a no-op.
+  // None of the identifiers match debug.ExprInspection.
   [[clang::suppress("core.NullDereference", "core.DivideZero")]] {
     clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
   }
+  // Any one matching identifier is enough.
+  [[clang::suppress("core.DivideZero", "debug.ExprInspection")]] {
+    clang_analyzer_warnIfReached(); // no-warning
+  }
 }
 
 // ============================================================================
@@ -76,7 +76,7 @@ void multiple_identifiers() {
 // ============================================================================
 
 void empty_string_identifier() {
-  // An empty string is still a non-empty identifier list.
+  // An empty string is still a non-empty identifier list and matches nothing.
   [[clang::suppress("")]] {
     clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
   }
@@ -91,9 +91,8 @@ void mixed_suppressions() {
     clang_analyzer_warnIfReached(); // no-warning: bare suppress works
   }
 
-  // FIXME: Should suppress too, but identifiers disable it.
   [[clang::suppress("debug.ExprInspection")]] {
-    clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+    clang_analyzer_warnIfReached(); // no-warning
   }
 }
 
@@ -107,9 +106,116 @@ namespace [[clang::suppress]] G_BareNS {
   }
 } // namespace G_BareNS
 
-// FIXME: Should suppress, but identifiers disable it.
-namespace [[clang::suppress("core")]] G_IdentifierNS {
+namespace [[clang::suppress("debug.ExprInspection")]] G_IdentifierNS {
   void func() {
-    clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+    clang_analyzer_warnIfReached(); // no-warning
   }
 } // namespace G_IdentifierNS
+
+// ============================================================================
+// Group H: Package-prefix matching
+// ============================================================================
+
+void package_prefix() {
+  // A package name suppresses every checker in that package.
+  [[clang::suppress("debug")]] {
+    clang_analyzer_warnIfReached(); // no-warning
+  }
+}
+
+void partial_component_does_not_match() {
+  // Matching is on '.'-separated components, not raw string prefixes.
+  [[clang::suppress("debug.Expr")]] {
+    clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+  }
+  [[clang::suppress("deb")]] {
+    clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+  }
+}
+
+void identifier_longer_than_checker_name() {
+  [[clang::suppress("debug.ExprInspection.Extra")]] {
+    clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+  }
+}
+
+// ============================================================================
+// Group I: Real checkers
+// ============================================================================
+
+int null_deref_matching() {
+  int *p = 0;
+  [[clang::suppress("core.NullDereference")]]
+  return *p; // no-warning
+}
+
+int null_deref_package() {
+  int *p = 0;
+  [[clang::suppress("core")]]
+  return *p; // no-warning
+}
+
+int null_deref_other_checker() {
+  int *p = 0;
+  [[clang::suppress("core.DivideZero")]]
+  return *p; // expected-warning{{Dereference of null pointer}}
+}
+
+int only_matching_checker_suppressed(int x) {
+  int *p = 0;
+  [[clang::suppress("core.NullDereference")]] {
+    if (x == 0)
+      return 1 / x; // expected-warning{{Division by zero}}
+  }
+  return *p; // expected-warning{{Dereference of null pointer}}
+}
+
+// ============================================================================
+// Group J: Two checkers warning on the same line
+// ============================================================================
+
+int two_checkers_none_suppressed() {
+  int *p = 0;
+  // expected-warning at +2{{REACHABLE}}
+  // expected-warning at +1{{Dereference of null pointer}}
+  return (clang_analyzer_warnIfReached(), *p);
+}
+
+int two_checkers_both_suppressed() {
+  int *p = 0;
+  [[clang::suppress("debug.ExprInspection", "core.NullDereference")]]
+  return (clang_analyzer_warnIfReached(), *p); // no-warning
+}
+
+int two_checkers_both_suppressed1() {
+  int *p = 0;
+  [[clang::suppress("debug.ExprInspection")]] [[clang::suppress("core.NullDereference")]]
+  return (clang_analyzer_warnIfReached(), *p); // no-warning
+}
+
+int two_checkers_bare_suppress() {
+  int *p = 0;
+  [[clang::suppress]]
+  return (clang_analyzer_warnIfReached(), *p); // no-warning
+}
+
+int two_checkers_only_first_suppressed() {
+  int *p = 0;
+  [[clang::suppress("debug.ExprInspection")]]
+  return (clang_analyzer_warnIfReached(), *p); // expected-warning{{Dereference of null pointer}}
+}
+
+int two_checkers_only_second_suppressed() {
+  int *p = 0;
+  [[clang::suppress("core.NullDereference")]]
+  return (clang_analyzer_warnIfReached(), *p); // expected-warning{{REACHABLE}}
+}
+
+int two_checkers_nested_suppressions() {
+  int *p = 0;
+  // Each attribute suppresses one of the two checkers; together they cover both.
+  [[clang::suppress("debug.ExprInspection")]] {
+    [[clang::suppress("core.NullDereference")]]
+    return (clang_analyzer_warnIfReached(), *p); // no-warning
+  }
+}



More information about the cfe-commits mailing list