[clang] Optimize -Wunsafe-buffer-usage. (PR #124554)

Ilya Biryukov via cfe-commits cfe-commits at lists.llvm.org
Mon Jan 27 09:17:58 PST 2025


================
@@ -1986,112 +2327,142 @@ class DerefSimplePtrArithFixableGadget : public FixableGadget {
   }
 };
 
-/// Scan the function and return a list of gadgets found with provided kits.
-static void findGadgets(const Stmt *S, ASTContext &Ctx,
-                        const UnsafeBufferUsageHandler &Handler,
-                        bool EmitSuggestions, FixableGadgetList &FixableGadgets,
-                        WarningGadgetList &WarningGadgets,
-                        DeclUseTracker &Tracker) {
+class EvaluatedStmtMatcher : public CustomMatcher {
 
-  struct GadgetFinderCallback : MatchFinder::MatchCallback {
-    GadgetFinderCallback(FixableGadgetList &FixableGadgets,
-                         WarningGadgetList &WarningGadgets,
-                         DeclUseTracker &Tracker)
-        : FixableGadgets(FixableGadgets), WarningGadgets(WarningGadgets),
-          Tracker(Tracker) {}
-
-    void run(const MatchFinder::MatchResult &Result) override {
-      // In debug mode, assert that we've found exactly one gadget.
-      // This helps us avoid conflicts in .bind() tags.
-#if NDEBUG
-#define NEXT return
-#else
-      [[maybe_unused]] int numFound = 0;
-#define NEXT ++numFound
-#endif
+public:
+  WarningGadgetList &WarningGadgets;
 
-      if (const auto *DRE = Result.Nodes.getNodeAs<DeclRefExpr>("any_dre")) {
-        Tracker.discoverUse(DRE);
-        NEXT;
-      }
+  EvaluatedStmtMatcher(WarningGadgetList &WarningGadgets)
+      : WarningGadgets(WarningGadgets) {}
 
-      if (const auto *DS = Result.Nodes.getNodeAs<DeclStmt>("any_ds")) {
-        Tracker.discoverDecl(DS);
-        NEXT;
-      }
+  bool matches(const DynTypedNode &DynNode, ASTContext &Ctx,
+               const UnsafeBufferUsageHandler &Handler) override {
+    const Stmt *S = DynNode.get<Stmt>();
+    if (!S)
+      return false;
+
+    MatchResult Result;
+#define WARNING_GADGET(name)                                                   \
----------------
ilya-biryukov wrote:

This is a concrete suggestion on how to keep the number of macros the same, a follow-up to the comment above about the duplicated macros.

I would pick a simpler signature for `match` over macros. Could we just add all 4 parameters to every match function and ignore them where they aren't needed?

If the decreased readability is a concern because of long function signatures, we could always introduce a parameter object to counter that. I suspect this won't be necessary, though.


https://github.com/llvm/llvm-project/pull/124554


More information about the cfe-commits mailing list