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

Ilya Biryukov via cfe-commits cfe-commits at lists.llvm.org
Thu Jan 30 01:38:43 PST 2025


================
@@ -68,32 +70,60 @@ static std::string getDREAncestorString(const DeclRefExpr *DRE,
 
     if (StParents.size() > 1)
       return "unavailable due to multiple parents";
-    if (StParents.size() == 0)
+    if (StParents.empty())
       break;
     St = StParents.begin()->get<Stmt>();
     if (St)
       SS << " ==> ";
   } while (St);
   return SS.str();
 }
+
 } // namespace
 #endif /* NDEBUG */
 
-namespace clang::ast_matchers {
+namespace {
+// Using a custom matcher instead of ASTMatchers to achieve better performance.
+class FastMatcher {
+public:
+  virtual bool matches(const DynTypedNode &DynNode, ASTContext &Ctx,
+                       const UnsafeBufferUsageHandler &Handler) = 0;
+  virtual ~FastMatcher() = default;
+};
+
+class MatchResult {
+
+public:
+  template <typename T> const T *getNodeAs(StringRef ID) const {
+    auto It = Nodes.find(std::string(ID));
+    if (It == Nodes.end()) {
+      return nullptr;
+    }
+    return It->second.get<T>();
+  }
+
+  void addNode(StringRef ID, const DynTypedNode &Node) {
+    Nodes[std::string(ID)] = Node;
+  }
+
+private:
+  llvm::StringMap<DynTypedNode>
+      Nodes; // DynTypedNode needed to store different types of Nodes, not
+             // necessarily sharing the same base.
+};
+} // namespace
+
 // A `RecursiveASTVisitor` that traverses all descendants of a given node "n"
 // except for those belonging to a different callable of "n".
 class MatchDescendantVisitor : public DynamicRecursiveASTVisitor {
 public:
   // Creates an AST visitor that matches `Matcher` on all
   // descendants of a given node "n" except for the ones
   // belonging to a different callable of "n".
-  MatchDescendantVisitor(const internal::DynTypedMatcher *Matcher,
-                         internal::ASTMatchFinder *Finder,
-                         internal::BoundNodesTreeBuilder *Builder,
-                         internal::ASTMatchFinder::BindKind Bind,
+  MatchDescendantVisitor(FastMatcher &Matcher, bool FindAll,
                          const bool ignoreUnevaluatedContext)
-      : Matcher(Matcher), Finder(Finder), Builder(Builder), Bind(Bind),
-        Matches(false), ignoreUnevaluatedContext(ignoreUnevaluatedContext) {
+      : Matcher(&Matcher), FindAll(FindAll), Matches(false),
+        ignoreUnevaluatedContext(ignoreUnevaluatedContext) {
----------------
ilya-biryukov wrote:

Please initialize `ActiveASTContext` and `Handler` with `nullptr` to ensure there is reliably a crash, and not UB, if the corresponding methods aren't called.

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


More information about the cfe-commits mailing list