================
@@ -1620,6 +1620,43 @@ void Sema::ActOnEndOfTranslationUnit() {
   if (Context.hasAnyFunctionEffects())
     performFunctionEffectAnalysis(Context.getTranslationUnitDecl());
 
+  // Diagnose unused-but-set static globals in a deterministic order.
+  // Not tracking shadowing info for static globals; there's nothing to shadow.
+  struct LocAndDiag {
+    SourceLocation Loc;
+    PartialDiagnostic PD;
+  };
+  SmallVector<LocAndDiag, 16> DeclDiags;
+  auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
+    DeclDiags.push_back(LocAndDiag{Loc, std::move(PD)});
+  };
+
+  // For -Wunused-but-set-variable we only care about variables that were
+  // referenced by the TU end.
+  SmallVector<const VarDecl *, 16> DeclsToErase;
+  for (const auto &Ref : RefsMinusAssignments) {
+    const VarDecl *VD = Ref.first;
+    // Only diagnose static file vars defined in the main file to match
+    // -Wunused-variable behavior and avoid false positives from header vars.
+    if (VD->isStaticFileVar() && SourceMgr.isInMainFile(VD->getLocation())) {
+      DiagnoseUnusedButSetDecl(VD, addDiag);
+      DeclsToErase.push_back(VD);
+    }
+  }
+  for (const VarDecl *VD : DeclsToErase) {
+    RefsMinusAssignments.erase(VD);
+  }
+
+  llvm::sort(DeclDiags,
+             [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
+               // Sorting purely for determinism; matches behavior in
+               // SemaDecl.cpp.
+               return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
----------------
jpjepko wrote:

I modeled some of the logic here after the diagnosing logic in 
`Sema::ActOnPopScope()`. The comment there mentions it's sorted to ensure the 
diagnostics are emitted deterministically (I imagine that's important for 
testing, for example), but there's still the limitation with macros you brought 
up:

https://github.com/llvm/llvm-project/blob/4831bf9e48553faff6095ec087557375bcaf4341/clang/lib/Sema/SemaDecl.cpp#L2327-L2334

Perhaps there's a better way to handle macros when sorting, if so then it would 
make sense to also update the existing sort in `SemaDecl.cpp`. 

https://github.com/llvm/llvm-project/pull/178342
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to