Issue 235706
Summary [clang-tidy] Shared C designated-initializer subtrees cause exponential traversal
Labels clang-tidy
Assignees
Reporter adamtheturtle
    Tested with official LLVM 23.1.4 (`7a941dfb2877a0b8cf30323fefa85ad019e0b0f5`) on Ubuntu 24.04.5, Linux AArch64.

This valid C99 input should produce the single sizeof warning without repeatedly expanding the shared initializer graph.

```c
typedef struct V { const struct V *child; } V;
int main(void) {
  V value = (V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = 0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}};
  (void)value;
  return sizeof(sizeof(int));
}
```

Run from the [reproducer bundle](https://github.com/adamtheturtle/literalizer/blob/609a43270048ac5e733e14b320fc667f6cc5429e/ci/llvm-upstream/README.md):

```sh
timeout 10s clang-tidy reproducers/shared-initializers.c --checks=-*,bugprone-sizeof-_expression_ --config={} -- -std=c99
```

The unmodified release exceeded the ten-second limit (exit 124).
The same input completed in 0.019 seconds with the [candidate implementation](https://github.com/adamtheturtle/literalizer/blob/609a43270048ac5e733e14b320fc667f6cc5429e/ci/llvm-upstream/patches/shared-initializers.patch).
These are single sequential wall-clock samples, not statistical benchmarks.
Raw commands and outputs are in [measurements.json](https://github.com/adamtheturtle/literalizer/blob/609a43270048ac5e733e14b320fc667f6cc5429e/ci/llvm-upstream/measurements.json).

C compound literals and designated initializers expose shared _expression_ nodes through syntactic and semantic forms.
Re-expanding the same children along every incoming path amplifies traversal.

Candidate fix: Preserve every parent edge while expanding each statement once; cache only missing descendant searches, respect direct-child search depth, and avoid duplicate visits in outer compound-literal matching and padding analysis.
The candidate intentionally removes duplicate callbacks for the same _expression_/context.
Parent-edge and positive binding-multiplicity controls are retained in the downstream builder.

The isolated patch applies to LLVM main `fac4500420cdeed42f35537a26eea1e4e17badf0` and contains a regression test.
The new test and the downstream semantic controls were run with the patched 23.1.4 tools; a complete build of current LLVM main has not been performed.

Prepared with AI assistance.

<details>
<summary>Candidate patch, including regression test</summary>

```diff
diff --git a/clang/lib/AST/ParentMapContext.cpp b/clang/lib/AST/ParentMapContext.cpp
index 7607cf27..d2859265 100644
--- a/clang/lib/AST/ParentMapContext.cpp
+++ b/clang/lib/AST/ParentMapContext.cpp
@@ -460,6 +460,11 @@ private:
   // Using generic TraverseNode for Stmt would prevent data-recursion.
   bool dataTraverseStmtPre(Stmt *StmtNode) {
     addParent(StmtNode, &Map.PointerParents);
+    // Shared statements can have several parents, but their outgoing edges
+    // do not depend on the path used to reach them. Record every incoming
+    // edge before skipping descendants already included in the parent map.
+    if (!TraversedStmts.insert(StmtNode).second)
+      return false;
 ParentStack.push_back(DynTypedNode::create(*StmtNode));
     return true;
 }
@@ -469,6 +474,7 @@ private:
   }

   ParentMap &Map;
+ llvm::SmallPtrSet<Stmt *, 32> TraversedStmts;
 llvm::SmallVector<DynTypedNode, 16> ParentStack;
 };

diff --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index 9395b79a..a131831a 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -191,8 +191,28 @@ public:

 if (!match(*StmtToTraverse))
       return false;
+    // No descendant can match a direct-child query below this depth.
+    if (CurrentDepth >= MaxDepth)
+      return true;
     return VisitorBase::TraverseStmt(StmtToTraverse, Queue);
   }
+  // The input bindings and matcher are fixed for this visitor. Cache only
+  // descendant searches with no matches, preserving successful binding
+  // multiplicity even when a statement has several incoming AST edges.
+  bool dataTraverseStmtPre(Stmt *S) {
+    if (MaxDepth == INT_MAX && NoMatchingDescendants.contains(S))
+      return false;
+ MatchCounts.push_back(MatchCount);
+    return true;
+  }
+
+  bool dataTraverseStmtPost(Stmt *S) {
+    if (MaxDepth == INT_MAX && MatchCounts.back() == MatchCount)
+      NoMatchingDescendants.insert(S);
+ MatchCounts.pop_back();
+    return true;
+  }
+
   // We assume that the QualType and the contained type are on the same
   // hierarchy level. Thus, we try to match either of them.
   bool TraverseType(QualType TypeNode, bool TraverseQualifier = true) {
@@ -379,6 +399,7 @@ private:
 if (Matcher->matches(DynTypedNode::create(Node), Finder,
 &RecursiveBuilder)) {
         Matches = true;
+ ++MatchCount;
         ResultBindings.addMatch(RecursiveBuilder);
 return false; // Abort as soon as a match is found.
       }
@@ -388,6 +409,7 @@ private:
                            &RecursiveBuilder)) {
 // After the first match the matcher succeeds.
         Matches = true;
+ ++MatchCount;
         ResultBindings.addMatch(RecursiveBuilder);
 }
     }
@@ -414,6 +436,9 @@ private:
   const bool IgnoreImplicitChildren;
   const ASTMatchFinder::BindKind Bind;
   bool Matches;
+  size_t MatchCount = 0;
+  llvm::SmallVector<size_t, 16> MatchCounts;
+  llvm::SmallPtrSet<const Stmt *, 32> NoMatchingDescendants;
 };

 // Controls the outermost traversal of the AST and allows to match multiple
@@ -775,6 +800,8 @@ public:
   }

 private:
+ std::set<std::tuple<const Stmt *, bool, bool, bool>>
+ TraversedCCompoundLiterals;
   bool TraversingASTNodeNotSpelledInSource = false;
   bool TraversingASTNodeNotAsIs = false;
   bool TraversingASTChildrenNotSpelledInSource = false;
@@ -1549,6 +1576,16 @@ bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode, DataRecursionQueue *Queue) {
 bool ScopedTraversal = TraversingASTNodeNotSpelledInSource ||
 TraversingASTChildrenNotSpelledInSource;

+  // C designated initializers share compound literals between syntactic
+  // and semantic forms. Visit each literal once in each traversal context;
+  // repeating the same subtree adds duplicate callbacks, not new matches.
+  if (!getASTContext().getLangOpts().CPlusPlus &&
+ isa<CompoundLiteralExpr>(StmtNode) &&
+      !TraversedCCompoundLiterals
+ .emplace(StmtNode, ScopedTraversal, TraversingASTNodeNotAsIs,
+ TraversingASTChildrenNotSpelledInSource)
+ .second)
+    return true;
   ASTNodeNotSpelledInSourceScope RAII(this, ScopedTraversal);
   match(*StmtNode);
   return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode, Queue);
diff --git a/clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
index 8fd838c8..8f940503 100644
--- a/clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
@@ -20,6 +20,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"

@@ -44,6 +45,12 @@ public:
 // want to visit those, so we make our own RecursiveASTVisitor.
     struct LocalVisitor : DynamicRecursiveASTVisitor {
       const PaddingChecker *Checker;
+      // Padding depends on declarations, not on the path to a shared
+      // initializer subtree. Still traverse every distinct statement.
+      llvm::SmallPtrSet<const Stmt *, 32> TraversedStmts;
+ bool dataTraverseStmtPre(Stmt *S) override {
+        return TraversedStmts.insert(S).second;
+      }
       explicit LocalVisitor(const PaddingChecker *Checker) : Checker(Checker) {
 ShouldVisitTemplateInstantiations = true;
         ShouldVisitImplicitCode = true;
diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-_expression_-shared-initializers.c b/clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-_expression_-shared-initializers.c
new file mode 100644
index 0000000000000..5855e0d9a100f2bb8614fe6d75deffa51c6ac57d
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-_expression_-shared-initializers.c
@@ -0,0 +1,9 @@
+// RUN: %check_clang_tidy -std=c99 %s bugprone-sizeof-_expression_ %t
+
+typedef struct V { const struct V *child; } V;
+int main(void) {
+  V value = (V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = (V[]){(V){.child = 0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}};
+  (void)value;
+  return sizeof(sizeof(int));
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(sizeof(...))' [bugprone-sizeof-_expression_]
+}

```

</details>


_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to