Author: Arseniy Zaostrovnykh
Date: 2026-11-17T09:10:59+01:00
New Revision: ea8f36531aac3b911b1b7c1382fe2a247574f00e

URL: 
https://github.com/llvm/llvm-project/commit/ea8f36531aac3b911b1b7c1382fe2a247574f00e
DIFF: 
https://github.com/llvm/llvm-project/commit/ea8f36531aac3b911b1b7c1382fe2a247574f00e.diff

LOG: [analyzer] Add an option to support unity-builds in CSA

Unity-build, a.k.a jumbo-build or unified-build is a practice to build
multiple C or C++ source files in a single compilation command by
including them into a synthetic TU main file using preprocessor
`#include` directives.

By default CSA would skip all functions in the files that are compiled
in this manner because the said functions would not be defined in the
"main TU" file, but in "headers", that are really #include'd sources.

Add unitybuild-file-extensions option (empty by default) that enables
CSA to start analysis of functions defined in #include'd files as long
as their extension matches one of the extensions configured.

Assisted by GPT-Sol LLM.

--

CPP-9564

Added: 
    clang/test/Analysis/unitybuild-file-extensions.cpp

Modified: 
    clang/docs/ReleaseNotes.md
    clang/docs/analyzer/user-docs/CommandLineUsage.md
    clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
    clang/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
    clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
    clang/lib/StaticAnalyzer/Core/BugReporter.cpp
    clang/test/Analysis/analyzer-config.c

Removed: 
    


################################################################################
diff  --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index f2397bc8dcd594..c3088b7ef65a60 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1588,6 +1588,11 @@ documentation](CIR/index.md) for more information 
regarding ClangIR's status and
 
 #### Improvements
 
+- The user can opt in to analyze functions coming from files participating in
+  unity or jumbo builds as analysis entry points with
+  `-analyzer-config unitybuild-file-extensions=<file-extensions>`.
+  The default behavior is unchanged.
+
 - `unix.StdCLibraryFunctions` now ignores `restrict` qualifiers in C library
   declarations such as `fopen` when targeting MSVC to avoid false negatives in
   C99 and later C standards.

diff  --git a/clang/docs/analyzer/user-docs/CommandLineUsage.md 
b/clang/docs/analyzer/user-docs/CommandLineUsage.md
index 49b556fce336cc..568d21987b621e 100644
--- a/clang/docs/analyzer/user-docs/CommandLineUsage.md
+++ b/clang/docs/analyzer/user-docs/CommandLineUsage.md
@@ -27,6 +27,22 @@ For project-wide analysis, use a tool such as scan-build or 
CodeChecker to drive
 $ scan-build -sarif -o reports make
 ```
 
+## Unity builds
+
+In a unity build (also called a jumbo build or unified-sources build), a source
+file includes other source files. By default, the analyzer never treats
+functions in those included files as analysis entry points. Set
+`unitybuild-file-extensions` to a semicolon-separated list of extensions to
+allow analyzing functions in files with those extensions as entry points, when
+the files are included through other source files or headers. For example:
+
+```console
+$ clang --analyze -Xclang -analyzer-config -Xclang 
'unitybuild-file-extensions=.c;.cc;.cpp;.cxx;.m;.mm' unified.cpp
+```
+
+Include the leading dot in each extension and quote the value so the shell does
+not interpret the semicolons as command separators.
+
 ## Comparison of CodeChecker and scan-build
 
 The static analyzer is by design a GUI tool originally intended to be consumed 
by the XCode IDE.

diff  --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
index 90b80e5201aa82..d253a18ee4fd83 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -227,6 +227,16 @@ ANALYZER_OPTION(
     "the number of nondeterministic diagnostics than "
     "\"crosscheck-with-z3-timeout-threshold\" in practice.", 3)
 
+ANALYZER_OPTION(
+    StringRef, UnityBuildFileExtensions, "unitybuild-file-extensions",
+    "Semicolon-separated file extensions (including leading dots, e.g. "
+    "'.cpp;.impl;.c') of included files whose functions are considered "
+    "analysis entry points, regardless of the including file's name. "
+    "This practice is also known as unity build, jumbo build, unified build, "
+    "blob build, amalgamated build, monolithic build, conglomerate build, "
+    "single compilation unit, single translation unit, or unified sources.",
+    "")
+
 ANALYZER_OPTION(bool, ShouldReportIssuesInMainSourceFile,
                 "report-in-main-source-file",
                 "Whether or not the diagnostic report should be always "

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
index eeb015e26b3ce8..2e3af6902d2f38 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
@@ -20,6 +20,8 @@
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
 
 namespace clang {
 
@@ -43,6 +45,7 @@ class AnalysisManager : public BugReporterData {
   ConstraintManagerCreator CreateConstraintMgr;
 
   CheckerManager *CheckerMgr;
+  SmallVector<StringRef> UnityBuildFileExtensions;
 
 public:
   AnalyzerOptions &options;
@@ -124,10 +127,18 @@ class AnalysisManager : public BugReporterData {
     return AnaCtxMgr.getContext(D);
   }
 
-  static bool isInCodeFile(SourceLocation SL, const SourceManager &SM) {
+  bool isInCodeFile(SourceLocation SL) const {
+    const SourceManager &SM = Ctx.getSourceManager();
     if (SM.isInMainFile(SL))
       return true;
 
+    // Treat configured included source files #include "foo.cpp" same as the
+    // main file.
+    StringRef FileName = SM.getFilename(SL);
+    for (StringRef Extension : UnityBuildFileExtensions)
+      if (FileName.ends_with(Extension))
+        return true;
+
     // Support the "unified sources" compilation method (eg. WebKit) that
     // involves producing non-header files that include other non-header files.
     // We should be included directly from a UnifiedSource* file
@@ -148,11 +159,6 @@ class AnalysisManager : public BugReporterData {
 
     return false;
   }
-
-  bool isInCodeFile(SourceLocation SL) {
-    const SourceManager &SM = getASTContext().getSourceManager();
-    return isInCodeFile(SL, SM);
-  }
 };
 
 } // enAnaCtxMgrspace

diff  --git a/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp 
b/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
index 8a16716f951b85..f952f43e6f031c 100644
--- a/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
@@ -7,6 +7,7 @@
 
//===----------------------------------------------------------------------===//
 
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
+#include "clang/Basic/DiagnosticDriver.h"
 
 using namespace clang;
 using namespace ento;
@@ -38,6 +39,19 @@ AnalysisManager::AnalysisManager(ASTContext &ASTCtx, 
Preprocessor &PP,
       PathConsumers(std::move(PDC)), CreateStoreMgr(storemgr),
       CreateConstraintMgr(constraintmgr), CheckerMgr(checkerMgr),
       options(Options) {
+  SmallVector<StringRef> Extensions;
+  if (!Options.UnityBuildFileExtensions.empty())
+    Options.UnityBuildFileExtensions.split(Extensions, ';');
+  for (StringRef Extension : Extensions) {
+    Extension = Extension.trim();
+    if (Extension.empty()) {
+      ASTCtx.getDiagnostics().Report(diag::err_analyzer_config_invalid_input)
+          << "unitybuild-file-extensions" << "a non-empty file extension";
+      continue;
+    }
+    UnityBuildFileExtensions.push_back(Extension);
+  }
+
   AnaCtxMgr.getCFGBuildOptions().setAllAlwaysAdd();
   AnaCtxMgr.getCFGBuildOptions().OmitImplicitValueInitializers = true;
   AnaCtxMgr.getCFGBuildOptions().AddCXXDefaultInitExprInAggregates =

diff  --git a/clang/lib/StaticAnalyzer/Core/BugReporter.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
index d61187055c9af9..c0ade4e5f85708 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -3297,18 +3297,18 @@ BugReporter::generateDiagnosticForConsumerMap(
 
 static PathDiagnosticCallPiece *
 getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece *CP,
-                                const SourceManager &SMgr) {
+                                const AnalysisManager &AMgr) {
   SourceLocation CallLoc = CP->callEnter.asLocation();
 
   // If the call is within a macro, don't do anything (for now).
   if (CallLoc.isMacroID())
     return nullptr;
 
-  assert(AnalysisManager::isInCodeFile(CallLoc, SMgr) &&
+  assert(AMgr.isInCodeFile(CallLoc) &&
          "The call piece should not be in a header file.");
 
   // Check if CP represents a path through a function outside of the main file.
-  if (!AnalysisManager::isInCodeFile(CP->callEnterWithin.asLocation(), SMgr))
+  if (!AMgr.isInCodeFile(CP->callEnterWithin.asLocation()))
     return CP;
 
   const PathPieces &Path = CP->path;
@@ -3318,24 +3318,24 @@ getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece 
*CP,
   // Check if the last piece in the callee path is a call to a function outside
   // of the main file.
   if (auto *CPInner = dyn_cast<PathDiagnosticCallPiece>(Path.back().get()))
-    return getFirstStackedCallToHeaderFile(CPInner, SMgr);
+    return getFirstStackedCallToHeaderFile(CPInner, AMgr);
 
   // Otherwise, the last piece is in the main file.
   return nullptr;
 }
 
-static void resetDiagnosticLocationToMainFile(PathDiagnostic &PD) {
+static void resetDiagnosticLocationToMainFile(PathDiagnostic &PD,
+                                              const AnalysisManager &AMgr) {
   if (PD.path.empty())
     return;
 
   PathDiagnosticPiece *LastP = PD.path.back().get();
   assert(LastP);
-  const SourceManager &SMgr = LastP->getLocation().getManager();
 
   // We only need to check if the report ends inside headers, if the last piece
   // is a call piece.
   if (auto *CP = dyn_cast<PathDiagnosticCallPiece>(LastP)) {
-    CP = getFirstStackedCallToHeaderFile(CP, SMgr);
+    CP = getFirstStackedCallToHeaderFile(CP, AMgr);
     if (CP) {
       // Mark the piece.
        CP->setAsLastInMainSourceFile();
@@ -3391,7 +3391,7 @@ 
PathSensitiveBugReporter::generateDiagnosticForConsumerMap(
   const AnalyzerOptions &Opts = getAnalyzerOptions();
   for (auto const &P : *Out)
     if (Opts.ShouldReportIssuesInMainSourceFile && !Opts.AnalyzeAll)
-      resetDiagnosticLocationToMainFile(*P.second);
+      resetDiagnosticLocationToMainFile(*P.second, Eng.getAnalysisManager());
 
   return Out;
 }

diff  --git a/clang/test/Analysis/analyzer-config.c 
b/clang/test/Analysis/analyzer-config.c
index 6715688ac56ecf..9587117dd3d034 100644
--- a/clang/test/Analysis/analyzer-config.c
+++ b/clang/test/Analysis/analyzer-config.c
@@ -135,6 +135,7 @@
 // CHECK-NEXT: suppress-null-return-paths = true
 // CHECK-NEXT: track-conditions = true
 // CHECK-NEXT: track-conditions-debug = false
+// CHECK-NEXT: unitybuild-file-extensions = ""
 // CHECK-NEXT: unix.DynamicMemoryModeling:AddNoOwnershipChangeNotes = true
 // CHECK-NEXT: unix.DynamicMemoryModeling:ModelAllocationFailure = false
 // CHECK-NEXT: unix.DynamicMemoryModeling:Optimistic = false

diff  --git a/clang/test/Analysis/unitybuild-file-extensions.cpp 
b/clang/test/Analysis/unitybuild-file-extensions.cpp
new file mode 100644
index 00000000000000..91db1eb459bab6
--- /dev/null
+++ b/clang/test/Analysis/unitybuild-file-extensions.cpp
@@ -0,0 +1,96 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %t/main.cpp
+// RUN: not %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:                        -analyzer-config 'unitybuild-file-extensions=; 
;' \
+// RUN:                        %t/main.cpp 2>&1 | FileCheck %s 
--check-prefix=EMPTY
+// EMPTY: invalid input for analyzer-config option 
'unitybuild-file-extensions', that expects a non-empty file extension
+// A comma is parsed as a separator between analyzer options, not extensions.
+// RUN: not %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:                        -analyzer-config 
'unitybuild-file-extensions=.c,.cc,.cpp,.cxx' \
+// RUN:                        %t/main.cpp 2>&1 | FileCheck %s 
--check-prefix=COMMA
+// COMMA: error: analyzer-config option '.cc' has a key but no value
+// The same error occurs if another analyzer option follows the extension list.
+// RUN: not %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:                        -analyzer-config 
'unitybuild-file-extensions=.c,.cc,eagerly-assume=true' \
+// RUN:                        %t/main.cpp 2>&1 | FileCheck %s 
--check-prefix=COMMA
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:                    -analyzer-config 
'unitybuild-file-extensions=.cpp;.impl;.c' \
+// RUN:                    -verify=expected,all-extensions %t/main.cpp
+// RUN: %clang_analyze_cc1 -analyzer-checker=core \
+// RUN:                    -analyzer-config unitybuild-file-extensions=.impl \
+// RUN:                    -verify=expected,impl-only %t/main.cpp
+
+//--- foo.cpp
+#include "nested.h"
+
+int includedCppFunction(int x) {
+  if (x == 0)
+    return 1 / x; // all-extensions-warning{{Division by zero}}
+  return 0;
+}
+
+// This bug is found through the call from main.cpp, even by the default run.
+int calledIncludedCppFunction(int x) {
+  return 1 / x; // expected-warning{{Division by zero}}
+}
+
+//--- nested.h
+#include "nested.cpp"
+
+//--- nested.cpp
+// main.cpp includes this file through foo.cpp and nested.h.
+int nestedCppFunction(int x) {
+  if (x == 0)
+    return 1 / x; // all-extensions-warning{{Division by zero}}
+  return 0;
+}
+
+//--- header.h
+int headerFunction(int x) {
+  // .h extension is not included in any of the runs.
+  if (x == 0)
+    return 1 / x; // no-warning
+  return 0;
+}
+
+// This bug is also found through a call from main.cpp, not as an entry point.
+int calledHeaderFunction(int x) {
+  return 1 / x; // expected-warning{{Division by zero}}
+}
+
+//--- file-extensions.impl
+int includedImplFunction(int x) {
+  if (x == 0)
+    return 1 / x; // all-extensions-warning{{Division by zero}} 
impl-only-warning{{Division by zero}}
+  return 0;
+}
+
+//--- file-extensions.c
+int includedCFunction(int x) {
+  if (x == 0)
+    return 1 / x; // all-extensions-warning{{Division by zero}}
+  return 0;
+}
+
+//--- main.cpp
+// With the empty default, only the main file contributes entry points.
+// The configured list also adds included files with matching extensions.
+#include "foo.cpp"
+#include "header.h"
+#include "file-extensions.impl"
+#include "file-extensions.c"
+
+int mainFileFunction(int x) {
+  if (x == 0)
+    return 1 / x; // expected-warning{{Division by zero}}
+  return 0;
+}
+
+int mainFileCaller(bool callHeader) {
+  if (callHeader)
+    return calledHeaderFunction(0);
+  return calledIncludedCppFunction(0);
+}


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

Reply via email to