[clang][-Wunsafe-buffer-usage] Cache the analysis gate per diagnostic state #240433
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang
@llvm/pr-subscribers-clang-analysis
Author: Ilyas Mallah (ilyas-mallah)
<details>
<summary>Changes</summary>
Follow-up to #<!-- -->233604. shouldRunUnsafeBufferUsageAnalysis runs after every function definition, with or without -Wunsafe-buffer-usage, and makes one isIgnored call per diagnostic. The libc-call warning became eight diagnostics, so with the warnings off the gate makes 12 calls per function instead of 5.
The answer is now cached per diagnostic state, keyed and flushed like getPolicyInEffectAt. PredefinedNames is a DenseMap<StringRef>, as aengelke asked in https://github.com/llvm/llvm-project/pull/233604#discussion_r4511893589. The new test changes a subgroup with pragmas between functions and fails if the cache ignores the diagnostic state.
I measured instructions:u with perf stat (release build, no assertions, ASLR off, two runs each) against the same tree without the cache. Interp.cpp at -O3 with its PCH, as CMake builds it: -0.23%. Interp.cpp, SemaDecl.cpp and ParseDecl.cpp with -fsyntax-only: -0.67% to -0.81%. I couldn't reproduce the tracker's setup, so I can't say how much of its +0.166% this recovers.
AI usage: Claude Code helped with the test runs and test scaffolding. I traced the issue, made the fix, and validated every change.
---
Full diff: https://github.com/llvm/llvm-project/pull/240433.diff
4 Files Affected:
````````````diff --git a/clang/include/clang/Sema/AnalysisBasedWarnings.h b/clang/include/clang/Sema/AnalysisBasedWarnings.h
index ea54f7e5ee8aa6..9e217aa36c1660 100644
--- a/clang/include/clang/Sema/AnalysisBasedWarnings.h
+++ b/clang/include/clang/Sema/AnalysisBasedWarnings.h
@@ -71,6 +71,15 @@ class AnalysisBasedWarnings {
llvm::DenseMap<const void *, Policy>
PolicyCache[static_cast<unsigned>(DiagStateSystemClass::NUM_CLASSES)];
+ /// Caches results for shouldRunUnsafeBufferUsageAnalysis(), keyed like
+ /// PolicyCache and flushed with it.
+ llvm::DenseMap<const void *, bool>
+ UnsafeBufferUsageCache[static_cast<unsigned>(
+ DiagStateSystemClass::NUM_CLASSES)];
+
+ /// \return true iff a -Wunsafe-buffer-usage analysis is enabled at \p Loc.
+ bool shouldRunUnsafeBufferUsageAnalysis(SourceLocation Loc);
+
/// \name Statistics
/// @{
@@ -139,7 +148,8 @@ class AnalysisBasedWarnings {
// will override the policy used to issue warnings.
Policy &getPolicyOverrides() { return PolicyOverrides; }
- /// Drop cached getPolicyInEffectAt() results (diagnostic state changed).
+ /// Drop cached getPolicyInEffectAt() and shouldRunUnsafeBufferUsageAnalysis()
+ /// results (diagnostic state changed).
void clearPolicyCache();
void PrintStats() const;
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index b68fc2f20dc56f..388beffb14c534 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -28,10 +28,10 @@
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.h"
+#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include <cstddef>
#include <optional>
@@ -1159,9 +1159,9 @@ hasUnsafeFormatOrSArg(ASTContext &Ctx, const CallExpr *Call,
// match.
static std::optional<UnsafeLibcFunctionFamily>
getPredefinedUnsafeLibcFuncFamily(const FunctionDecl &Node) {
- static const llvm::StringMap<UnsafeLibcFunctionFamily> PredefinedNames = [] {
- using F = UnsafeLibcFunctionFamily;
- llvm::StringMap<F> M;
+ using F = UnsafeLibcFunctionFamily;
+ static const llvm::DenseMap<StringRef, F> PredefinedNames = [] {
+ llvm::DenseMap<StringRef, F> M;
auto Add = [&](F Family, std::initializer_list<StringRef> Names) {
for (StringRef N : Names)
M[N] = Family;
diff --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp b/clang/lib/Sema/AnalysisBasedWarnings.cpp
index de5eb3f093e41b..9b9f627afd8f6d 100644
--- a/clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -2925,6 +2925,8 @@ sema::AnalysisBasedWarnings::getPolicyInEffectAt(SourceLocation Loc) {
void sema::AnalysisBasedWarnings::clearPolicyCache() {
for (auto &M : PolicyCache)
M.clear();
+ for (auto &M : UnsafeBufferUsageCache)
+ M.clear();
}
void sema::AnalysisBasedWarnings::clearOverrides() {
@@ -3103,8 +3105,8 @@ LifetimeSafetyTUAnalysis(Sema &S, TranslationUnitDecl *TU,
}
}
-static bool shouldRunUnsafeBufferUsageAnalysis(const Sema &S,
- SourceLocation Loc) {
+static bool isUnsafeBufferUsageAnalysisEnabledAt(const Sema &S,
+ SourceLocation Loc) {
const DiagnosticsEngine &Diags = S.getDiagnostics();
return !Diags.isIgnored(diag::warn_unsafe_buffer_operation, Loc) ||
!Diags.isIgnored(diag::warn_unsafe_buffer_variable, Loc) ||
@@ -3116,6 +3118,25 @@ static bool shouldRunUnsafeBufferUsageAnalysis(const Sema &S,
!Diags.isIgnored(diag::warn_unsafe_buffer_format_attr_call, Loc)));
}
+// This runs at the end of every function definition, so the answer is cached
+// on the diagnostic state at Loc like getPolicyInEffectAt().
+bool sema::AnalysisBasedWarnings::shouldRunUnsafeBufferUsageAnalysis(
+ SourceLocation Loc) {
+ DiagnosticsEngine &D = S.getDiagnostics();
+ if (D.hasDiagSuppressionMapping() || Loc.isInvalid())
+ return isUnsafeBufferUsageAnalysisEnabledAt(S, Loc);
+
+ const void *StateKey = D.getDiagStateKeyForLoc(Loc);
+ auto &Cache = UnsafeBufferUsageCache[static_cast<unsigned>(
+ D.getDiagStateSystemClassForLoc(Loc))];
+ auto It = Cache.find(StateKey);
+ if (It != Cache.end())
+ return It->second;
+ bool Enabled = isUnsafeBufferUsageAnalysisEnabledAt(S, Loc);
+ Cache[StateKey] = Enabled;
+ return Enabled;
+}
+
/// \return true iff fix-its should be emitted along with -Wunsafe-buffer-usage
/// warnings
static bool shouldEmitUnsafeBufferUsageSuggestions(const Sema &S) {
@@ -3156,7 +3177,7 @@ void clang::sema::AnalysisBasedWarnings::IssueWarnings(
return;
// Perform unsafe buffer usage analysis:
- if (shouldRunUnsafeBufferUsageAnalysis(S, Node->getBeginLoc())) {
+ if (shouldRunUnsafeBufferUsageAnalysis(Node->getBeginLoc())) {
clang::checkUnsafeBufferUsage(Node, R,
/*EmitSuggestion =*/true);
}
@@ -3166,7 +3187,7 @@ void clang::sema::AnalysisBasedWarnings::IssueWarnings(
// Emit per-function analysis-based warnings that require the whole-TU
// reasoning. Check if any of them is enabled at all before scanning the
// AST:
- if (shouldRunUnsafeBufferUsageAnalysis(S, SourceLocation())) {
+ if (shouldRunUnsafeBufferUsageAnalysis(SourceLocation())) {
CallableVisitor(CallAnalyzers, TU->getOwningModule())
.TraverseTranslationUnitDecl(TU);
}
@@ -3445,7 +3466,7 @@ void clang::sema::AnalysisBasedWarnings::IssueWarnings(
shouldSuggestUnsafeBufferUsageSuggestions(S));
// Perform unsafe buffer usage analysis:
- if (shouldRunUnsafeBufferUsageAnalysis(S, D->getBeginLoc())) {
+ if (shouldRunUnsafeBufferUsageAnalysis(D->getBeginLoc())) {
clang::checkUnsafeBufferUsage(
D, R, /*UnsafeBufferUsageShouldEmitSuggestions=*/false);
}
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-in-libc-call-pragma.cpp b/clang/test/SemaCXX/warn-unsafe-buffer-usage-in-libc-call-pragma.cpp
new file mode 100644
index 00000000000000..e8f2350a0882de
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-in-libc-call-pragma.cpp
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+// The analysis is skipped for a function when none of its warnings is
+// enabled, so changing a libc-call subgroup with a pragma between functions
+// has to change what runs.
+
+typedef __SIZE_TYPE__ size_t;
+
+void *memcpy(void *, const void *, size_t);
+
+void before(void *p, const void *q, size_t n) {
+ memcpy(p, q, n);
+}
+
+#pragma clang diagnostic warning "-Wunsafe-buffer-usage-in-libc-call-memory"
+
+void enabled(void *p, const void *q, size_t n) {
+ memcpy(p, q, n); // expected-warning{{function 'memcpy' is unsafe}}
+}
+
+// A function is checked after the pragmas that follow it are read, so this
+// declaration makes ignored() the first function checked once they apply.
+void ignored(void *p, const void *q, size_t n);
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunsafe-buffer-usage-in-libc-call-memory"
+
+void ignored(void *p, const void *q, size_t n) {
+ memcpy(p, q, n);
+}
+
+#pragma clang diagnostic pop
+
+void enabled_again(void *p, const void *q, size_t n) {
+ memcpy(p, q, n); // expected-warning{{function 'memcpy' is unsafe}}
+}
</details>
Nit: Could we use try_emplace here to avoid a second DenseMap lookup on cache misses?
auto [It, Inserted] = Cache.try_emplace(StateKey);
if (Inserted)
It->second = isUnsafeBufferUsageAnalysisEnabledAt(S, Loc);
return It->second;
Done!
@aengelke @kazutakahirata CI hadn't run on the last head, so I merged main. Linux and Windows pass now. The macOS job stops at CMake configure because the runner's CMake needs a newer macOS. This is the compile-time follow-up to #233604. Could one of you take a look?
/compile-time
Compile-time results for dad92a8d0c3890de680d4e188028924af15e1e51 (base 3f679c2a42e1a018b4539bb81e31529deb4ce647):
https://llvm-compile-time-tracker.com/compare.php?from=3f679c2a42e1a018b4539bb81e31529deb4ce647&to=dad92a8d0c3890de680d4e188028924af15e1e51&stat=instructions%3Au
| Config | instructions:u |
|:--|--:|
| stage1-O3 | +0.00% |
| stage1-ReleaseThinLTO | +0.00% |
| stage1-ReleaseLTO-g | +0.02% |
| stage1-O0-g | +0.01% |
| stage1-aarch64-O3 | +0.00% |
| stage1-aarch64-O0-g | +0.02% |
| stage2-O3 | +0.00% |
| stage2-O0-g | +0.00% |
| clang build | -0.15% |
Changes in bold are likely significant.
@aengelke The clang build takes 0.15% fewer instructions with this, nearly all of the 0.166% that #233604 added. The other configs stay within 0.02%.
Yes, I read that. Nevertheless, I'm not at all familiar with clang/Sema and therefore can't review this.
@AaronBallman @Sirraide Could one of you review the Sema change? It caches the check that decides whether to run the unsafe buffer analysis per diagnostic state, the way #212213 cached the warning policy.
@AaronBallman @Sirraide Weekly ping on the Sema change. CI is green and the branch is mergeable. Is the per diagnostic state cache acceptable as written, or would you rather see it somewhere else?
kazutakahirata
ilyas-mallah
Follow-up to #233604. shouldRunUnsafeBufferUsageAnalysis runs after every function definition, with or without -Wunsafe-buffer-usage, and makes one isIgnored call per diagnostic. The libc-call warning became eight diagnostics, so with the warnings off the gate makes 12 calls per function instead of 5.
The answer is now cached per diagnostic state, keyed and flushed like getPolicyInEffectAt. PredefinedNames is a DenseMap<StringRef>, as aengelke asked in https://github.com/llvm/llvm-project/pull/233604#discussion_r4511893589. The new test changes a subgroup with pragmas between functions and fails if the cache ignores the diagnostic state.
I measured instructions:u with perf stat (release build, no assertions, ASLR off, two runs each) against the same tree without the cache. Interp.cpp at -O3 with its PCH, as CMake builds it: -0.23%. Interp.cpp, SemaDecl.cpp and ParseDecl.cpp with -fsyntax-only: -0.67% to -0.81%. The compile-time tracker measures the clang build at -0.15% instructions:u, nearly all of the +0.166% that #233604 added.
AI usage: Claude Code helped with the test runs and test scaffolding. I traced the issue, made the fix, and validated every change.