[flang-commits] [flang] Add Flang-Tidy: A Fortran Static Analysis Tool (PR #143883)

via flang-commits flang-commits at lists.llvm.org
Wed Jul 16 01:35:45 PDT 2025


https://github.com/Originns updated https://github.com/llvm/llvm-project/pull/143883

>From 29e41425289ffd99f5b554fdd62b8531b7737ecc Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 24 Jun 2025 11:43:59 +0200
Subject: [PATCH 01/31] [flang-tidy] basic executable infrastructure

---
 flang/tools/CMakeLists.txt                    |  1 +
 flang/tools/flang-tidy/.clang-format          |  2 ++
 flang/tools/flang-tidy/CMakeLists.txt         |  1 +
 flang/tools/flang-tidy/tool/CMakeLists.txt    | 27 +++++++++++++++++++
 .../flang-tidy/tool/FlangTidyToolMain.cpp     |  9 +++++++
 5 files changed, 40 insertions(+)
 create mode 100644 flang/tools/flang-tidy/.clang-format
 create mode 100644 flang/tools/flang-tidy/CMakeLists.txt
 create mode 100644 flang/tools/flang-tidy/tool/CMakeLists.txt
 create mode 100644 flang/tools/flang-tidy/tool/FlangTidyToolMain.cpp

diff --git a/flang/tools/CMakeLists.txt b/flang/tools/CMakeLists.txt
index 1d2d2c608faf9..644fa7fe9c715 100644
--- a/flang/tools/CMakeLists.txt
+++ b/flang/tools/CMakeLists.txt
@@ -13,3 +13,4 @@ add_subdirectory(tco)
 add_subdirectory(f18-parse-demo)
 add_subdirectory(fir-opt)
 add_subdirectory(fir-lsp-server)
+add_subdirectory(flang-tidy)
diff --git a/flang/tools/flang-tidy/.clang-format b/flang/tools/flang-tidy/.clang-format
new file mode 100644
index 0000000000000..a74fda4b67345
--- /dev/null
+++ b/flang/tools/flang-tidy/.clang-format
@@ -0,0 +1,2 @@
+BasedOnStyle: LLVM
+AlwaysBreakTemplateDeclarations: Yes
diff --git a/flang/tools/flang-tidy/CMakeLists.txt b/flang/tools/flang-tidy/CMakeLists.txt
new file mode 100644
index 0000000000000..0362281046be1
--- /dev/null
+++ b/flang/tools/flang-tidy/CMakeLists.txt
@@ -0,0 +1 @@
+add_subdirectory(tool)
diff --git a/flang/tools/flang-tidy/tool/CMakeLists.txt b/flang/tools/flang-tidy/tool/CMakeLists.txt
new file mode 100644
index 0000000000000..6233d354973eb
--- /dev/null
+++ b/flang/tools/flang-tidy/tool/CMakeLists.txt
@@ -0,0 +1,27 @@
+set(LLVM_LINK_COMPONENTS
+  ${LLVM_TARGETS_TO_BUILD}
+  FrontendOpenACC
+  FrontendOpenMP
+  Support
+  Option
+  TargetParser
+  )
+
+if(FLANG_PLUGIN_SUPPORT)
+  set(support_plugins SUPPORT_PLUGINS)
+endif()
+
+add_flang_tool(flang-tidy
+  FlangTidyToolMain.cpp
+
+  ${support_plugins}
+  )
+
+target_link_libraries(flang-tidy
+  PRIVATE
+  ${ALL_FLANG_TIDY_CHECKS}
+  )
+
+if(FLANG_PLUGIN_SUPPORT)
+  export_executable_symbols_for_plugins(flang-tidy)
+endif()
diff --git a/flang/tools/flang-tidy/tool/FlangTidyToolMain.cpp b/flang/tools/flang-tidy/tool/FlangTidyToolMain.cpp
new file mode 100644
index 0000000000000..8f3481de6df69
--- /dev/null
+++ b/flang/tools/flang-tidy/tool/FlangTidyToolMain.cpp
@@ -0,0 +1,9 @@
+//===--- FlangTidyToolMain.cpp - flang-tidy -------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+int main(int argc, const char **argv) {}

>From 4b956962b6e3d76cf3cbcb0f2d8abe680b960837 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 24 Jun 2025 13:52:19 +0200
Subject: [PATCH 02/31] [flang-tidy] add main tool

---
 flang/tools/flang-tidy/tool/CMakeLists.txt      | 17 +++++++++++++++++
 flang/tools/flang-tidy/tool/FlangTidyMain.cpp   | 13 +++++++++++++
 flang/tools/flang-tidy/tool/FlangTidyMain.h     | 11 +++++++++++
 .../tools/flang-tidy/tool/FlangTidyToolMain.cpp |  6 +++++-
 4 files changed, 46 insertions(+), 1 deletion(-)
 create mode 100644 flang/tools/flang-tidy/tool/FlangTidyMain.cpp
 create mode 100644 flang/tools/flang-tidy/tool/FlangTidyMain.h

diff --git a/flang/tools/flang-tidy/tool/CMakeLists.txt b/flang/tools/flang-tidy/tool/CMakeLists.txt
index 6233d354973eb..69db1da4723de 100644
--- a/flang/tools/flang-tidy/tool/CMakeLists.txt
+++ b/flang/tools/flang-tidy/tool/CMakeLists.txt
@@ -7,6 +7,21 @@ set(LLVM_LINK_COMPONENTS
   TargetParser
   )
 
+set(LLVM_OPTIONAL_SOURCES FlangTidyMain.cpp FlangTidyToolMain.cpp)
+
+add_flang_library(flangTidyMain STATIC
+  FlangTidyMain.cpp
+
+  LINK_LIBS
+  FortranSupport
+  FortranEvaluate
+  FortranParser
+  FortranSemantics
+  LLVMSupport
+  flangTidy
+  ${ALL_FLANG_TIDY_CHECKS}
+  )
+
 if(FLANG_PLUGIN_SUPPORT)
   set(support_plugins SUPPORT_PLUGINS)
 endif()
@@ -19,6 +34,8 @@ add_flang_tool(flang-tidy
 
 target_link_libraries(flang-tidy
   PRIVATE
+  flangTidy
+  flangTidyMain
   ${ALL_FLANG_TIDY_CHECKS}
   )
 
diff --git a/flang/tools/flang-tidy/tool/FlangTidyMain.cpp b/flang/tools/flang-tidy/tool/FlangTidyMain.cpp
new file mode 100644
index 0000000000000..7492dfda36d8f
--- /dev/null
+++ b/flang/tools/flang-tidy/tool/FlangTidyMain.cpp
@@ -0,0 +1,13 @@
+//===--- FlangTidyMain.cpp - flang-tidy -----------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+namespace Fortran::tidy {
+
+extern int flangTidyMain(int &argc, const char **argv) { return 0; }
+
+} // namespace Fortran::tidy
diff --git a/flang/tools/flang-tidy/tool/FlangTidyMain.h b/flang/tools/flang-tidy/tool/FlangTidyMain.h
new file mode 100644
index 0000000000000..8dcff94135cc0
--- /dev/null
+++ b/flang/tools/flang-tidy/tool/FlangTidyMain.h
@@ -0,0 +1,11 @@
+//===--- FlangTidyMain.h - flang-tidy ---------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+namespace Fortran::tidy {
+int flangTidyMain(int &argc, const char **argv);
+} // namespace Fortran::tidy
diff --git a/flang/tools/flang-tidy/tool/FlangTidyToolMain.cpp b/flang/tools/flang-tidy/tool/FlangTidyToolMain.cpp
index 8f3481de6df69..503f037241e1c 100644
--- a/flang/tools/flang-tidy/tool/FlangTidyToolMain.cpp
+++ b/flang/tools/flang-tidy/tool/FlangTidyToolMain.cpp
@@ -6,4 +6,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-int main(int argc, const char **argv) {}
+#include "FlangTidyMain.h"
+
+int main(int argc, const char **argv) {
+  return Fortran::tidy::flangTidyMain(argc, argv);
+}

>From f6cea61d979042a6e6c029a84d2984d9aef16287 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Wed, 25 Jun 2025 11:38:51 +0200
Subject: [PATCH 03/31] [flang-tidy] add visitor, options and module & check
 architecture

---
 flang/tools/flang-tidy/CMakeLists.txt         |  27 +
 flang/tools/flang-tidy/FlangTidy.cpp          | 297 ++++++++++
 flang/tools/flang-tidy/FlangTidy.h            |  20 +
 flang/tools/flang-tidy/FlangTidyCheck.cpp     | 215 +++++++
 flang/tools/flang-tidy/FlangTidyCheck.h       | 542 ++++++++++++++++++
 flang/tools/flang-tidy/FlangTidyContext.h     |  78 +++
 flang/tools/flang-tidy/FlangTidyForceLinker.h |  18 +
 flang/tools/flang-tidy/FlangTidyModule.cpp    |  49 ++
 flang/tools/flang-tidy/FlangTidyModule.h      |  99 ++++
 .../flang-tidy/FlangTidyModuleRegistry.h      |  25 +
 flang/tools/flang-tidy/FlangTidyOptions.cpp   | 420 ++++++++++++++
 flang/tools/flang-tidy/FlangTidyOptions.h     | 223 +++++++
 flang/tools/flang-tidy/MultiplexVisitor.h     | 103 ++++
 flang/tools/flang-tidy/tool/FlangTidyMain.cpp | 297 +++++++++-
 .../flang-tidy/utils/CollectActualArguments.h |  45 ++
 flang/tools/flang-tidy/utils/SymbolUtils.h    |  25 +
 16 files changed, 2482 insertions(+), 1 deletion(-)
 create mode 100644 flang/tools/flang-tidy/FlangTidy.cpp
 create mode 100644 flang/tools/flang-tidy/FlangTidy.h
 create mode 100644 flang/tools/flang-tidy/FlangTidyCheck.cpp
 create mode 100644 flang/tools/flang-tidy/FlangTidyCheck.h
 create mode 100644 flang/tools/flang-tidy/FlangTidyContext.h
 create mode 100644 flang/tools/flang-tidy/FlangTidyForceLinker.h
 create mode 100644 flang/tools/flang-tidy/FlangTidyModule.cpp
 create mode 100644 flang/tools/flang-tidy/FlangTidyModule.h
 create mode 100644 flang/tools/flang-tidy/FlangTidyModuleRegistry.h
 create mode 100644 flang/tools/flang-tidy/FlangTidyOptions.cpp
 create mode 100644 flang/tools/flang-tidy/FlangTidyOptions.h
 create mode 100644 flang/tools/flang-tidy/MultiplexVisitor.h
 create mode 100644 flang/tools/flang-tidy/utils/CollectActualArguments.h
 create mode 100644 flang/tools/flang-tidy/utils/SymbolUtils.h

diff --git a/flang/tools/flang-tidy/CMakeLists.txt b/flang/tools/flang-tidy/CMakeLists.txt
index 0362281046be1..4e485cd25c46e 100644
--- a/flang/tools/flang-tidy/CMakeLists.txt
+++ b/flang/tools/flang-tidy/CMakeLists.txt
@@ -1 +1,28 @@
+set(LLVM_LINK_COMPONENTS
+  ${LLVM_TARGETS_TO_BUILD}
+  Support
+)
+
+add_flang_library(flangTidy STATIC
+  FlangTidy.cpp
+  FlangTidyCheck.cpp
+  FlangTidyModule.cpp
+  FlangTidyOptions.cpp
+)
+
+target_link_libraries(flangTidy
+  PRIVATE
+  FortranSupport
+  FortranEvaluate
+  FortranParser
+  FortranSemantics
+  flangFrontend
+  flangFrontendTool
+  )
+
+set(ALL_FLANG_TIDY_CHECKS
+  )
+
+set(ALL_FLANG_TIDY_CHECKS ${ALL_FLANG_TIDY_CHECKS} PARENT_SCOPE)
+
 add_subdirectory(tool)
diff --git a/flang/tools/flang-tidy/FlangTidy.cpp b/flang/tools/flang-tidy/FlangTidy.cpp
new file mode 100644
index 0000000000000..d81314538c6e4
--- /dev/null
+++ b/flang/tools/flang-tidy/FlangTidy.cpp
@@ -0,0 +1,297 @@
+//===--- FlangTidy.cpp - flang-tidy ---------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "FlangTidy.h"
+#include "FlangTidyContext.h"
+#include "FlangTidyModule.h"
+#include "FlangTidyModuleRegistry.h"
+#include "MultiplexVisitor.h"
+#include "flang/Frontend/CompilerInstance.h"
+#include "flang/Frontend/CompilerInvocation.h"
+#include "flang/Frontend/TextDiagnosticPrinter.h"
+#include "flang/FrontendTool/Utils.h"
+#include "flang/Parser/parsing.h"
+#include "flang/Parser/provenance.h"
+#include "flang/Semantics/semantics.h"
+#include "flang/Semantics/symbol.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/Option/Arg.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Option/OptTable.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/raw_ostream.h"
+#include <clang/Basic/DiagnosticOptions.h>
+#include <memory>
+
+LLVM_INSTANTIATE_REGISTRY(Fortran::tidy::FlangTidyModuleRegistry)
+
+namespace Fortran::tidy {
+
+// Factory to populate MultiplexVisitor with all registered checks
+class MultiplexVisitorFactory {
+public:
+  MultiplexVisitorFactory();
+
+public:
+  std::unique_ptr<FlangTidyCheckFactories> CheckFactories;
+};
+
+MultiplexVisitorFactory::MultiplexVisitorFactory()
+    : CheckFactories(new FlangTidyCheckFactories) {
+  // Traverse the FlangTidyModuleRegistry to register all checks
+  for (auto &entry : FlangTidyModuleRegistry::entries()) {
+    // Instantiate the module
+    std::unique_ptr<FlangTidyModule> module = entry.instantiate();
+    module->addCheckFactories(*CheckFactories);
+  }
+}
+
+static std::string extractCheckName(const std::string &message) {
+  size_t openBracket = message.rfind('[');
+  size_t closeBracket = message.rfind(']');
+
+  if (openBracket != std::string::npos && closeBracket != std::string::npos &&
+      openBracket < closeBracket && closeBracket == message.length() - 1) {
+    return message.substr(openBracket + 1, closeBracket - openBracket - 1);
+  }
+
+  return "";
+}
+
+static bool shouldSuppressWarning(const parser::ProvenanceRange &source,
+                                  const std::string &checkName,
+                                  FlangTidyContext *context) {
+  if (source.empty()) {
+    return false;
+  }
+
+  const auto &cookedSources = context->getSemanticsContext().allCookedSources();
+  const auto &allSources = cookedSources.allSources();
+
+  auto srcPosition = allSources.GetSourcePosition(source.start());
+  if (!srcPosition) {
+    return false;
+  }
+
+  int lineNum = srcPosition->line;
+
+  // Get the source file and line
+  std::size_t offset;
+  const auto *sourceFile = allSources.GetSourceFile(source.start(), &offset);
+  if (!sourceFile) {
+    return false;
+  }
+
+  // Extract the line content from the source file
+  auto checkForNoLint = [&](llvm::StringRef line) -> bool {
+    // Look for ! NOLINT or !NOLINT
+    auto commentPos = line.find('!');
+    if (commentPos == llvm::StringRef::npos) {
+      return false;
+    }
+
+    auto comment = line.substr(commentPos);
+
+    // Check for NOLINT
+    if (comment.contains("NOLINT") || comment.contains("nolint")) {
+      // If there's no specific check mentioned, it applies to all checks
+      if (!comment.contains("(")) {
+        return true;
+      }
+
+      // Check for specific check name in parentheses
+      if (comment.contains("(" + checkName + ")")) {
+        return true;
+      }
+    }
+    return false;
+  };
+
+  // Try to get the current line
+  const auto &content = sourceFile->content();
+  std::size_t lineStart = 0;
+  std::size_t lineEnd = 0;
+  int currentLine = 1;
+
+  // Find the start of the current line
+  for (std::size_t i = 0; i < content.size(); i++) {
+    if (currentLine == lineNum) {
+      lineStart = i;
+
+      // Find the end of the line
+      while (i < content.size() && content[i] != '\n') {
+        i++;
+      }
+      lineEnd = i;
+
+      // Check if this line has a NOLINT comment
+      llvm::StringRef line(content.data() + lineStart, lineEnd - lineStart);
+      if (checkForNoLint(line)) {
+        return true;
+      }
+
+      // Check previous line if we can
+      if (lineNum > 1 && lineStart > 0) {
+        // Find the start of the previous line
+        std::size_t prevLineEnd = lineStart - 1;
+        std::size_t prevLineStart = prevLineEnd;
+
+        // Go back to find the start of the previous line
+        while (prevLineStart > 0 && content[prevLineStart - 1] != '\n') {
+          prevLineStart--;
+        }
+
+        llvm::StringRef prevLine(content.data() + prevLineStart,
+                                 prevLineEnd - prevLineStart);
+        if (checkForNoLint(prevLine)) {
+          return true;
+        }
+      }
+
+      // We've checked the current and previous lines, so we're done
+      break;
+    }
+
+    if (content[i] == '\n') {
+      currentLine++;
+    }
+  }
+
+  return false;
+}
+
+static void filterMessagesWithNoLint(parser::Messages &messages,
+                                     FlangTidyContext *context) {
+  std::vector<parser::Message> filteredMessages;
+
+  const auto &cookedSources = context->getSemanticsContext().allCookedSources();
+
+  for (const auto &message : messages.messages()) {
+    // Extract the check name from the message text
+    std::string checkName = extractCheckName(message.ToString());
+
+    // Skip messages that should be suppressed
+    const auto &provenanceRange = message.GetProvenanceRange(cookedSources);
+
+    // get the charBlock
+    if (!checkName.empty() && provenanceRange &&
+        shouldSuppressWarning(provenanceRange.value(), checkName, context)) {
+      continue;
+    }
+
+    // Keep messages that aren't suppressed
+    filteredMessages.push_back(message);
+  }
+
+  // Replace the original messages with the filtered ones
+  messages.clear();
+  for (const auto &msg : filteredMessages) {
+    messages.Say(msg);
+  }
+}
+
+int runFlangTidy(const FlangTidyOptions &options) {
+  auto flang = std::make_unique<Fortran::frontend::CompilerInstance>();
+
+  // create diagnostics engine
+  flang->createDiagnostics();
+  if (!flang->hasDiagnostics()) {
+    llvm::errs() << "Failed to create diagnostics engine\n";
+    return 1;
+  }
+
+  // create diagnostics buffer
+  auto diagsPrinter =
+      std::make_unique<Fortran::frontend::TextDiagnosticPrinter>(
+          llvm::outs(), flang->getDiagnostics().getDiagnosticOptions());
+
+  flang->getDiagnostics().setClient(diagsPrinter.get(), false);
+
+  // convert the options to a format that can be passed to the compiler
+  // invocation
+  std::vector<const char *> cstrArgs;
+
+  // add input files
+  for (const auto &sourcePath : options.sourcePaths) {
+    cstrArgs.push_back(sourcePath.c_str());
+  }
+
+  // add extra args before (if present)
+  if (options.ExtraArgsBefore) {
+    for (const auto &arg : *options.ExtraArgsBefore) {
+      cstrArgs.push_back(arg.c_str());
+    }
+  }
+
+  // add extra args (if present)
+  if (options.ExtraArgs) {
+    for (const auto &arg : *options.ExtraArgs) {
+      cstrArgs.push_back(arg.c_str());
+    }
+  }
+
+  llvm::ArrayRef<const char *> argv(cstrArgs);
+  flang->getFrontendOpts().programAction = frontend::ParseSyntaxOnly;
+
+  // parse arguments
+  bool success = Fortran::frontend::CompilerInvocation::createFromArgs(
+      flang->getInvocation(), argv, flang->getDiagnostics(), options.argv0);
+
+  // initialize targets
+  llvm::InitializeAllTargets();
+  llvm::InitializeAllTargetMCs();
+  llvm::InitializeAllAsmPrinters();
+
+  // emit diagnostics
+  if (!success) {
+    llvm::errs() << "Failed to parse arguments\n";
+    return 1;
+  }
+
+  // run the compiler instance
+  if (!Fortran::frontend::executeCompilerInvocation(flang.get())) {
+    return 1;
+  }
+
+  // handle help and version flags
+  if (flang->getFrontendOpts().showHelp ||
+      flang->getFrontendOpts().showVersion) {
+    return 0;
+  }
+
+  // get the parse tree
+  auto &parsing = flang->getParsing();
+  auto &parseTree = parsing.parseTree();
+  if (!parseTree) {
+    return 1;
+  }
+
+  auto &semantics = flang->getSemantics();
+  auto &semanticsContext = semantics.context();
+
+  FlangTidyContext context{options, &semanticsContext};
+
+  MultiplexVisitorFactory visitorFactory{};
+  MultiplexVisitor visitor{semanticsContext};
+  auto checks = visitorFactory.CheckFactories->createChecks(&context);
+
+  for (auto &&check : checks) {
+    visitor.AddChecker(std::move(check));
+  }
+
+  visitor.Walk(*parseTree);
+
+  auto &messages = context.Context->messages();
+  filterMessagesWithNoLint(messages, &context);
+
+  semantics.EmitMessages(llvm::outs());
+
+  return 0;
+}
+
+} // namespace Fortran::tidy
diff --git a/flang/tools/flang-tidy/FlangTidy.h b/flang/tools/flang-tidy/FlangTidy.h
new file mode 100644
index 0000000000000..db65d430f45b6
--- /dev/null
+++ b/flang/tools/flang-tidy/FlangTidy.h
@@ -0,0 +1,20 @@
+//===--- FlangTidy.h - flang-tidy -------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDY_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDY_H
+
+#include "FlangTidyOptions.h"
+
+namespace Fortran::tidy {
+
+int runFlangTidy(const FlangTidyOptions &options);
+
+} // namespace Fortran::tidy
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDY_H
diff --git a/flang/tools/flang-tidy/FlangTidyCheck.cpp b/flang/tools/flang-tidy/FlangTidyCheck.cpp
new file mode 100644
index 0000000000000..a3354b4cc1fcd
--- /dev/null
+++ b/flang/tools/flang-tidy/FlangTidyCheck.cpp
@@ -0,0 +1,215 @@
+//===--- FlangTidyCheck.cpp - flang-tidy ----------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "FlangTidyCheck.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/StringSet.h"
+#include "llvm/Support/YAMLParser.h"
+#include <optional>
+
+namespace Fortran::tidy {
+
+FlangTidyCheck::FlangTidyCheck(llvm::StringRef CheckName,
+                               FlangTidyContext *Context)
+    : Options(CheckName, Context->getOptions().CheckOptions, Context),
+      name_(CheckName), context_(Context) {}
+
+FlangTidyCheck::OptionsView::OptionsView(
+    llvm::StringRef CheckName, const FlangTidyOptions::OptionMap &CheckOptions,
+    FlangTidyContext *Context)
+    : NamePrefix((CheckName + ".").str()), CheckOptions(CheckOptions),
+      Context(Context) {}
+
+std::optional<llvm::StringRef>
+FlangTidyCheck::OptionsView::get(llvm::StringRef LocalName) const {
+  const auto &Iter = CheckOptions.find((NamePrefix + LocalName).str());
+  if (Iter != CheckOptions.end())
+    return llvm::StringRef(Iter->getValue().Value);
+  return std::nullopt;
+}
+
+static const llvm::StringSet<> DeprecatedGlobalOptions{
+    "StrictMode",
+    "IgnoreMacros",
+};
+
+static FlangTidyOptions::OptionMap::const_iterator
+findPriorityOption(const FlangTidyOptions::OptionMap &Options,
+                   llvm::StringRef NamePrefix, llvm::StringRef LocalName,
+                   FlangTidyContext *Context) {
+  auto IterLocal = Options.find((NamePrefix + LocalName).str());
+  auto IterGlobal = Options.find(LocalName);
+
+  // FIXME: temporary solution for deprecation warnings, should be removed
+  // after migration. Warn configuration deps on deprecation global options.
+  if (IterLocal == Options.end() && IterGlobal != Options.end() &&
+      DeprecatedGlobalOptions.contains(LocalName)) {
+    // Could add deprecation warning here if needed
+  }
+
+  if (IterLocal == Options.end())
+    return IterGlobal;
+  if (IterGlobal == Options.end())
+    return IterLocal;
+  if (IterLocal->getValue().Priority >= IterGlobal->getValue().Priority)
+    return IterLocal;
+  return IterGlobal;
+}
+
+std::optional<llvm::StringRef>
+FlangTidyCheck::OptionsView::getLocalOrGlobal(llvm::StringRef LocalName) const {
+  auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName, Context);
+  if (Iter != CheckOptions.end())
+    return llvm::StringRef(Iter->getValue().Value);
+  return std::nullopt;
+}
+
+static std::optional<bool> getAsBool(llvm::StringRef Value,
+                                     const llvm::Twine &LookupName) {
+  if (std::optional<bool> Parsed = llvm::yaml::parseBool(Value))
+    return Parsed;
+  // To maintain backwards compatability, we support parsing numbers as
+  // booleans, even though its not supported in YAML.
+  long long Number = 0;
+  if (!Value.getAsInteger(10, Number))
+    return Number != 0;
+  return std::nullopt;
+}
+
+template <>
+std::optional<bool>
+FlangTidyCheck::OptionsView::get<bool>(llvm::StringRef LocalName) const {
+  if (std::optional<llvm::StringRef> ValueOr = get(LocalName)) {
+    if (auto Result = getAsBool(*ValueOr, NamePrefix + LocalName))
+      return Result;
+    diagnoseBadBooleanOption(NamePrefix + LocalName, *ValueOr);
+  }
+  return std::nullopt;
+}
+
+template <>
+std::optional<bool> FlangTidyCheck::OptionsView::getLocalOrGlobal<bool>(
+    llvm::StringRef LocalName) const {
+  auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName, Context);
+  if (Iter != CheckOptions.end()) {
+    if (auto Result = getAsBool(Iter->getValue().Value, Iter->getKey()))
+      return Result;
+    diagnoseBadBooleanOption(Iter->getKey(), Iter->getValue().Value);
+  }
+  return std::nullopt;
+}
+
+void FlangTidyCheck::OptionsView::store(FlangTidyOptions::OptionMap &Options,
+                                        llvm::StringRef LocalName,
+                                        llvm::StringRef Value) const {
+  Options[(NamePrefix + LocalName).str()] =
+      FlangTidyOptions::FlangTidyValue(Value);
+}
+
+void FlangTidyCheck::OptionsView::storeInt(FlangTidyOptions::OptionMap &Options,
+                                           llvm::StringRef LocalName,
+                                           int64_t Value) const {
+  store(Options, LocalName, llvm::itostr(Value));
+}
+
+void FlangTidyCheck::OptionsView::storeUnsigned(
+    FlangTidyOptions::OptionMap &Options, llvm::StringRef LocalName,
+    uint64_t Value) const {
+  store(Options, LocalName, llvm::utostr(Value));
+}
+
+template <>
+void FlangTidyCheck::OptionsView::store<bool>(
+    FlangTidyOptions::OptionMap &Options, llvm::StringRef LocalName,
+    bool Value) const {
+  store(Options, LocalName,
+        Value ? llvm::StringRef("true") : llvm::StringRef("false"));
+}
+
+std::optional<int64_t>
+FlangTidyCheck::OptionsView::getEnumInt(llvm::StringRef LocalName,
+                                        llvm::ArrayRef<NameAndValue> Mapping,
+                                        bool CheckGlobal) const {
+  auto Iter = CheckGlobal ? findPriorityOption(CheckOptions, NamePrefix,
+                                               LocalName, Context)
+                          : CheckOptions.find((NamePrefix + LocalName).str());
+  if (Iter == CheckOptions.end())
+    return std::nullopt;
+
+  llvm::StringRef Value = Iter->getValue().Value;
+  llvm::StringRef Closest;
+  unsigned EditDistance = 3;
+  for (const auto &NameAndEnum : Mapping) {
+    if (Value == NameAndEnum.second) {
+      return NameAndEnum.first;
+    }
+    if (Value.equals_insensitive(NameAndEnum.second)) {
+      Closest = NameAndEnum.second;
+      EditDistance = 0;
+      continue;
+    }
+    unsigned Distance =
+        Value.edit_distance(NameAndEnum.second, true, EditDistance);
+    if (Distance < EditDistance) {
+      EditDistance = Distance;
+      Closest = NameAndEnum.second;
+    }
+  }
+  if (EditDistance < 3)
+    diagnoseBadEnumOption(Iter->getKey(), Iter->getValue().Value, Closest);
+  else
+    diagnoseBadEnumOption(Iter->getKey(), Iter->getValue().Value);
+  return std::nullopt;
+}
+
+/*
+static constexpr llvm::StringLiteral ConfigWarning(
+    "invalid configuration value '%0' for option '%1'%select{|; expected a "
+    "bool|; expected an integer|; did you mean '%3'?}2");
+ */
+void FlangTidyCheck::OptionsView::diagnoseBadBooleanOption(
+    const llvm::Twine &Lookup, llvm::StringRef Unparsed) const {
+  llvm::SmallString<64> Buffer;
+  // For now, just use a simple error message since we don't have the diagnostic
+  // infrastructure
+  llvm::errs() << "Error: invalid boolean value '" << Unparsed
+               << "' for option '" << Lookup.toStringRef(Buffer) << "'\n";
+}
+
+void FlangTidyCheck::OptionsView::diagnoseBadIntegerOption(
+    const llvm::Twine &Lookup, llvm::StringRef Unparsed) const {
+  llvm::SmallString<64> Buffer;
+  llvm::errs() << "Error: invalid integer value '" << Unparsed
+               << "' for option '" << Lookup.toStringRef(Buffer) << "'\n";
+}
+
+void FlangTidyCheck::OptionsView::diagnoseBadEnumOption(
+    const llvm::Twine &Lookup, llvm::StringRef Unparsed,
+    llvm::StringRef Suggestion) const {
+  llvm::SmallString<64> Buffer;
+  llvm::errs() << "Error: invalid enum value '" << Unparsed << "' for option '"
+               << Lookup.toStringRef(Buffer) << "'";
+  if (!Suggestion.empty())
+    llvm::errs() << "; did you mean '" << Suggestion << "'?";
+  llvm::errs() << "\n";
+}
+
+llvm::StringRef
+FlangTidyCheck::OptionsView::get(llvm::StringRef LocalName,
+                                 llvm::StringRef Default) const {
+  return get(LocalName).value_or(Default);
+}
+
+llvm::StringRef
+FlangTidyCheck::OptionsView::getLocalOrGlobal(llvm::StringRef LocalName,
+                                              llvm::StringRef Default) const {
+  return getLocalOrGlobal(LocalName).value_or(Default);
+}
+
+} // namespace Fortran::tidy
diff --git a/flang/tools/flang-tidy/FlangTidyCheck.h b/flang/tools/flang-tidy/FlangTidyCheck.h
new file mode 100644
index 0000000000000..6d5e248b6c07f
--- /dev/null
+++ b/flang/tools/flang-tidy/FlangTidyCheck.h
@@ -0,0 +1,542 @@
+//===--- FlangTidyCheck.h - flang-tidy --------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYCHECK_H
+
+#include "FlangTidyContext.h"
+#include "FlangTidyOptions.h"
+#include "flang/Parser/message.h"
+#include "flang/Parser/parse-tree.h"
+#include "flang/Semantics/semantics.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/Twine.h"
+#include <optional>
+#include <type_traits>
+#include <utility>
+#include <vector>
+
+namespace Fortran::tidy {
+
+/// This class should be specialized by any enum type that needs to be converted
+/// to and from an \ref llvm::StringRef.
+template <class T>
+struct OptionEnumMapping {
+  // Specializations of this struct must implement this function.
+  static llvm::ArrayRef<std::pair<T, llvm::StringRef>>
+  getEnumMapping() = delete;
+};
+
+/// This is the base class for all Flang Tidy checks. It provides a
+/// common interface for all checks and allows them to interact with
+/// the Flang Tidy context. Each check should inherit from this
+/// class and implement the necessary methods to perform its
+/// specific analysis.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/flang-tidy-checks.html
+class FlangTidyCheck : public semantics::BaseChecker {
+public:
+  FlangTidyCheck(llvm::StringRef name, FlangTidyContext *context);
+  virtual ~FlangTidyCheck() = default;
+  llvm::StringRef name() const { return name_; }
+  FlangTidyContext *context() { return context_; }
+  bool fixAvailable() const { return fixAvailable_; }
+
+  using semantics::BaseChecker::Enter;
+  using semantics::BaseChecker::Leave;
+
+  /// Should store all options supported by this check with their
+  /// current values or default values for options that haven't been overridden.
+  ///
+  /// The check should use ``Options.store()`` to store each option it supports
+  /// whether it has the default value or it has been overridden.
+  virtual void storeOptions(FlangTidyOptions::OptionMap &Options) {}
+
+  /// Provides access to the ``FlangTidyCheck`` options via check-local
+  /// names.
+  ///
+  /// Methods of this class prepend ``CheckName + "."`` to translate check-local
+  /// option names to global option names.
+  class OptionsView {
+    void diagnoseBadIntegerOption(const llvm::Twine &Lookup,
+                                  llvm::StringRef Unparsed) const;
+    void diagnoseBadBooleanOption(const llvm::Twine &Lookup,
+                                  llvm::StringRef Unparsed) const;
+    void
+    diagnoseBadEnumOption(const llvm::Twine &Lookup, llvm::StringRef Unparsed,
+                          llvm::StringRef Suggestion = llvm::StringRef()) const;
+
+  public:
+    /// Initializes the instance using \p CheckName + "." as a prefix.
+    OptionsView(llvm::StringRef CheckName,
+                const FlangTidyOptions::OptionMap &CheckOptions,
+                FlangTidyContext *Context);
+
+    /// Read a named option from the ``Context``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from the
+    /// ``CheckOptions``. If the corresponding key is not present, return
+    /// ``std::nullopt``.
+    std::optional<llvm::StringRef> get(llvm::StringRef LocalName) const;
+
+    /// Read a named option from the ``Context``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from the
+    /// ``CheckOptions``. If the corresponding key is not present, returns
+    /// \p Default.
+    llvm::StringRef get(llvm::StringRef LocalName,
+                        llvm::StringRef Default) const;
+
+    /// Read a named option from the ``Context``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from local or
+    /// global ``CheckOptions``. Gets local option first. If local is not
+    /// present, falls back to get global option. If global option is not
+    /// present either, return ``std::nullopt``.
+    std::optional<llvm::StringRef>
+    getLocalOrGlobal(llvm::StringRef LocalName) const;
+
+    /// Read a named option from the ``Context``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from local or
+    /// global ``CheckOptions``. Gets local option first. If local is not
+    /// present, falls back to get global option. If global option is not
+    /// present either, returns \p Default.
+    llvm::StringRef getLocalOrGlobal(llvm::StringRef LocalName,
+                                     llvm::StringRef Default) const;
+
+    /// Read a named option from the ``Context`` and parse it as an
+    /// integral type ``T``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from the
+    /// ``CheckOptions``. If the corresponding key is not present,
+    ///  return ``std::nullopt``.
+    ///
+    /// If the corresponding key can't be parsed as a ``T``, emit a
+    /// diagnostic and return ``std::nullopt``.
+    template <typename T>
+    std::enable_if_t<std::is_integral_v<T>, std::optional<T>>
+    get(llvm::StringRef LocalName) const {
+      if (std::optional<llvm::StringRef> Value = get(LocalName)) {
+        T Result{};
+        if (!llvm::StringRef(*Value).getAsInteger(10, Result))
+          return Result;
+        diagnoseBadIntegerOption(NamePrefix + LocalName, *Value);
+      }
+      return std::nullopt;
+    }
+
+    /// Read a named option from the ``Context`` and parse it as an
+    /// integral type ``T``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from the
+    /// ``CheckOptions``. If the corresponding key is `none`, `null`,
+    /// `-1` or empty, return ``std::nullopt``. If the corresponding
+    /// key is not present, return \p Default.
+    ///
+    /// If the corresponding key can't be parsed as a ``T``, emit a
+    /// diagnostic and return \p Default.
+    template <typename T>
+    std::enable_if_t<std::is_integral_v<T>, std::optional<T>>
+    get(llvm::StringRef LocalName, std::optional<T> Default) const {
+      if (std::optional<llvm::StringRef> Value = get(LocalName)) {
+        if (Value == "" || Value == "none" || Value == "null" ||
+            (std::is_unsigned_v<T> && Value == "-1"))
+          return std::nullopt;
+        T Result{};
+        if (!llvm::StringRef(*Value).getAsInteger(10, Result))
+          return Result;
+        diagnoseBadIntegerOption(NamePrefix + LocalName, *Value);
+      }
+      return Default;
+    }
+
+    /// Read a named option from the ``Context`` and parse it as an
+    /// integral type ``T``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from the
+    /// ``CheckOptions``. If the corresponding key is not present, return
+    /// \p Default.
+    ///
+    /// If the corresponding key can't be parsed as a ``T``, emit a
+    /// diagnostic and return \p Default.
+    template <typename T>
+    std::enable_if_t<std::is_integral_v<T>, T> get(llvm::StringRef LocalName,
+                                                   T Default) const {
+      return get<T>(LocalName).value_or(Default);
+    }
+
+    /// Read a named option from the ``Context`` and parse it as an
+    /// integral type ``T``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from local or
+    /// global ``CheckOptions``. Gets local option first. If local is not
+    /// present, falls back to get global option. If global option is not
+    /// present either, return ``std::nullopt``.
+    ///
+    /// If the corresponding key can't be parsed as a ``T``, emit a
+    /// diagnostic and return ``std::nullopt``.
+    template <typename T>
+    std::enable_if_t<std::is_integral_v<T>, std::optional<T>>
+    getLocalOrGlobal(llvm::StringRef LocalName) const {
+      std::optional<llvm::StringRef> ValueOr = get(LocalName);
+      bool IsGlobal = false;
+      if (!ValueOr) {
+        IsGlobal = true;
+        ValueOr = getLocalOrGlobal(LocalName);
+        if (!ValueOr)
+          return std::nullopt;
+      }
+      T Result{};
+      if (!llvm::StringRef(*ValueOr).getAsInteger(10, Result))
+        return Result;
+      diagnoseBadIntegerOption(
+          IsGlobal ? llvm::Twine(LocalName) : NamePrefix + LocalName, *ValueOr);
+      return std::nullopt;
+    }
+
+    /// Read a named option from the ``Context`` and parse it as an
+    /// integral type ``T``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from local or
+    /// global ``CheckOptions``. Gets local option first. If local is not
+    /// present, falls back to get global option. If global option is not
+    /// present either, return \p Default. If the value value was found
+    /// and equals ``none``, ``null``, ``-1`` or empty, return ``std::nullopt``.
+    ///
+    /// If the corresponding key can't be parsed as a ``T``, emit a
+    /// diagnostic and return \p Default.
+    template <typename T>
+    std::enable_if_t<std::is_integral_v<T>, std::optional<T>>
+    getLocalOrGlobal(llvm::StringRef LocalName,
+                     std::optional<T> Default) const {
+      std::optional<llvm::StringRef> ValueOr = get(LocalName);
+      bool IsGlobal = false;
+      if (!ValueOr) {
+        IsGlobal = true;
+        ValueOr = getLocalOrGlobal(LocalName);
+        if (!ValueOr)
+          return Default;
+      }
+      T Result{};
+      if (ValueOr == "" || ValueOr == "none" || ValueOr == "null" ||
+          (std::is_unsigned_v<T> && ValueOr == "-1"))
+        return std::nullopt;
+      if (!llvm::StringRef(*ValueOr).getAsInteger(10, Result))
+        return Result;
+      diagnoseBadIntegerOption(
+          IsGlobal ? llvm::Twine(LocalName) : NamePrefix + LocalName, *ValueOr);
+      return Default;
+    }
+
+    /// Read a named option from the ``Context`` and parse it as an
+    /// integral type ``T``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from local or
+    /// global ``CheckOptions``. Gets local option first. If local is not
+    /// present, falls back to get global option. If global option is not
+    /// present either, return \p Default.
+    ///
+    /// If the corresponding key can't be parsed as a ``T``, emit a
+    /// diagnostic and return \p Default.
+    template <typename T>
+    std::enable_if_t<std::is_integral_v<T>, T>
+    getLocalOrGlobal(llvm::StringRef LocalName, T Default) const {
+      return getLocalOrGlobal<T>(LocalName).value_or(Default);
+    }
+
+    /// Read a named option from the ``Context`` and parse it as an
+    /// enum type ``T``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from the
+    /// ``CheckOptions``. If the corresponding key is not present, return
+    /// ``std::nullopt``.
+    ///
+    /// If the corresponding key can't be parsed as a ``T``, emit a
+    /// diagnostic and return ``std::nullopt``.
+    ///
+    /// \ref Fortran::tidy::OptionEnumMapping must be specialized for ``T`` to
+    /// supply the mapping required to convert between ``T`` and a string.
+    template <typename T>
+    std::enable_if_t<std::is_enum_v<T>, std::optional<T>>
+    get(llvm::StringRef LocalName) const {
+      if (std::optional<int64_t> ValueOr =
+              getEnumInt(LocalName, typeEraseMapping<T>(), false))
+        return static_cast<T>(*ValueOr);
+      return std::nullopt;
+    }
+
+    /// Read a named option from the ``Context`` and parse it as an
+    /// enum type ``T``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from the
+    /// ``CheckOptions``. If the corresponding key is not present,
+    /// return \p Default.
+    ///
+    /// If the corresponding key can't be parsed as a ``T``, emit a
+    /// diagnostic and return \p Default.
+    ///
+    /// \ref Fortran::tidy::OptionEnumMapping must be specialized for ``T`` to
+    /// supply the mapping required to convert between ``T`` and a string.
+    template <typename T>
+    std::enable_if_t<std::is_enum_v<T>, T> get(llvm::StringRef LocalName,
+                                               T Default) const {
+      return get<T>(LocalName).value_or(Default);
+    }
+
+    /// Read a named option from the ``Context`` and parse it as an
+    /// enum type ``T``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from local or
+    /// global ``CheckOptions``. Gets local option first. If local is not
+    /// present, falls back to get global option. If global option is not
+    /// present either, returns ``std::nullopt``.
+    ///
+    /// If the corresponding key can't be parsed as a ``T``, emit a
+    /// diagnostic and return ``std::nullopt``.
+    ///
+    /// \ref Fortran::tidy::OptionEnumMapping must be specialized for ``T`` to
+    /// supply the mapping required to convert between ``T`` and a string.
+    template <typename T>
+    std::enable_if_t<std::is_enum_v<T>, std::optional<T>>
+    getLocalOrGlobal(llvm::StringRef LocalName) const {
+      if (std::optional<int64_t> ValueOr =
+              getEnumInt(LocalName, typeEraseMapping<T>(), true))
+        return static_cast<T>(*ValueOr);
+      return std::nullopt;
+    }
+
+    /// Read a named option from the ``Context`` and parse it as an
+    /// enum type ``T``.
+    ///
+    /// Reads the option with the check-local name \p LocalName from local or
+    /// global ``CheckOptions``. Gets local option first. If local is not
+    /// present, falls back to get global option. If global option is not
+    /// present either return \p Default.
+    ///
+    /// If the corresponding key can't be parsed as a ``T``, emit a
+    /// diagnostic and return \p Default.
+    ///
+    /// \ref Fortran::tidy::OptionEnumMapping must be specialized for ``T`` to
+    /// supply the mapping required to convert between ``T`` and a string.
+    template <typename T>
+    std::enable_if_t<std::is_enum_v<T>, T>
+    getLocalOrGlobal(llvm::StringRef LocalName, T Default) const {
+      return getLocalOrGlobal<T>(LocalName).value_or(Default);
+    }
+
+    /// Stores an option with the check-local name \p LocalName with
+    /// string value \p Value to \p Options.
+    void store(FlangTidyOptions::OptionMap &Options, llvm::StringRef LocalName,
+               llvm::StringRef Value) const;
+
+    /// Stores an option with the check-local name \p LocalName with
+    /// integer value \p Value to \p Options.
+    template <typename T>
+    std::enable_if_t<std::is_integral_v<T>>
+    store(FlangTidyOptions::OptionMap &Options, llvm::StringRef LocalName,
+          T Value) const {
+      if constexpr (std::is_signed_v<T>)
+        storeInt(Options, LocalName, Value);
+      else
+        storeUnsigned(Options, LocalName, Value);
+    }
+
+    /// Stores an option with the check-local name \p LocalName with
+    /// integer value \p Value to \p Options. If the value is empty
+    /// stores "none"
+    template <typename T>
+    std::enable_if_t<std::is_integral_v<T>>
+    store(FlangTidyOptions::OptionMap &Options, llvm::StringRef LocalName,
+          std::optional<T> Value) const {
+      if (Value)
+        store(Options, LocalName, *Value);
+      else
+        store(Options, LocalName, "none");
+    }
+
+    /// Stores an option with the check-local name \p LocalName as the string
+    /// representation of the Enum \p Value to \p Options.
+    ///
+    /// \ref Fortran::tidy::OptionEnumMapping must be specialized for ``T`` to
+    /// supply the mapping required to convert between ``T`` and a string.
+    template <typename T>
+    std::enable_if_t<std::is_enum_v<T>>
+    store(FlangTidyOptions::OptionMap &Options, llvm::StringRef LocalName,
+          T Value) const {
+      llvm::ArrayRef<std::pair<T, llvm::StringRef>> Mapping =
+          OptionEnumMapping<T>::getEnumMapping();
+      auto Iter = llvm::find_if(
+          Mapping, [&](const std::pair<T, llvm::StringRef> &NameAndEnum) {
+            return NameAndEnum.first == Value;
+          });
+      assert(Iter != Mapping.end() && "Unknown Case Value");
+      store(Options, LocalName, Iter->second);
+    }
+
+  private:
+    using NameAndValue = std::pair<int64_t, llvm::StringRef>;
+
+    std::optional<int64_t> getEnumInt(llvm::StringRef LocalName,
+                                      llvm::ArrayRef<NameAndValue> Mapping,
+                                      bool CheckGlobal) const;
+
+    template <typename T>
+    std::enable_if_t<std::is_enum_v<T>, std::vector<NameAndValue>>
+    typeEraseMapping() const {
+      llvm::ArrayRef<std::pair<T, llvm::StringRef>> Mapping =
+          OptionEnumMapping<T>::getEnumMapping();
+      std::vector<NameAndValue> Result;
+      Result.reserve(Mapping.size());
+      for (auto &MappedItem : Mapping) {
+        Result.emplace_back(static_cast<int64_t>(MappedItem.first),
+                            MappedItem.second);
+      }
+      return Result;
+    }
+
+    void storeInt(FlangTidyOptions::OptionMap &Options,
+                  llvm::StringRef LocalName, int64_t Value) const;
+
+    void storeUnsigned(FlangTidyOptions::OptionMap &Options,
+                       llvm::StringRef LocalName, uint64_t Value) const;
+
+    std::string NamePrefix;
+    const FlangTidyOptions::OptionMap &CheckOptions;
+    FlangTidyContext *Context;
+  };
+
+  virtual void Enter(const parser::AcImpliedDo &) {}
+  virtual void Enter(const parser::ArithmeticIfStmt &) {}
+  virtual void Enter(const parser::AssignedGotoStmt &) {}
+  virtual void Enter(const parser::AssignmentStmt &) {}
+  virtual void Enter(const parser::AssignStmt &) {}
+  virtual void Enter(const parser::AssociateConstruct &) {}
+  virtual void Enter(const parser::BackspaceStmt &) {}
+  virtual void Enter(const parser::Block &) {}
+  virtual void Enter(const parser::CallStmt &) {}
+  virtual void Enter(const parser::CaseConstruct &) {}
+  virtual void Enter(const parser::CommonStmt &) {}
+  virtual void Enter(const parser::ComputedGotoStmt &) {}
+  virtual void Enter(const parser::DataImpliedDo &) {}
+  virtual void Enter(const parser::DataStmt &) {}
+  virtual void Enter(const parser::DoConstruct &) {}
+  virtual void Enter(const parser::EntityDecl &) {}
+  virtual void Enter(const parser::ExecutableConstruct &) {}
+  virtual void Enter(const parser::Expr &) {}
+  virtual void Enter(const parser::Expr::AND &) {}
+  virtual void Enter(const parser::Expr::OR &) {}
+  virtual void Enter(const parser::ForallConstruct &) {}
+  virtual void Enter(const parser::ForallStmt &) {}
+  virtual void Enter(const parser::FunctionSubprogram &) {}
+  virtual void Enter(const parser::GotoStmt &) {}
+  virtual void Enter(const parser::IfConstruct &) {}
+  virtual void Enter(const parser::InputImpliedDo &) {}
+  virtual void Enter(const parser::OmpAtomicUpdate &) {}
+  virtual void Enter(const parser::OpenMPBlockConstruct &) {}
+  virtual void Enter(const parser::OpenMPCriticalConstruct &) {}
+  virtual void Enter(const parser::OpenMPLoopConstruct &) {}
+  virtual void Enter(const parser::OutputImpliedDo &) {}
+  virtual void Enter(const parser::PauseStmt &) {}
+  virtual void Enter(const parser::SelectRankConstruct &) {}
+  virtual void Enter(const parser::SelectTypeConstruct &) {}
+  virtual void Enter(const parser::SubroutineSubprogram &) {}
+  virtual void Leave(const parser::AllocateStmt &) {}
+  virtual void Leave(const parser::AssignmentStmt &) {}
+  virtual void Leave(const parser::BackspaceStmt &) {}
+  virtual void Leave(const parser::Block &) {}
+  virtual void Leave(const parser::CloseStmt &) {}
+  virtual void Leave(const parser::CommonStmt &) {}
+  virtual void Leave(const parser::DeallocateStmt &) {}
+  virtual void Leave(const parser::EndfileStmt &) {}
+  virtual void Leave(const parser::EventPostStmt &) {}
+  virtual void Leave(const parser::EventWaitStmt &) {}
+  virtual void Leave(const parser::FileUnitNumber &) {}
+  virtual void Leave(const parser::FlushStmt &) {}
+  virtual void Leave(const parser::FormTeamStmt &) {}
+  virtual void Leave(const parser::FunctionSubprogram &) {}
+  virtual void Leave(const parser::InquireStmt &) {}
+  virtual void Leave(const parser::LockStmt &) {}
+  virtual void Leave(const parser::Name &) {}
+  virtual void Leave(const parser::OmpAtomicUpdate &) {}
+  virtual void Leave(const parser::OpenMPBlockConstruct &) {}
+  virtual void Leave(const parser::OpenMPCriticalConstruct &) {}
+  virtual void Leave(const parser::OpenMPLoopConstruct &) {}
+  virtual void Leave(const parser::OpenStmt &) {}
+  virtual void Leave(const parser::PointerAssignmentStmt &) {}
+  virtual void Leave(const parser::PrintStmt &) {}
+  virtual void Leave(const parser::Program &) {}
+  virtual void Leave(const parser::ReadStmt &) {}
+  virtual void Leave(const parser::RewindStmt &) {}
+  virtual void Leave(const parser::SubroutineSubprogram &) {}
+  virtual void Leave(const parser::SyncAllStmt &) {}
+  virtual void Leave(const parser::SyncImagesStmt &) {}
+  virtual void Leave(const parser::SyncMemoryStmt &) {}
+  virtual void Leave(const parser::SyncTeamStmt &) {}
+  virtual void Leave(const parser::UnlockStmt &) {}
+  virtual void Leave(const parser::UseStmt &) {}
+  virtual void Leave(const parser::WaitStmt &) {}
+  virtual void Leave(const parser::WriteStmt &) {}
+
+  template <typename... Args>
+  parser::Message &Say(parser::CharBlock at, parser::MessageFixedText &&message,
+                       Args &&...args) {
+    // construct a new fixedTextMessage
+    std::string str{message.text().ToString()};
+    str.append(" [%s]");
+    parser::MessageFixedText newMessage{str.c_str(), str.length(),
+                                        message.severity()};
+    return context_->getSemanticsContext().Say(
+        at, std::move(newMessage), std::forward<Args>(args)..., name_.str());
+  }
+
+protected:
+  OptionsView Options;
+
+private:
+  bool fixAvailable_{false};
+  llvm::StringRef name_;
+  FlangTidyContext *context_;
+};
+
+/// Read a named option from the ``Context`` and parse it as a bool.
+///
+/// Reads the option with the check-local name \p LocalName from the
+/// ``CheckOptions``. If the corresponding key is not present, return
+/// ``std::nullopt``.
+///
+/// If the corresponding key can't be parsed as a bool, emit a
+/// diagnostic and return ``std::nullopt``.
+template <>
+std::optional<bool>
+FlangTidyCheck::OptionsView::get<bool>(llvm::StringRef LocalName) const;
+
+/// Read a named option from the ``Context`` and parse it as a bool.
+///
+/// Reads the option with the check-local name \p LocalName from the
+/// ``CheckOptions``. If the corresponding key is not present, return
+/// \p Default.
+///
+/// If the corresponding key can't be parsed as a bool, emit a
+/// diagnostic and return \p Default.
+template <>
+std::optional<bool> FlangTidyCheck::OptionsView::getLocalOrGlobal<bool>(
+    llvm::StringRef LocalName) const;
+
+/// Stores an option with the check-local name \p LocalName with
+/// bool value \p Value to \p Options.
+template <>
+void FlangTidyCheck::OptionsView::store<bool>(
+    FlangTidyOptions::OptionMap &Options, llvm::StringRef LocalName,
+    bool Value) const;
+
+} // namespace Fortran::tidy
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYCHECK_H
diff --git a/flang/tools/flang-tidy/FlangTidyContext.h b/flang/tools/flang-tidy/FlangTidyContext.h
new file mode 100644
index 0000000000000..8158ccdce6d7f
--- /dev/null
+++ b/flang/tools/flang-tidy/FlangTidyContext.h
@@ -0,0 +1,78 @@
+//===--- FlangTidyContext.h - flang-tidy ------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYCONTEXT_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYCONTEXT_H
+
+#include "FlangTidyOptions.h"
+#include "flang/Semantics/semantics.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/StringRef.h"
+#include <clang/Basic/Diagnostic.h>
+
+namespace Fortran::tidy {
+
+/// This class is used to manage the context for Flang Tidy checks.
+/// It contains the enabled checks and the semantics context.
+/// It provides methods to check if a specific check is enabled and to access
+/// the semantics context.
+///
+/// For user-facing documentation, see:
+/// https://flang.llvm.org/@PLACEHOLDER@/flang-tidy.html
+class FlangTidyContext {
+public:
+  FlangTidyContext(const FlangTidyOptions &options,
+                   semantics::SemanticsContext *ctx) {
+    Options = options;
+    for (const auto &CheckName : options.enabledChecks) {
+      Checks.insert(CheckName);
+    }
+    Context = ctx;
+  }
+
+  bool isCheckEnabled(const llvm::StringRef &CheckName) const {
+    bool enabled = false;
+    for (const auto &Pattern : Checks) {
+      if (Pattern.starts_with("-")) {
+        llvm::StringRef DisablePrefix = Pattern.drop_front(1);
+        if (DisablePrefix.ends_with("*")) {
+          DisablePrefix = DisablePrefix.drop_back(1);
+          if (CheckName.starts_with(DisablePrefix)) {
+            enabled = false;
+          }
+        } else if (DisablePrefix == CheckName) {
+          enabled = false;
+        }
+      } else if (Pattern.ends_with("*")) {
+        llvm::StringRef EnablePrefix = Pattern.drop_back(1);
+        if (CheckName.starts_with(EnablePrefix)) {
+          enabled = true;
+        }
+      } else if (Pattern == CheckName) {
+        enabled = true;
+      }
+    }
+    return enabled;
+  }
+
+  semantics::SemanticsContext &getSemanticsContext() const { return *Context; }
+
+  /// Get the FlangTidy options
+  const FlangTidyOptions &getOptions() const { return Options; }
+
+public:
+  /// List of enabled checks.
+  llvm::SmallSet<llvm::StringRef, 16> Checks;
+  /// The semantics context used for the checks.
+  semantics::SemanticsContext *Context;
+  FlangTidyOptions Options;
+};
+
+} // namespace Fortran::tidy
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYCONTEXT_H
diff --git a/flang/tools/flang-tidy/FlangTidyForceLinker.h b/flang/tools/flang-tidy/FlangTidyForceLinker.h
new file mode 100644
index 0000000000000..3e9467013ea1c
--- /dev/null
+++ b/flang/tools/flang-tidy/FlangTidyForceLinker.h
@@ -0,0 +1,18 @@
+//===--- FlangTidyForceLinker.h - flang-tidy --------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYFORCELINKER_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYFORCELINKER_H
+
+#include "llvm/Support/Compiler.h"
+
+namespace Fortran::tidy {
+
+} // namespace Fortran::tidy
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYFORCELINKER_H
diff --git a/flang/tools/flang-tidy/FlangTidyModule.cpp b/flang/tools/flang-tidy/FlangTidyModule.cpp
new file mode 100644
index 0000000000000..1cdb2a20f7dfb
--- /dev/null
+++ b/flang/tools/flang-tidy/FlangTidyModule.cpp
@@ -0,0 +1,49 @@
+//===--- FlangTidyModule.cpp - flang-tidy ---------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "FlangTidyModule.h"
+#include "FlangTidyCheck.h"
+#include "FlangTidyContext.h"
+
+namespace Fortran::tidy {
+
+void FlangTidyCheckFactories::registerCheckFactory(llvm::StringRef Name,
+                                                   CheckFactory Factory) {
+  Factories.insert_or_assign(Name, std::move(Factory));
+}
+
+std::vector<std::unique_ptr<FlangTidyCheck>>
+FlangTidyCheckFactories::createChecks(FlangTidyContext *Context) const {
+  std::vector<std::unique_ptr<FlangTidyCheck>> Checks;
+  for (const auto &Factory : Factories) {
+    if (Context->isCheckEnabled(Factory.getKey())) {
+      Checks.emplace_back(Factory.getValue()(Factory.getKey(), Context));
+    }
+  }
+  return Checks;
+}
+
+std::vector<std::unique_ptr<FlangTidyCheck>>
+FlangTidyCheckFactories::createChecksForLanguage(
+    FlangTidyContext *Context) const {
+  std::vector<std::unique_ptr<FlangTidyCheck>> Checks;
+  // const LangOptions &LO = Context->getLangOpts();
+  for (const auto &Factory : Factories) {
+    if (!Context->isCheckEnabled(Factory.getKey()))
+      continue;
+    std::unique_ptr<FlangTidyCheck> Check =
+        Factory.getValue()(Factory.getKey(), Context);
+    // if (Check->isLanguageVersionSupported(LO))
+    //   Checks.push_back(std::move(Check));
+  }
+  return Checks;
+}
+
+FlangTidyOptions FlangTidyModule::getModuleOptions() { return {}; }
+
+} // namespace Fortran::tidy
diff --git a/flang/tools/flang-tidy/FlangTidyModule.h b/flang/tools/flang-tidy/FlangTidyModule.h
new file mode 100644
index 0000000000000..b3658767da2b2
--- /dev/null
+++ b/flang/tools/flang-tidy/FlangTidyModule.h
@@ -0,0 +1,99 @@
+//===--- FlangTidyModule.h - flang-tidy -------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYMODULE_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYMODULE_H
+
+#include "FlangTidyOptions.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringRef.h"
+#include <functional>
+#include <memory>
+
+namespace Fortran::tidy {
+
+class FlangTidyCheck;
+class FlangTidyContext;
+
+/// A collection of \c TidyCheckFactory instances.
+///
+/// All Flang-tidy modules register their check factories with an instance of
+/// this object.
+class FlangTidyCheckFactories {
+public:
+  using CheckFactory = std::function<std::unique_ptr<FlangTidyCheck>(
+      llvm::StringRef Name, FlangTidyContext *Context)>;
+
+  /// Registers check \p Factory with name \p Name.
+  ///
+  /// For all checks that have default constructors, use \c registerCheck.
+  void registerCheckFactory(llvm::StringRef Name, CheckFactory Factory);
+
+  /// Registers the \c CheckType with the name \p Name.
+  ///
+  /// This method should be used for all \c FlangTidyChecks that don't require
+  /// constructor parameters.
+  ///
+  /// For example, if have a Flang-tidy check like:
+  /// \code
+  /// class MyTidyCheck : public FlangTidyCheck {
+  ///   void registerMatchers(ast_matchers::MatchFinder *Finder) override {
+  ///     ..
+  ///   }
+  /// };
+  /// \endcode
+  /// you can register it with:
+  /// \code
+  /// class MyModule : public FlangTidyModule {
+  ///   void addCheckFactories(FlangTidyCheckFactories &Factories) override {
+  ///     Factories.registerCheck<MyTidyCheck>("myproject-my-check");
+  ///   }
+  /// };
+  /// \endcode
+  template <typename CheckType>
+  void registerCheck(llvm::StringRef CheckName) {
+    registerCheckFactory(CheckName,
+                         [](llvm::StringRef Name, FlangTidyContext *Context) {
+                           return std::make_unique<CheckType>(Name, Context);
+                         });
+  }
+
+  /// Create instances of checks that are enabled.
+  std::vector<std::unique_ptr<FlangTidyCheck>>
+  createChecks(FlangTidyContext *Context) const;
+
+  /// Create instances of checks that are enabled for the current Language.
+  std::vector<std::unique_ptr<FlangTidyCheck>>
+  createChecksForLanguage(FlangTidyContext *Context) const;
+
+  using FactoryMap = llvm::StringMap<CheckFactory>;
+  FactoryMap::const_iterator begin() const { return Factories.begin(); }
+  FactoryMap::const_iterator end() const { return Factories.end(); }
+  bool empty() const { return Factories.empty(); }
+
+private:
+  FactoryMap Factories;
+};
+
+/// A flang-tidy module groups a number of \c FlangTidyChecks and gives
+/// them a prefixed name.
+class FlangTidyModule {
+public:
+  virtual ~FlangTidyModule() {}
+
+  /// Implement this function in order to register all \c CheckFactories
+  /// belonging to this module.
+  virtual void addCheckFactories(FlangTidyCheckFactories &CheckFactories) = 0;
+
+  /// Gets default options for checks defined in this module.
+  virtual FlangTidyOptions getModuleOptions();
+};
+
+} // namespace Fortran::tidy
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYMODULE_H
diff --git a/flang/tools/flang-tidy/FlangTidyModuleRegistry.h b/flang/tools/flang-tidy/FlangTidyModuleRegistry.h
new file mode 100644
index 0000000000000..18ebf5c30ef28
--- /dev/null
+++ b/flang/tools/flang-tidy/FlangTidyModuleRegistry.h
@@ -0,0 +1,25 @@
+//===--- FlangTidyModuleRegistry.h - flang-tidy -----------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYMODULEREGISTRY_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYMODULEREGISTRY_H
+
+#include "FlangTidyModule.h"
+#include "llvm/Support/Registry.h"
+
+namespace Fortran::tidy {
+
+using FlangTidyModuleRegistry = llvm::Registry<FlangTidyModule>;
+
+} // namespace Fortran::tidy
+
+namespace llvm {
+extern template class Registry<Fortran::tidy::FlangTidyModule>;
+} // namespace llvm
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYMODULEREGISTRY_H
diff --git a/flang/tools/flang-tidy/FlangTidyOptions.cpp b/flang/tools/flang-tidy/FlangTidyOptions.cpp
new file mode 100644
index 0000000000000..aaf7dac0f19be
--- /dev/null
+++ b/flang/tools/flang-tidy/FlangTidyOptions.cpp
@@ -0,0 +1,420 @@
+//===--- FlangTidyOptions.cpp - flang-tidy --------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "FlangTidyOptions.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/MemoryBufferRef.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/YAMLTraits.h"
+#include <algorithm>
+#include <sstream>
+
+#define DEBUG_TYPE "flang-tidy-options"
+
+using Fortran::tidy::FlangTidyOptions;
+using OptionsSource = Fortran::tidy::FlangTidyOptionsProvider::OptionsSource;
+
+namespace llvm::yaml {
+
+template <>
+struct MappingTraits<FlangTidyOptions::StringPair> {
+  static void mapping(IO &IO, FlangTidyOptions::StringPair &KeyValue) {
+    IO.mapRequired("key", KeyValue.first);
+    IO.mapRequired("value", KeyValue.second);
+  }
+};
+
+struct NOptionMap {
+  NOptionMap(IO &) {}
+  NOptionMap(IO &, const FlangTidyOptions::OptionMap &OptionMap) {
+    Options.reserve(OptionMap.size());
+    for (const auto &KeyValue : OptionMap)
+      Options.emplace_back(std::string(KeyValue.getKey()),
+                           KeyValue.getValue().Value);
+  }
+  FlangTidyOptions::OptionMap denormalize(IO &) {
+    FlangTidyOptions::OptionMap Map;
+    for (const auto &KeyValue : Options)
+      Map[KeyValue.first] = FlangTidyOptions::FlangTidyValue(KeyValue.second);
+    return Map;
+  }
+  std::vector<FlangTidyOptions::StringPair> Options;
+};
+
+template <>
+void yamlize(IO &IO, FlangTidyOptions::OptionMap &Val, bool,
+             EmptyContext &Ctx) {
+  if (IO.outputting()) {
+    // Ensure check options are sorted
+    std::vector<std::pair<llvm::StringRef, llvm::StringRef>> SortedOptions;
+    SortedOptions.reserve(Val.size());
+    for (auto &Key : Val) {
+      SortedOptions.emplace_back(Key.getKey(), Key.getValue().Value);
+    }
+    std::sort(SortedOptions.begin(), SortedOptions.end());
+
+    IO.beginMapping();
+    // Only output as a map
+    for (auto &Option : SortedOptions) {
+      bool UseDefault = false;
+      void *SaveInfo = nullptr;
+      IO.preflightKey(Option.first.data(), true, false, UseDefault, SaveInfo);
+      IO.scalarString(Option.second, needsQuotes(Option.second));
+      IO.postflightKey(SaveInfo);
+    }
+    IO.endMapping();
+  } else {
+    // Support both old list format and new map format for reading
+    auto &I = reinterpret_cast<Input &>(IO);
+    if (isa<SequenceNode>(I.getCurrentNode())) {
+      MappingNormalization<NOptionMap, FlangTidyOptions::OptionMap> NOpts(IO,
+                                                                          Val);
+      EmptyContext Ctx;
+      yamlize(IO, NOpts->Options, true, Ctx);
+    } else if (isa<MappingNode>(I.getCurrentNode())) {
+      IO.beginMapping();
+      for (llvm::StringRef Key : IO.keys()) {
+        IO.mapRequired(Key.data(), Val[Key].Value);
+      }
+      IO.endMapping();
+    } else {
+      IO.setError("expected a sequence or map");
+    }
+  }
+}
+
+template <>
+struct MappingTraits<FlangTidyOptions> {
+  static void mapping(IO &IO, FlangTidyOptions &Options) {
+    IO.mapOptional("Checks", Options.Checks);
+    IO.mapOptional("CheckOptions", Options.CheckOptions);
+    IO.mapOptional("ExtraArgs", Options.ExtraArgs);
+    IO.mapOptional("ExtraArgsBefore", Options.ExtraArgsBefore);
+    IO.mapOptional("InheritParentConfig", Options.InheritParentConfig);
+  }
+};
+
+} // namespace llvm::yaml
+
+namespace Fortran::tidy {
+
+const char FlangTidyOptionsProvider::OptionsSourceTypeDefaultBinary[] =
+    "flang-tidy binary";
+const char FlangTidyOptionsProvider::OptionsSourceTypeCheckCommandLineOption[] =
+    "command-line option '-checks'";
+const char
+    FlangTidyOptionsProvider::OptionsSourceTypeConfigCommandLineOption[] =
+        "command-line option '-config'";
+
+FlangTidyOptions FlangTidyOptions::getDefaults() {
+  FlangTidyOptions Options;
+  Options.Checks = "*";
+  return Options;
+}
+
+template <typename T>
+static void mergeVectors(std::optional<T> &Dest, const std::optional<T> &Src) {
+  if (Src) {
+    if (Dest)
+      Dest->insert(Dest->end(), Src->begin(), Src->end());
+    else
+      Dest = Src;
+  }
+}
+
+template <typename T>
+static void overrideValue(std::optional<T> &Dest, const std::optional<T> &Src) {
+  if (Src)
+    Dest = Src;
+}
+
+FlangTidyOptions &FlangTidyOptions::mergeWith(const FlangTidyOptions &Other,
+                                              unsigned Order) {
+  // For checks: if Other has checks defined, override completely (don't merge)
+  // This ensures config file checks override defaults instead of appending
+  if (Other.Checks) {
+    Checks = Other.Checks;
+  }
+
+  mergeVectors(ExtraArgs, Other.ExtraArgs);
+  mergeVectors(ExtraArgsBefore, Other.ExtraArgsBefore);
+  overrideValue(InheritParentConfig, Other.InheritParentConfig);
+
+  for (const auto &KeyValue : Other.CheckOptions) {
+    CheckOptions.insert_or_assign(
+        KeyValue.getKey(),
+        FlangTidyValue(KeyValue.getValue().Value,
+                       KeyValue.getValue().Priority + Order));
+  }
+  return *this;
+}
+
+FlangTidyOptions FlangTidyOptions::merge(const FlangTidyOptions &Other,
+                                         unsigned Order) const {
+  FlangTidyOptions Result = *this;
+  Result.mergeWith(Other, Order);
+  return Result;
+}
+
+void FlangTidyOptions::parseChecksString() {
+  enabledChecks.clear();
+  if (!Checks || Checks->empty())
+    return;
+
+  std::stringstream ss(*Checks);
+  std::string check;
+  while (std::getline(ss, check, ',')) {
+    // Trim whitespace
+    check.erase(0, check.find_first_not_of(" \t"));
+    check.erase(check.find_last_not_of(" \t") + 1);
+    if (!check.empty()) {
+      enabledChecks.push_back(check);
+    }
+  }
+}
+
+FlangTidyOptions
+FlangTidyOptionsProvider::getOptions(llvm::StringRef FileName) {
+  FlangTidyOptions Result;
+  unsigned Priority = 0;
+  for (auto &Source : getRawOptions(FileName))
+    Result.mergeWith(Source.first, ++Priority);
+  return Result;
+}
+
+std::vector<OptionsSource>
+DefaultOptionsProvider::getRawOptions(llvm::StringRef FileName) {
+  std::vector<OptionsSource> Result;
+  Result.emplace_back(DefaultOptions, OptionsSourceTypeDefaultBinary);
+  return Result;
+}
+
+ConfigOptionsProvider::ConfigOptionsProvider(
+    FlangTidyGlobalOptions GlobalOptions, FlangTidyOptions DefaultOptions,
+    FlangTidyOptions ConfigOptions, FlangTidyOptions OverrideOptions,
+    llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
+    : FileOptionsBaseProvider(std::move(GlobalOptions),
+                              std::move(DefaultOptions),
+                              std::move(OverrideOptions), std::move(FS)),
+      ConfigOptions(std::move(ConfigOptions)) {}
+
+std::vector<OptionsSource>
+ConfigOptionsProvider::getRawOptions(llvm::StringRef FileName) {
+  std::vector<OptionsSource> RawOptions =
+      DefaultOptionsProvider::getRawOptions(FileName);
+  if (ConfigOptions.InheritParentConfig.value_or(false)) {
+    LLVM_DEBUG(llvm::dbgs()
+               << "Getting options for file " << FileName << "...\n");
+
+    llvm::ErrorOr<llvm::SmallString<128>> AbsoluteFilePath =
+        getNormalizedAbsolutePath(FileName);
+    if (AbsoluteFilePath) {
+      addRawFileOptions(AbsoluteFilePath->str(), RawOptions);
+    }
+  }
+  RawOptions.emplace_back(ConfigOptions,
+                          OptionsSourceTypeConfigCommandLineOption);
+  // Give command-line options very high priority so they override everything
+  RawOptions.emplace_back(OverrideOptions,
+                          OptionsSourceTypeCheckCommandLineOption);
+  return RawOptions;
+}
+
+FileOptionsBaseProvider::FileOptionsBaseProvider(
+    FlangTidyGlobalOptions GlobalOptions, FlangTidyOptions DefaultOptions,
+    FlangTidyOptions OverrideOptions,
+    llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
+    : DefaultOptionsProvider(std::move(GlobalOptions),
+                             std::move(DefaultOptions)),
+      OverrideOptions(std::move(OverrideOptions)), FS(std::move(VFS)) {
+  if (!FS)
+    FS = llvm::vfs::getRealFileSystem();
+  ConfigHandlers.emplace_back(".flang-tidy", parseConfiguration);
+}
+
+FileOptionsBaseProvider::FileOptionsBaseProvider(
+    FlangTidyGlobalOptions GlobalOptions, FlangTidyOptions DefaultOptions,
+    FlangTidyOptions OverrideOptions,
+    FileOptionsBaseProvider::ConfigFileHandlers ConfigHandlers)
+    : DefaultOptionsProvider(std::move(GlobalOptions),
+                             std::move(DefaultOptions)),
+      OverrideOptions(std::move(OverrideOptions)),
+      ConfigHandlers(std::move(ConfigHandlers)) {}
+
+llvm::ErrorOr<llvm::SmallString<128>>
+FileOptionsBaseProvider::getNormalizedAbsolutePath(llvm::StringRef Path) {
+  assert(FS && "FS must be set.");
+  llvm::SmallString<128> NormalizedAbsolutePath = {Path};
+  std::error_code Err = FS->makeAbsolute(NormalizedAbsolutePath);
+  if (Err)
+    return Err;
+  llvm::sys::path::remove_dots(NormalizedAbsolutePath, /*remove_dot_dot=*/true);
+  return NormalizedAbsolutePath;
+}
+
+void FileOptionsBaseProvider::addRawFileOptions(
+    llvm::StringRef AbsolutePath, std::vector<OptionsSource> &CurOptions) {
+  auto CurSize = CurOptions.size();
+  llvm::StringRef RootPath = llvm::sys::path::parent_path(AbsolutePath);
+  auto MemorizedConfigFile =
+      [this,
+       &RootPath](llvm::StringRef CurrentPath) -> std::optional<OptionsSource> {
+    const auto Iter = CachedOptions.Memorized.find(CurrentPath);
+    if (Iter != CachedOptions.Memorized.end())
+      return CachedOptions.Storage[Iter->second];
+    std::optional<OptionsSource> OptionsSource = tryReadConfigFile(CurrentPath);
+    if (OptionsSource) {
+      const size_t Index = CachedOptions.Storage.size();
+      CachedOptions.Storage.emplace_back(OptionsSource.value());
+      while (RootPath != CurrentPath) {
+        LLVM_DEBUG(llvm::dbgs()
+                   << "Caching configuration for path " << RootPath << ".\n");
+        CachedOptions.Memorized[RootPath] = Index;
+        RootPath = llvm::sys::path::parent_path(RootPath);
+      }
+      CachedOptions.Memorized[CurrentPath] = Index;
+      RootPath = llvm::sys::path::parent_path(CurrentPath);
+    }
+    return OptionsSource;
+  };
+  for (llvm::StringRef CurrentPath = RootPath; !CurrentPath.empty();
+       CurrentPath = llvm::sys::path::parent_path(CurrentPath)) {
+    if (std::optional<OptionsSource> Result =
+            MemorizedConfigFile(CurrentPath)) {
+      CurOptions.emplace_back(Result.value());
+      if (!Result->first.InheritParentConfig.value_or(false))
+        break;
+    }
+  }
+  // Reverse order of file configs because closer configs should have higher
+  // priority.
+  std::reverse(CurOptions.begin() + CurSize, CurOptions.end());
+}
+
+FileOptionsProvider::FileOptionsProvider(
+    FlangTidyGlobalOptions GlobalOptions, FlangTidyOptions DefaultOptions,
+    FlangTidyOptions OverrideOptions,
+    llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
+    : FileOptionsBaseProvider(std::move(GlobalOptions),
+                              std::move(DefaultOptions),
+                              std::move(OverrideOptions), std::move(VFS)) {}
+
+FileOptionsProvider::FileOptionsProvider(
+    FlangTidyGlobalOptions GlobalOptions, FlangTidyOptions DefaultOptions,
+    FlangTidyOptions OverrideOptions,
+    FileOptionsBaseProvider::ConfigFileHandlers ConfigHandlers)
+    : FileOptionsBaseProvider(
+          std::move(GlobalOptions), std::move(DefaultOptions),
+          std::move(OverrideOptions), std::move(ConfigHandlers)) {}
+
+std::vector<OptionsSource>
+FileOptionsProvider::getRawOptions(llvm::StringRef FileName) {
+  LLVM_DEBUG(llvm::dbgs() << "Getting options for file " << FileName
+                          << "...\n");
+
+  llvm::ErrorOr<llvm::SmallString<128>> AbsoluteFilePath =
+      getNormalizedAbsolutePath(FileName);
+  if (!AbsoluteFilePath)
+    return {};
+
+  std::vector<OptionsSource> RawOptions =
+      DefaultOptionsProvider::getRawOptions(AbsoluteFilePath->str());
+  addRawFileOptions(AbsoluteFilePath->str(), RawOptions);
+
+  // Give command-line options very high priority so they override everything
+  OptionsSource CommandLineOptions(OverrideOptions,
+                                   OptionsSourceTypeCheckCommandLineOption);
+  RawOptions.push_back(CommandLineOptions);
+  return RawOptions;
+}
+
+std::optional<OptionsSource>
+FileOptionsBaseProvider::tryReadConfigFile(llvm::StringRef Directory) {
+  assert(!Directory.empty());
+
+  llvm::ErrorOr<llvm::vfs::Status> DirectoryStatus = FS->status(Directory);
+
+  if (!DirectoryStatus || !DirectoryStatus->isDirectory()) {
+    llvm::errs() << "Error reading configuration from " << Directory
+                 << ": directory doesn't exist.\n";
+    return std::nullopt;
+  }
+
+  for (const ConfigFileHandler &ConfigHandler : ConfigHandlers) {
+    llvm::SmallString<128> ConfigFile(Directory);
+    llvm::sys::path::append(ConfigFile, ConfigHandler.first);
+    LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
+
+    llvm::ErrorOr<llvm::vfs::Status> FileStatus = FS->status(ConfigFile);
+
+    if (!FileStatus || !FileStatus->isRegularFile())
+      continue;
+
+    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
+        FS->getBufferForFile(ConfigFile);
+    if (std::error_code EC = Text.getError()) {
+      llvm::errs() << "Can't read " << ConfigFile << ": " << EC.message()
+                   << "\n";
+      continue;
+    }
+
+    // Skip empty files
+    if ((*Text)->getBuffer().empty())
+      continue;
+    llvm::ErrorOr<FlangTidyOptions> ParsedOptions =
+        ConfigHandler.second({(*Text)->getBuffer(), ConfigFile});
+    if (!ParsedOptions) {
+      if (ParsedOptions.getError())
+        llvm::errs() << "Error parsing " << ConfigFile << ": "
+                     << ParsedOptions.getError().message() << "\n";
+      continue;
+    }
+    return OptionsSource(*ParsedOptions, std::string(ConfigFile));
+  }
+  return std::nullopt;
+}
+
+llvm::ErrorOr<FlangTidyOptions>
+parseConfiguration(llvm::MemoryBufferRef Config) {
+  llvm::yaml::Input Input(Config);
+  FlangTidyOptions Options;
+  Input >> Options;
+  if (Input.error())
+    return Input.error();
+
+  // Parse the checks string into the enabledChecks vector
+  Options.parseChecksString();
+
+  return Options;
+}
+
+std::string configurationAsText(const FlangTidyOptions &Options) {
+  std::string Text;
+  llvm::raw_string_ostream Stream(Text);
+  llvm::yaml::Output Output(Stream);
+  // We use the same mapping method for input and output, so we need a non-const
+  // reference here.
+  FlangTidyOptions NonConstValue = Options;
+  Output << NonConstValue;
+  return Stream.str();
+}
+
+// Simple function to get options for a file (for backward compatibility)
+FlangTidyOptions getOptionsForFile(llvm::StringRef FileName) {
+  FlangTidyGlobalOptions GlobalOptions;
+  FlangTidyOptions DefaultOptions = FlangTidyOptions::getDefaults();
+  FlangTidyOptions OverrideOptions;
+
+  FileOptionsProvider Provider(std::move(GlobalOptions),
+                               std::move(DefaultOptions),
+                               std::move(OverrideOptions));
+  return Provider.getOptions(FileName);
+}
+
+} // namespace Fortran::tidy
diff --git a/flang/tools/flang-tidy/FlangTidyOptions.h b/flang/tools/flang-tidy/FlangTidyOptions.h
new file mode 100644
index 0000000000000..55bc2a0780515
--- /dev/null
+++ b/flang/tools/flang-tidy/FlangTidyOptions.h
@@ -0,0 +1,223 @@
+//===--- FlangTidyOptions.h - flang-tidy ------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYOPTIONS_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYOPTIONS_H
+
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/MemoryBufferRef.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include <functional>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+namespace Fortran::tidy {
+
+/// Global options for FlangTidy. These options are neither stored nor read from
+/// configuration files.
+struct FlangTidyGlobalOptions {
+  // Reserved for future use (line filters, etc.)
+};
+
+/// Contains options for flang-tidy. These options may be read from
+/// configuration files, and may be different for different translation units.
+struct FlangTidyOptions {
+  /// These options are used for all settings that haven't been
+  /// overridden by the \c OptionsProvider.
+  static FlangTidyOptions getDefaults();
+
+  /// Overwrites all fields in here by the fields of \p Other that have a value.
+  /// \p Order specifies precedence of \p Other option.
+  FlangTidyOptions &mergeWith(const FlangTidyOptions &Other, unsigned Order);
+
+  /// Creates a new \c FlangTidyOptions instance combined from all fields
+  /// of this instance overridden by the fields of \p Other that have a value.
+  /// \p Order specifies precedence of \p Other option.
+  [[nodiscard]] FlangTidyOptions merge(const FlangTidyOptions &Other,
+                                       unsigned Order) const;
+
+  /// Checks filter.
+  std::optional<std::string> Checks;
+
+  /// Helper structure for storing option value with priority of the value.
+  struct FlangTidyValue {
+    FlangTidyValue() = default;
+    FlangTidyValue(const char *Value) : Value(Value) {}
+    FlangTidyValue(llvm::StringRef Value, unsigned Priority = 0)
+        : Value(Value), Priority(Priority) {}
+
+    std::string Value;
+    /// Priority stores relative precedence of the value loaded from config
+    /// files to disambiguate local vs global value from different levels.
+    unsigned Priority = 0;
+  };
+  using StringPair = std::pair<std::string, std::string>;
+  using OptionMap = llvm::StringMap<FlangTidyValue>;
+
+  /// Key-value mapping used to store check-specific options.
+  OptionMap CheckOptions;
+
+  using ArgList = std::vector<std::string>;
+
+  /// Add extra compilation arguments to the end of the list.
+  std::optional<ArgList> ExtraArgs;
+
+  /// Add extra compilation arguments to the start of the list.
+  std::optional<ArgList> ExtraArgsBefore;
+
+  /// Only used in the FileOptionsProvider and ConfigOptionsProvider. If true
+  /// and using a FileOptionsProvider, it will take a configuration file in the
+  /// parent directory (if any exists) and apply this config file on top of the
+  /// parent one. If false or missing, only this configuration file will be
+  /// used.
+  std::optional<bool> InheritParentConfig;
+
+  // Runtime-only options (not serialized to/from YAML)
+  std::vector<std::string> sourcePaths;   // Set by command line
+  std::vector<std::string> enabledChecks; // Parsed from Checks string
+  const char *argv0 = nullptr;            // Set by command line
+
+  /// Parse the Checks string into enabledChecks vector
+  void parseChecksString();
+};
+
+/// Abstract interface for retrieving various FlangTidy options.
+class FlangTidyOptionsProvider {
+public:
+  static const char OptionsSourceTypeDefaultBinary[];
+  static const char OptionsSourceTypeCheckCommandLineOption[];
+  static const char OptionsSourceTypeConfigCommandLineOption[];
+
+  virtual ~FlangTidyOptionsProvider() {}
+
+  /// Returns global options, which are independent of the file.
+  virtual const FlangTidyGlobalOptions &getGlobalOptions() = 0;
+
+  /// FlangTidyOptions and its source.
+  using OptionsSource = std::pair<FlangTidyOptions, std::string>;
+
+  /// Returns an ordered vector of OptionsSources, in order of increasing
+  /// priority.
+  virtual std::vector<OptionsSource>
+  getRawOptions(llvm::StringRef FileName) = 0;
+
+  /// Returns options applying to a specific translation unit with the
+  /// specified \p FileName.
+  FlangTidyOptions getOptions(llvm::StringRef FileName);
+};
+
+/// Implementation of the \c FlangTidyOptionsProvider interface, which
+/// returns the same options for all files.
+class DefaultOptionsProvider : public FlangTidyOptionsProvider {
+public:
+  DefaultOptionsProvider(FlangTidyGlobalOptions GlobalOptions,
+                         FlangTidyOptions Options)
+      : GlobalOptions(std::move(GlobalOptions)),
+        DefaultOptions(std::move(Options)) {}
+  const FlangTidyGlobalOptions &getGlobalOptions() override {
+    return GlobalOptions;
+  }
+  std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
+
+protected:
+  FlangTidyGlobalOptions GlobalOptions;
+  FlangTidyOptions DefaultOptions;
+};
+
+class FileOptionsBaseProvider : public DefaultOptionsProvider {
+protected:
+  // A pair of configuration file base name and a function parsing
+  // configuration from text in the corresponding format.
+  using ConfigFileHandler =
+      std::pair<std::string, std::function<llvm::ErrorOr<FlangTidyOptions>(
+                                 llvm::MemoryBufferRef)>>;
+
+  /// Configuration file handlers listed in the order of priority.
+  using ConfigFileHandlers = std::vector<ConfigFileHandler>;
+
+  FileOptionsBaseProvider(FlangTidyGlobalOptions GlobalOptions,
+                          FlangTidyOptions DefaultOptions,
+                          FlangTidyOptions OverrideOptions,
+                          llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS);
+
+  FileOptionsBaseProvider(FlangTidyGlobalOptions GlobalOptions,
+                          FlangTidyOptions DefaultOptions,
+                          FlangTidyOptions OverrideOptions,
+                          ConfigFileHandlers ConfigHandlers);
+
+  void addRawFileOptions(llvm::StringRef AbsolutePath,
+                         std::vector<OptionsSource> &CurOptions);
+
+  llvm::ErrorOr<llvm::SmallString<128>>
+  getNormalizedAbsolutePath(llvm::StringRef AbsolutePath);
+
+  /// Try to read configuration files from \p Directory using registered
+  /// \c ConfigHandlers.
+  std::optional<OptionsSource> tryReadConfigFile(llvm::StringRef Directory);
+
+  struct OptionsCache {
+    llvm::StringMap<size_t> Memorized;
+    llvm::SmallVector<OptionsSource, 4U> Storage;
+  } CachedOptions;
+  FlangTidyOptions OverrideOptions;
+  ConfigFileHandlers ConfigHandlers;
+  llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS;
+};
+
+/// Implementation of FlangTidyOptions interface, which is used for
+/// '-config' command-line option.
+class ConfigOptionsProvider : public FileOptionsBaseProvider {
+public:
+  ConfigOptionsProvider(
+      FlangTidyGlobalOptions GlobalOptions, FlangTidyOptions DefaultOptions,
+      FlangTidyOptions ConfigOptions, FlangTidyOptions OverrideOptions,
+      llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = nullptr);
+  std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
+
+private:
+  FlangTidyOptions ConfigOptions;
+};
+
+/// Implementation of the \c FlangTidyOptionsProvider interface, which
+/// tries to find a configuration file in the closest parent directory of each
+/// source file.
+class FileOptionsProvider : public FileOptionsBaseProvider {
+public:
+  FileOptionsProvider(
+      FlangTidyGlobalOptions GlobalOptions, FlangTidyOptions DefaultOptions,
+      FlangTidyOptions OverrideOptions,
+      llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = nullptr);
+
+  FileOptionsProvider(FlangTidyGlobalOptions GlobalOptions,
+                      FlangTidyOptions DefaultOptions,
+                      FlangTidyOptions OverrideOptions,
+                      ConfigFileHandlers ConfigHandlers);
+
+  std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
+};
+
+/// Parse FlangTidy configuration from YAML and returns \c FlangTidyOptions or
+/// an error.
+llvm::ErrorOr<FlangTidyOptions>
+parseConfiguration(llvm::MemoryBufferRef Config);
+
+/// Serializes configuration to a YAML-encoded string.
+std::string configurationAsText(const FlangTidyOptions &Options);
+
+/// Simple function to get options for a file (for backward compatibility)
+FlangTidyOptions getOptionsForFile(llvm::StringRef FileName);
+
+} // namespace Fortran::tidy
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYOPTIONS_H
diff --git a/flang/tools/flang-tidy/MultiplexVisitor.h b/flang/tools/flang-tidy/MultiplexVisitor.h
new file mode 100644
index 0000000000000..1ba2df297fea9
--- /dev/null
+++ b/flang/tools/flang-tidy/MultiplexVisitor.h
@@ -0,0 +1,103 @@
+//===--- MultiplexVisitor.h - flang-tidy ------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_MULTIPLEXVISITOR_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_MULTIPLEXVISITOR_H
+
+#include "FlangTidyCheck.h"
+#include "flang/Parser/parse-tree-visitor.h"
+#include "flang/Semantics/semantics.h"
+#include <memory>
+#include <vector>
+
+namespace Fortran::tidy {
+
+class MultiplexVisitor {
+public:
+  MultiplexVisitor(semantics::SemanticsContext &context) : context_{context} {}
+
+  void AddChecker(std::unique_ptr<FlangTidyCheck> checker) {
+    checkers_.emplace_back(std::move(checker));
+  }
+
+  template <typename N>
+  bool Pre(const N &node) {
+    if constexpr (common::HasMember<const N *, semantics::ConstructNode>) {
+      context_.PushConstruct(node);
+    }
+    for (auto &checker : checkers_) {
+      checker->Enter(node);
+    }
+    return true;
+  }
+
+  template <typename N>
+  void Post(const N &node) {
+    for (auto &checker : checkers_) {
+      checker->Leave(node);
+    }
+    if constexpr (common::HasMember<const N *, semantics::ConstructNode>) {
+      context_.PopConstruct();
+    }
+  }
+
+  template <typename T>
+  bool Pre(const parser::Statement<T> &node) {
+    if (context_.IsInModuleFile(node.source))
+      return true;
+    context_.set_location(node.source);
+    for (auto &checker : checkers_) {
+      checker->Enter(node);
+    }
+    return true;
+  }
+
+  template <typename T>
+  bool Pre(const parser::UnlabeledStatement<T> &node) {
+    if (context_.IsInModuleFile(node.source))
+      return true;
+    context_.set_location(node.source);
+    for (auto &checker : checkers_) {
+      checker->Enter(node);
+    }
+    return true;
+  }
+
+  template <typename T>
+  void Post(const parser::Statement<T> &node) {
+    if (context_.IsInModuleFile(node.source))
+      return;
+    for (auto &checker : checkers_) {
+      checker->Leave(node);
+    }
+    context_.set_location(std::nullopt);
+  }
+
+  template <typename T>
+  void Post(const parser::UnlabeledStatement<T> &node) {
+    if (context_.IsInModuleFile(node.source))
+      return;
+    for (auto &checker : checkers_) {
+      checker->Leave(node);
+    }
+    context_.set_location(std::nullopt);
+  }
+
+  bool Walk(const parser::Program &program) {
+    parser::Walk(program, *this);
+    return !context_.AnyFatalError();
+  }
+
+public:
+  semantics::SemanticsContext &context_;
+  std::vector<std::unique_ptr<FlangTidyCheck>> checkers_;
+};
+
+} // namespace Fortran::tidy
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_MULTIPLEXVISITOR_H
diff --git a/flang/tools/flang-tidy/tool/FlangTidyMain.cpp b/flang/tools/flang-tidy/tool/FlangTidyMain.cpp
index 7492dfda36d8f..50229930a2600 100644
--- a/flang/tools/flang-tidy/tool/FlangTidyMain.cpp
+++ b/flang/tools/flang-tidy/tool/FlangTidyMain.cpp
@@ -6,8 +6,303 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "../FlangTidy.h"
+#include "../FlangTidyForceLinker.h"
+#include "../FlangTidyOptions.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/InitLLVM.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/raw_ostream.h"
+#include <cassert>
+#include <sstream>
+#include <vector>
+
+// Frontend driver
+#include "flang/Frontend/CompilerInstance.h"
+#include "flang/Frontend/CompilerInvocation.h"
+#include "flang/Frontend/TextDiagnosticBuffer.h"
+
 namespace Fortran::tidy {
 
-extern int flangTidyMain(int &argc, const char **argv) { return 0; }
+static llvm::cl::list<std::string>
+    SourcePaths(llvm::cl::Positional,
+                llvm::cl::desc("<source0> [... <sourceN>]"),
+                llvm::cl::OneOrMore, llvm::cl::value_desc("source files"),
+                llvm::cl::sub(llvm::cl::SubCommand::getAll()));
+
+static llvm::cl::opt<std::string>
+    CheckOption("checks",
+                llvm::cl::desc("Comma-separated list of checks to enable. "
+                               "Overrides configuration file settings."),
+                llvm::cl::init(""), llvm::cl::value_desc("check list"));
+
+static llvm::cl::opt<std::string> ConfigOption(
+    "config",
+    llvm::cl::desc(
+        "Specify configuration in YAML format: "
+        "-config=\"{Checks: '*', CognitiveComplexityThreshold: 30}\" "
+        "When empty, flang-tidy will look for .flang-tidy files."),
+    llvm::cl::init(""), llvm::cl::value_desc("yaml config"));
+
+static llvm::cl::opt<std::string> ConfigFile(
+    "config-file",
+    llvm::cl::desc("Specify the path of .flang-tidy or custom config file"),
+    llvm::cl::init(""), llvm::cl::value_desc("filename"));
+
+static llvm::cl::opt<bool>
+    DumpConfig("dump-config",
+               llvm::cl::desc("Dump configuration in YAML format to stdout"),
+               llvm::cl::init(false));
+
+static llvm::cl::list<std::string> ArgsBefore(
+    "extra-arg-before",
+    llvm::cl::desc(
+        "Additional argument to prepend to the compiler command line"),
+    llvm::cl::ZeroOrMore, llvm::cl::sub(llvm::cl::SubCommand::getAll()));
+
+static llvm::cl::list<std::string>
+    ArgsAfter("extra-arg",
+              llvm::cl::desc(
+                  "Additional argument to append to the compiler command line"),
+              llvm::cl::ZeroOrMore,
+              llvm::cl::sub(llvm::cl::SubCommand::getAll()));
+
+static std::string GetFlangToolCommand() {
+  static int Dummy;
+  std::string FlangExecutable =
+      llvm::sys::fs::getMainExecutable("flang", (void *)&Dummy);
+  llvm::SmallString<128> FlangToolPath;
+  FlangToolPath = llvm::sys::path::parent_path(FlangExecutable);
+  llvm::sys::path::append(FlangToolPath, "flang-tool");
+  return std::string(FlangToolPath);
+}
+
+static bool stripPositionalArgs(std::vector<const char *> Args,
+                                std::vector<std::string> &Result,
+                                std::string &ErrorMsg) {
+  auto flang = std::make_unique<Fortran::frontend::CompilerInstance>();
+
+  // Create diagnostics engine
+  flang->createDiagnostics();
+  if (!flang->hasDiagnostics()) {
+    llvm::errs() << "Failed to create diagnostics engine\n";
+    return false;
+  }
+
+  // Capture diagnostics
+  frontend::TextDiagnosticBuffer *diagsBuffer =
+      new frontend::TextDiagnosticBuffer;
+  llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID(
+      new clang::DiagnosticIDs());
+  clang::DiagnosticOptions diagOpts;
+  clang::DiagnosticsEngine diags(diagID, diagOpts, diagsBuffer);
+
+  // Insert Flang tool command
+  std::string Argv0 = GetFlangToolCommand();
+  Args.insert(Args.begin(), Argv0.c_str());
+
+  // Add a dummy file to ensure at least one compilation job
+  Args.push_back("placeholder.f90");
+
+  // Remove -c flags if present
+  Args.erase(std::remove_if(
+                 Args.begin(), Args.end(),
+                 [](const char *arg) { return llvm::StringRef(arg) == "-c"; }),
+             Args.end());
+
+  // Create compiler invocation
+  bool success = Fortran::frontend::CompilerInvocation::createFromArgs(
+      flang->getInvocation(), Args, diags, Argv0.c_str());
+
+  if (!success) {
+    ErrorMsg = "Failed to create compiler invocation\n";
+    // Flush diagnostic
+    diagsBuffer->flushDiagnostics(flang->getDiagnostics());
+    return false;
+  }
+
+  // Get the list of input files from Flang's frontend options
+  std::vector<std::string> inputs;
+  for (const auto &input : flang->getFrontendOpts().inputs) {
+    inputs.push_back(input.getFile().str());
+  }
+
+  if (inputs.empty()) {
+    ErrorMsg = "warning: no compile jobs found\n";
+    return false;
+  }
+
+  // Remove input files from Args
+  std::vector<const char *>::iterator End = llvm::remove_if(
+      Args, [&](llvm::StringRef S) { return llvm::is_contained(inputs, S); });
+
+  // Store the filtered arguments
+  Result = std::vector<std::string>(Args.begin(), End);
+  return true;
+}
+
+static std::vector<std::string>
+loadFromCommandLine(int &Argc, const char *const *Argv, std::string &ErrorMsg) {
+  ErrorMsg.clear();
+  if (Argc == 0)
+    return {};
+  const char *const *DoubleDash =
+      std::find(Argv, Argv + Argc, llvm::StringRef("--"));
+  if (DoubleDash == Argv + Argc)
+    return {};
+  std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc);
+  Argc = DoubleDash - Argv;
+
+  std::vector<std::string> StrippedArgs;
+  if (!stripPositionalArgs(CommandLine, StrippedArgs, ErrorMsg))
+    return {};
+  return StrippedArgs;
+}
+
+static std::unique_ptr<FlangTidyOptionsProvider>
+createOptionsProvider(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) {
+  FlangTidyGlobalOptions GlobalOptions;
+
+  FlangTidyOptions DefaultOptions = FlangTidyOptions::getDefaults();
+
+  FlangTidyOptions OverrideOptions;
+  if (!CheckOption.empty())
+    OverrideOptions.Checks =
+        CheckOption; // This completely overrides, not merges
+
+  auto LoadConfig =
+      [&](llvm::StringRef Configuration,
+          llvm::StringRef Source) -> std::unique_ptr<FlangTidyOptionsProvider> {
+    llvm::ErrorOr<FlangTidyOptions> ParsedConfig =
+        parseConfiguration(llvm::MemoryBufferRef(Configuration, Source));
+    if (ParsedConfig)
+      return std::make_unique<ConfigOptionsProvider>(
+          std::move(GlobalOptions),
+          FlangTidyOptions::getDefaults().merge(DefaultOptions, 0),
+          std::move(*ParsedConfig), std::move(OverrideOptions), std::move(FS));
+    llvm::errs() << "Error: invalid configuration specified.\n"
+                 << ParsedConfig.getError().message() << "\n";
+    return nullptr;
+  };
+
+  if (!ConfigFile.empty()) {
+    if (!ConfigOption.empty()) {
+      llvm::errs() << "Error: --config-file and --config are "
+                      "mutually exclusive. Specify only one.\n";
+      return nullptr;
+    }
+
+    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
+        llvm::MemoryBuffer::getFile(ConfigFile);
+    if (std::error_code EC = Text.getError()) {
+      llvm::errs() << "Error: can't read config-file '" << ConfigFile
+                   << "': " << EC.message() << "\n";
+      return nullptr;
+    }
+
+    return LoadConfig((*Text)->getBuffer(), ConfigFile);
+  }
+
+  if (!ConfigOption.empty())
+    return LoadConfig(ConfigOption, "<command-line-config>");
+
+  return std::make_unique<FileOptionsProvider>(
+      std::move(GlobalOptions), std::move(DefaultOptions),
+      std::move(OverrideOptions), std::move(FS));
+}
+
+extern int flangTidyMain(int &argc, const char **argv) {
+  llvm::InitLLVM X(argc, argv);
+
+  std::string ErrorMessage;
+  auto Compilations = loadFromCommandLine(argc, argv, ErrorMessage);
+
+  if (!ErrorMessage.empty()) {
+    llvm::outs() << ErrorMessage << "\n";
+    return 1;
+  }
+
+  llvm::cl::ParseCommandLineOptions(
+      argc, argv, "flang-tidy: A Fortran source analysis tool\n");
+
+  llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS =
+      llvm::vfs::getRealFileSystem();
+
+  auto OwningOptionsProvider = createOptionsProvider(BaseFS);
+  auto *OptionsProvider = OwningOptionsProvider.get();
+  if (!OptionsProvider)
+    return 1;
+
+  llvm::StringRef FileName = "dummy.f90";
+  if (!SourcePaths.empty())
+    FileName = SourcePaths[0];
+
+  FlangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
+
+  if (DumpConfig) {
+    llvm::outs() << configurationAsText(EffectiveOptions) << "\n";
+    return 0;
+  }
+
+  EffectiveOptions.sourcePaths.assign(SourcePaths.begin(), SourcePaths.end());
+  EffectiveOptions.argv0 = argv[0];
+
+  EffectiveOptions.parseChecksString();
+
+  for (const auto &sourcePath : EffectiveOptions.sourcePaths) {
+    if (!llvm::sys::fs::exists(sourcePath)) {
+      llvm::errs() << "Error: File not found: " << sourcePath << "\n";
+      return 1;
+    }
+  }
+
+  // Add extra args from command line (these override config file settings)
+  for (const auto &arg : ArgsBefore) {
+    std::istringstream stream(arg);
+    std::string subArg;
+    while (stream >> subArg) {
+      if (!EffectiveOptions.ExtraArgsBefore)
+        EffectiveOptions.ExtraArgsBefore = std::vector<std::string>();
+      EffectiveOptions.ExtraArgsBefore->push_back(subArg);
+    }
+  }
+
+  for (const auto &arg : ArgsAfter) {
+    std::istringstream stream(arg);
+    std::string subArg;
+    while (stream >> subArg) {
+      if (!EffectiveOptions.ExtraArgs)
+        EffectiveOptions.ExtraArgs = std::vector<std::string>();
+      EffectiveOptions.ExtraArgs->push_back(subArg);
+    }
+  }
+
+  // Add compilation args if present
+  if (!Compilations.empty()) {
+    assert(EffectiveOptions.sourcePaths.size() == 1);
+    if (!EffectiveOptions.ExtraArgs)
+      EffectiveOptions.ExtraArgs = std::vector<std::string>();
+    EffectiveOptions.ExtraArgs->insert(EffectiveOptions.ExtraArgs->end(),
+                                       Compilations.begin(),
+                                       Compilations.end());
+  }
+
+  // Remove anything starting with --driver-mode
+  if (EffectiveOptions.ExtraArgs) {
+    EffectiveOptions.ExtraArgs->erase(
+        std::remove_if(EffectiveOptions.ExtraArgs->begin(),
+                       EffectiveOptions.ExtraArgs->end(),
+                       [](std::string const &arg) {
+                         return llvm::StringRef(arg).starts_with(
+                             "--driver-mode");
+                       }),
+        EffectiveOptions.ExtraArgs->end());
+  }
+
+  return runFlangTidy(EffectiveOptions);
+}
 
 } // namespace Fortran::tidy
diff --git a/flang/tools/flang-tidy/utils/CollectActualArguments.h b/flang/tools/flang-tidy/utils/CollectActualArguments.h
new file mode 100644
index 0000000000000..f445ec59097ea
--- /dev/null
+++ b/flang/tools/flang-tidy/utils/CollectActualArguments.h
@@ -0,0 +1,45 @@
+//===--- CollectActualArguments.h - flang-tidy ------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef FORTRAN_TIDY_UTILS_COLLECT_ACTUAL_ARGUMENTS
+#define FORTRAN_TIDY_UTILS_COLLECT_ACTUAL_ARGUMENTS
+
+#include "flang/Evaluate/call.h"
+#include "flang/Evaluate/traverse.h"
+
+namespace Fortran::evaluate {
+using ActualArgumentRef = common::Reference<const ActualArgument>;
+
+inline bool operator<(ActualArgumentRef x, ActualArgumentRef y) {
+  return &*x < &*y;
+}
+
+using ActualArgumentSet = std::set<evaluate::ActualArgumentRef>;
+
+struct CollectActualArgumentsHelper
+    : public evaluate::SetTraverse<CollectActualArgumentsHelper,
+                                   ActualArgumentSet> {
+  using Base = SetTraverse<CollectActualArgumentsHelper, ActualArgumentSet>;
+  CollectActualArgumentsHelper() : Base{*this} {}
+  using Base::operator();
+  ActualArgumentSet operator()(const evaluate::ActualArgument &arg) const {
+    return Combine(ActualArgumentSet{arg},
+                   CollectActualArgumentsHelper{}(arg.UnwrapExpr()));
+  }
+};
+
+template <typename A>
+ActualArgumentSet CollectActualArguments(const A &x) {
+  return CollectActualArgumentsHelper{}(x);
+}
+
+template ActualArgumentSet CollectActualArguments(const semantics::SomeExpr &);
+
+} // namespace Fortran::evaluate
+
+#endif // FORTRAN_TIDY_UTILS_COLLECT_ACTUAL_ARGUMENTS
diff --git a/flang/tools/flang-tidy/utils/SymbolUtils.h b/flang/tools/flang-tidy/utils/SymbolUtils.h
new file mode 100644
index 0000000000000..588a91d0e992b
--- /dev/null
+++ b/flang/tools/flang-tidy/utils/SymbolUtils.h
@@ -0,0 +1,25 @@
+//===--- SymbolUtils.h - flang-tidy -----------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef FORTRAN_TIDY_UTILS_SYMBOL
+#define FORTRAN_TIDY_UTILS_SYMBOL
+
+#include "flang/Semantics/scope.h"
+#include "flang/Semantics/symbol.h"
+
+namespace Fortran::tidy::utils {
+
+inline bool IsFromModFileSafe(const semantics::Symbol &sym) {
+  return sym.test(semantics::Symbol::Flag::ModFile) ||
+         (!sym.owner().IsTopLevel() &&
+          (sym.owner().symbol() && IsFromModFileSafe(*sym.owner().symbol())));
+}
+
+} // namespace Fortran::tidy::utils
+
+#endif // FORTRAN_TIDY_UTILS_SYMBOL

>From 87e6d9015258971f2a307840067713b5bb1026db Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 11:30:09 +0200
Subject: [PATCH 04/31] [flang-tidy] add test infra

---
 flang/tools/CMakeLists.txt                    |   4 +
 flang/tools/test/CMakeLists.txt               |  39 ++++
 .../tools/test/flang-tidy/check_flang_tidy.py | 200 ++++++++++++++++++
 flang/tools/test/lit.cfg.py                   |  54 +++++
 flang/tools/test/lit.site.cfg.py.in           |  24 +++
 5 files changed, 321 insertions(+)
 create mode 100644 flang/tools/test/CMakeLists.txt
 create mode 100644 flang/tools/test/flang-tidy/check_flang_tidy.py
 create mode 100644 flang/tools/test/lit.cfg.py
 create mode 100644 flang/tools/test/lit.site.cfg.py.in

diff --git a/flang/tools/CMakeLists.txt b/flang/tools/CMakeLists.txt
index 644fa7fe9c715..5524c1ef365a1 100644
--- a/flang/tools/CMakeLists.txt
+++ b/flang/tools/CMakeLists.txt
@@ -14,3 +14,7 @@ add_subdirectory(f18-parse-demo)
 add_subdirectory(fir-opt)
 add_subdirectory(fir-lsp-server)
 add_subdirectory(flang-tidy)
+
+if(FLANG_INCLUDE_TESTS)
+  add_subdirectory(test)
+endif()
\ No newline at end of file
diff --git a/flang/tools/test/CMakeLists.txt b/flang/tools/test/CMakeLists.txt
new file mode 100644
index 0000000000000..47cc32561d26b
--- /dev/null
+++ b/flang/tools/test/CMakeLists.txt
@@ -0,0 +1,39 @@
+set(FLANG_TOOLS_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/..")
+set(FLANG_TOOLS_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/..")
+
+llvm_canonicalize_cmake_booleans(
+  FLANG_PLUGIN_SUPPORT
+  LLVM_INSTALL_TOOLCHAIN_ONLY
+)
+
+configure_lit_site_cfg(
+  ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.py.in
+  ${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg.py
+  MAIN_CONFIG
+  ${CMAKE_CURRENT_SOURCE_DIR}/lit.cfg.py
+)
+
+set(FLANG_TOOLS_TEST_DEPS
+  # Individual tools we test.
+  flang-tidy
+  module_files
+)
+
+# Add lit test dependencies.
+set(LLVM_UTILS_DEPS
+  FileCheck count not
+)
+foreach(dep ${LLVM_UTILS_DEPS})
+  if(TARGET ${dep})
+    list(APPEND FLANG_TOOLS_TEST_DEPS ${dep})
+  endif()
+endforeach()
+
+add_lit_testsuite(check-flang-tools "Running flang-tools/test"
+   ${CMAKE_CURRENT_BINARY_DIR}
+   DEPENDS ${FLANG_TOOLS_TEST_DEPS}
+)
+
+add_lit_testsuites(FLANG-EXTRA ${CMAKE_CURRENT_SOURCE_DIR}
+  DEPENDS ${FLANG_TOOLS_TEST_DEPS}
+)
diff --git a/flang/tools/test/flang-tidy/check_flang_tidy.py b/flang/tools/test/flang-tidy/check_flang_tidy.py
new file mode 100644
index 0000000000000..5557038c83b8f
--- /dev/null
+++ b/flang/tools/test/flang-tidy/check_flang_tidy.py
@@ -0,0 +1,200 @@
+#!/usr/bin/env python3
+#
+# ===- check_flang_tidy.py - FlangTidy Test Helper ------------*- python -*--===#
+#
+# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+# See https://llvm.org/LICENSE.txt for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+#
+# ===------------------------------------------------------------------------===#
+
+"""
+FlangTidy Test Helper
+=====================
+
+This script helps run flang-tidy checks with llvm-lit. By default, it runs flang-tidy
+without applying fixes and uses FileCheck to verify warnings.
+"""
+
+import argparse
+import os
+import pathlib
+import re
+import subprocess
+import sys
+
+
+def write_file(file_name, text):
+    with open(file_name, "w", encoding="utf-8") as f:
+        f.write(text)
+        f.truncate()
+
+
+def try_run(args, raise_error=True):
+    try:
+        process_output = subprocess.check_output(args, stderr=subprocess.STDOUT).decode(
+            errors="ignore"
+        )
+    except subprocess.CalledProcessError as e:
+        process_output = e.output.decode(errors="ignore")
+        print("%s failed:\n%s" % (" ".join(args), process_output))
+        if raise_error:
+            raise
+    return process_output
+
+
+class MessagePrefix:
+    def __init__(self, label):
+        self.has_message = False
+        self.prefixes = []
+        self.label = label
+
+    def check(self, file_check_suffix, input_text):
+        self.prefix = self.label + file_check_suffix
+        self.has_message = self.prefix in input_text
+        if self.has_message:
+            self.prefixes.append(self.prefix)
+        return self.has_message
+
+
+class CheckRunner:
+    def __init__(self, args, extra_args):
+        self.resource_dir = args.resource_dir
+        self.input_file_name = args.input_file_name
+        self.check_name = args.check_name
+        self.temp_file_name = args.temp_file_name
+        self.expect_flang_tidy_error = args.expect_flang_tidy_error
+        self.std = args.std
+        self.check_suffix = args.check_suffix
+        self.input_text = ""
+        self.has_check_messages = False
+        self.expect_no_diagnosis = False
+        self.messages = MessagePrefix("CHECK-MESSAGES")
+
+        file_name_with_extension = self.input_file_name
+        _, extension = os.path.splitext(file_name_with_extension)
+        if extension not in [".f", ".f90", ".f95"]:
+            extension = ".f90"
+        self.temp_file_name = self.temp_file_name + extension
+
+        self.extra_args = extra_args
+        self.flang_extra_args = []
+
+        if "--" in extra_args:
+            i = self.extra_args.index("--")
+            self.flang_extra_args = self.extra_args[i + 1 :]
+            self.extra_args = self.extra_args[:i]
+
+    def read_input(self):
+        with open(self.input_file_name, "r", encoding="utf-8") as input_file:
+            self.input_text = input_file.read()
+
+    def get_prefixes(self):
+        for suffix in self.check_suffix:
+            if suffix and not re.match("^[A-Z0-9\\-]+$", suffix):
+                sys.exit(
+                    'Only A..Z, 0..9 and "-" are allowed in check suffixes list,'
+                    + ' but "%s" was given' % suffix
+                )
+
+            file_check_suffix = ("-" + suffix) if suffix else ""
+
+            has_check_message = self.messages.check(file_check_suffix, self.input_text)
+            self.has_check_messages = self.has_check_messages or has_check_message
+
+            if not has_check_message:
+                self.expect_no_diagnosis = True
+
+        if self.expect_no_diagnosis and self.has_check_messages:
+            sys.exit(
+                "%s not found in the input" % self.messages.prefix
+            )
+        assert self.has_check_messages or self.expect_no_diagnosis
+
+    def prepare_test_inputs(self):
+        cleaned_test = re.sub("// *CHECK-[A-Z0-9\\-]*:[^\r\n]*", "//", self.input_text)
+        write_file(self.temp_file_name, cleaned_test)
+
+    def run_flang_tidy(self):
+        args = (
+            [
+                "flang-tidy",
+                self.temp_file_name,
+            ]
+            + ["--checks=" + self.check_name]
+            + self.extra_args
+            #+ ["--"]
+            #+ self.flang_extra_args
+        )
+        if self.expect_flang_tidy_error:
+            args.insert(0, "not")
+        print("Running " + repr(args) + "...")
+        flang_tidy_output = try_run(args)
+        print("------------------------ flang-tidy output -----------------------")
+        print(
+            flang_tidy_output.encode(sys.stdout.encoding, errors="replace").decode(
+                sys.stdout.encoding
+            )
+        )
+        print("------------------------------------------------------------------")
+        return flang_tidy_output
+
+    def check_messages(self, flang_tidy_output):
+        if self.has_check_messages:
+            messages_file = self.temp_file_name + ".msg"
+            write_file(messages_file, flang_tidy_output)
+            try_run(
+                [
+                    "FileCheck",
+                    "-input-file=" + messages_file,
+                    self.input_file_name,
+                    "-check-prefixes=" + ",".join(self.messages.prefixes),
+                    "-implicit-check-not={{warning|error}}:",
+                ]
+            )
+
+    def run(self):
+        self.read_input()
+        self.get_prefixes()
+        self.prepare_test_inputs()
+        flang_tidy_output = self.run_flang_tidy()
+        if self.expect_no_diagnosis:
+            if flang_tidy_output != "":
+                sys.exit("No diagnostics were expected, but found the ones above")
+        else:
+            self.check_messages(flang_tidy_output)
+
+
+def parse_arguments():
+    parser = argparse.ArgumentParser(
+        prog=pathlib.Path(__file__).stem,
+        description=__doc__,
+        formatter_class=argparse.RawDescriptionHelpFormatter,
+    )
+    parser.add_argument("-expect-flang-tidy-error", action="store_true")
+    parser.add_argument("-resource-dir")
+    parser.add_argument("input_file_name")
+    parser.add_argument("check_name")
+    parser.add_argument("temp_file_name")
+    parser.add_argument(
+        "-check-suffix",
+        "-check-suffixes",
+        default=[""],
+        type=lambda x: x.split(","),
+        help="comma-separated list of FileCheck suffixes",
+    )
+    parser.add_argument(
+        "-std",
+        default="f2003",
+        help="Fortran standard to pass to flang.",
+    )
+    return parser.parse_known_args()
+
+
+def main():
+    args, extra_args = parse_arguments()
+    CheckRunner(args, extra_args).run()
+
+
+if __name__ == "__main__":
+    main()
\ No newline at end of file
diff --git a/flang/tools/test/lit.cfg.py b/flang/tools/test/lit.cfg.py
new file mode 100644
index 0000000000000..01b737179d594
--- /dev/null
+++ b/flang/tools/test/lit.cfg.py
@@ -0,0 +1,54 @@
+# -*- Python -*-
+
+import os
+import shlex
+
+import lit.formats
+
+from lit.llvm import llvm_config
+
+# Configuration file for the 'lit' test runner.
+
+# name: The name of this test suite.
+config.name = "Flang Tools"
+
+# testFormat: The test format to use to interpret tests.
+config.test_format = lit.formats.ShTest(not llvm_config.use_lit_shell)
+
+# suffixes: A list of file extensions to treat as test files.
+config.suffixes = [
+    ".f",
+    ".f90",
+    ".f95",
+    ".f03",
+    ".f08",
+    ".mod",
+    ".test"
+]
+
+# Exclude 'Inputs' directories as they are for test dependencies.
+config.excludes = ["Inputs"]
+
+# test_source_root: The root path where tests are located.
+config.test_source_root = os.path.dirname(__file__)
+
+# test_exec_root: The root path where tests should be run.
+config.test_exec_root = os.path.join(config.flang_tools_binary_dir, "test")
+
+# Tools need the same environment setup as clang (we don't need clang itself).
+llvm_config.use_clang(required=False)
+
+python_exec = shlex.quote(config.python_executable)
+check_flang_tidy = os.path.join(
+    config.test_source_root, "flang-tidy", "check_flang_tidy.py"
+)
+config.substitutions.append(
+    ("%check_flang_tidy", "%s %s" % (python_exec, check_flang_tidy))
+)
+
+# Plugins (loadable modules)
+if config.has_plugins and config.llvm_plugin_ext:
+    config.available_features.add("plugins")
+
+# Disable default configuration files to avoid interference with test runs.
+config.environment["FLANG_NO_DEFAULT_CONFIG"] = "1"
\ No newline at end of file
diff --git a/flang/tools/test/lit.site.cfg.py.in b/flang/tools/test/lit.site.cfg.py.in
new file mode 100644
index 0000000000000..0f6c901adcce0
--- /dev/null
+++ b/flang/tools/test/lit.site.cfg.py.in
@@ -0,0 +1,24 @@
+ at LIT_SITE_CFG_IN_HEADER@
+
+import sys
+
+config.llvm_plugin_ext = "@LLVM_PLUGIN_EXT@"
+config.lit_tools_dir = "@LLVM_LIT_TOOLS_DIR@"
+config.flang_tools_binary_dir = "@FLANG_TOOLS_BINARY_DIR@"
+config.llvm_shlib_dir = "@SHLIBDIR@"
+config.python_executable = "@Python3_EXECUTABLE@"
+config.target_triple = "@LLVM_TARGET_TRIPLE@"
+config.host_triple = "@LLVM_HOST_TRIPLE@"
+config.has_plugins = @FLANG_PLUGIN_SUPPORT@
+
+# Support substitution of the tools and libs dirs with user parameters. This is
+# used when we can't determine the tool dir at configuration time.
+config.llvm_tools_dir = lit_config.substitute("@LLVM_TOOLS_DIR@")
+config.llvm_libs_dir = lit_config.substitute("@LLVM_LIBS_DIR@")
+config.flang_tools_dir = lit_config.substitute("@CURRENT_TOOLS_DIR@")
+
+import lit.llvm
+lit.llvm.initialize(lit_config, config)
+
+# Let the main config do the real work.
+lit_config.load_config(config, "@FLANG_TOOLS_SOURCE_DIR@/test/lit.cfg.py")
\ No newline at end of file

>From 50a0f81dec5a995e5cf82380d12607841bce3d8f Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 11:33:50 +0200
Subject: [PATCH 05/31] [flang-tidy] add bugprone module

---
 flang/tools/flang-tidy/CMakeLists.txt         |  3 ++
 flang/tools/flang-tidy/FlangTidyForceLinker.h |  5 +++
 .../bugprone/BugproneTidyModule.cpp           | 32 +++++++++++++++++++
 .../tools/flang-tidy/bugprone/CMakeLists.txt  | 17 ++++++++++
 4 files changed, 57 insertions(+)
 create mode 100644 flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/CMakeLists.txt

diff --git a/flang/tools/flang-tidy/CMakeLists.txt b/flang/tools/flang-tidy/CMakeLists.txt
index 4e485cd25c46e..2c18eb741e22e 100644
--- a/flang/tools/flang-tidy/CMakeLists.txt
+++ b/flang/tools/flang-tidy/CMakeLists.txt
@@ -20,7 +20,10 @@ target_link_libraries(flangTidy
   flangFrontendTool
   )
 
+add_subdirectory(bugprone)
+
 set(ALL_FLANG_TIDY_CHECKS
+  flangTidyBugproneModule
   )
 
 set(ALL_FLANG_TIDY_CHECKS ${ALL_FLANG_TIDY_CHECKS} PARENT_SCOPE)
diff --git a/flang/tools/flang-tidy/FlangTidyForceLinker.h b/flang/tools/flang-tidy/FlangTidyForceLinker.h
index 3e9467013ea1c..b612329037f89 100644
--- a/flang/tools/flang-tidy/FlangTidyForceLinker.h
+++ b/flang/tools/flang-tidy/FlangTidyForceLinker.h
@@ -13,6 +13,11 @@
 
 namespace Fortran::tidy {
 
+// This anchor is used to force the linker to link the BugproneModule.
+extern volatile int BugproneModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED BugproneModuleAnchorDestination =
+    BugproneModuleAnchorSource;
+
 } // namespace Fortran::tidy
 
 #endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYFORCELINKER_H
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
new file mode 100644
index 0000000000000..9db2db341fdd6
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -0,0 +1,32 @@
+//===--- BugproneTidyModule.cpp - flang-tidy ------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "../FlangTidyModule.h"
+#include "../FlangTidyModuleRegistry.h"
+
+namespace Fortran::tidy {
+namespace bugprone {
+
+class BugproneModule : public FlangTidyModule {
+public:
+  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {}
+};
+
+} // namespace bugprone
+
+// Register the BugproneTidyModule using this statically initialized variable.
+static FlangTidyModuleRegistry::Add<bugprone::BugproneModule>
+    X("bugprone-module", "Adds checks for bugprone code constructs.");
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the BugproneModule.
+
+// NOLINTNEXTLINE
+volatile int BugproneModuleAnchorSource = 0;
+
+} // namespace Fortran::tidy
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
new file mode 100644
index 0000000000000..e248b365cccfb
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -0,0 +1,17 @@
+add_flang_library(flangTidyBugproneModule STATIC
+  BugproneTidyModule.cpp
+
+  LINK_LIBS
+  FortranSupport
+  FortranParser
+  FortranEvaluate
+  FortranSemantics
+  LLVMSupport
+  flangTidy
+
+  LINK_COMPONENTS
+  Support
+  FrontendOpenMP
+  FrontendOpenACC
+  TargetParser
+  )

>From d2b5e75e27996b5f0816204d0af4a02e04257e8e Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 11:39:27 +0200
Subject: [PATCH 06/31] [flang-tidy] add modernize module

---
 flang/tools/flang-tidy/CMakeLists.txt         |  2 ++
 flang/tools/flang-tidy/FlangTidyForceLinker.h |  5 +++
 .../tools/flang-tidy/modernize/CMakeLists.txt | 18 +++++++++++
 .../modernize/ModernizeTidyModule.cpp         | 32 +++++++++++++++++++
 4 files changed, 57 insertions(+)
 create mode 100644 flang/tools/flang-tidy/modernize/CMakeLists.txt
 create mode 100644 flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp

diff --git a/flang/tools/flang-tidy/CMakeLists.txt b/flang/tools/flang-tidy/CMakeLists.txt
index 2c18eb741e22e..5af3bf4fe1d17 100644
--- a/flang/tools/flang-tidy/CMakeLists.txt
+++ b/flang/tools/flang-tidy/CMakeLists.txt
@@ -21,9 +21,11 @@ target_link_libraries(flangTidy
   )
 
 add_subdirectory(bugprone)
+add_subdirectory(modernize)
 
 set(ALL_FLANG_TIDY_CHECKS
   flangTidyBugproneModule
+  flangTidyModernizeModule
   )
 
 set(ALL_FLANG_TIDY_CHECKS ${ALL_FLANG_TIDY_CHECKS} PARENT_SCOPE)
diff --git a/flang/tools/flang-tidy/FlangTidyForceLinker.h b/flang/tools/flang-tidy/FlangTidyForceLinker.h
index b612329037f89..18194dd57f727 100644
--- a/flang/tools/flang-tidy/FlangTidyForceLinker.h
+++ b/flang/tools/flang-tidy/FlangTidyForceLinker.h
@@ -18,6 +18,11 @@ extern volatile int BugproneModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED BugproneModuleAnchorDestination =
     BugproneModuleAnchorSource;
 
+// This anchor is used to force the linker to link the ModernizeModule.
+extern volatile int ModernizeModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED ModernizeModuleAnchorDestination =
+    ModernizeModuleAnchorSource;
+
 } // namespace Fortran::tidy
 
 #endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYFORCELINKER_H
diff --git a/flang/tools/flang-tidy/modernize/CMakeLists.txt b/flang/tools/flang-tidy/modernize/CMakeLists.txt
new file mode 100644
index 0000000000000..bbb3098f76d9b
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/CMakeLists.txt
@@ -0,0 +1,18 @@
+add_flang_library(flangTidyModernizeModule STATIC
+  ModernizeTidyModule.cpp
+
+  LINK_LIBS
+  FortranSupport
+  FortranParser
+  FortranEvaluate
+  FortranSemantics
+  LLVMSupport
+  flangTidy
+
+  LINK_COMPONENTS
+  Support
+  FrontendOpenMP
+  FrontendOpenACC
+  TargetParser
+  )
+
diff --git a/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
new file mode 100644
index 0000000000000..f2717adac43ed
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
@@ -0,0 +1,32 @@
+//===--- ModernizeTidyModule.cpp - flang-tidy -----------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "../FlangTidyModule.h"
+#include "../FlangTidyModuleRegistry.h"
+
+namespace Fortran::tidy {
+namespace modernize {
+
+class ModernizeModule : public FlangTidyModule {
+public:
+  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {}
+};
+
+} // namespace modernize
+
+// Register the BugproneTidyModule using this statically initialized variable.
+static FlangTidyModuleRegistry::Add<modernize::ModernizeModule>
+    X("modernize-module", "Adds checks to enforce modern code style.");
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the ModernizeModule.
+
+// NOLINTNEXTLINE
+volatile int ModernizeModuleAnchorSource = 0;
+
+} // namespace Fortran::tidy

>From 590611f5f4081db63c30b748a02ad84e512478e3 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 11:46:32 +0200
Subject: [PATCH 07/31] [flang-tidy] add openmp module

---
 flang/tools/flang-tidy/CMakeLists.txt         |  2 ++
 flang/tools/flang-tidy/FlangTidyForceLinker.h |  5 +++
 flang/tools/flang-tidy/openmp/CMakeLists.txt  | 17 ++++++++++
 .../flang-tidy/openmp/OpenMPTidyModule.cpp    | 32 +++++++++++++++++++
 4 files changed, 56 insertions(+)
 create mode 100644 flang/tools/flang-tidy/openmp/CMakeLists.txt
 create mode 100644 flang/tools/flang-tidy/openmp/OpenMPTidyModule.cpp

diff --git a/flang/tools/flang-tidy/CMakeLists.txt b/flang/tools/flang-tidy/CMakeLists.txt
index 5af3bf4fe1d17..78d0564f411a7 100644
--- a/flang/tools/flang-tidy/CMakeLists.txt
+++ b/flang/tools/flang-tidy/CMakeLists.txt
@@ -22,10 +22,12 @@ target_link_libraries(flangTidy
 
 add_subdirectory(bugprone)
 add_subdirectory(modernize)
+add_subdirectory(openmp)
 
 set(ALL_FLANG_TIDY_CHECKS
   flangTidyBugproneModule
   flangTidyModernizeModule
+  flangTidyOpenMPModule
   )
 
 set(ALL_FLANG_TIDY_CHECKS ${ALL_FLANG_TIDY_CHECKS} PARENT_SCOPE)
diff --git a/flang/tools/flang-tidy/FlangTidyForceLinker.h b/flang/tools/flang-tidy/FlangTidyForceLinker.h
index 18194dd57f727..74a0f2c6f68b1 100644
--- a/flang/tools/flang-tidy/FlangTidyForceLinker.h
+++ b/flang/tools/flang-tidy/FlangTidyForceLinker.h
@@ -23,6 +23,11 @@ extern volatile int ModernizeModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED ModernizeModuleAnchorDestination =
     ModernizeModuleAnchorSource;
 
+// This anchor is used to force the linker to link the OpenMPModule.
+extern volatile int OpenMPModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED OpenMPModuleAnchorDestination =
+    OpenMPModuleAnchorSource;
+
 } // namespace Fortran::tidy
 
 #endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYFORCELINKER_H
diff --git a/flang/tools/flang-tidy/openmp/CMakeLists.txt b/flang/tools/flang-tidy/openmp/CMakeLists.txt
new file mode 100644
index 0000000000000..69e07c16a3c88
--- /dev/null
+++ b/flang/tools/flang-tidy/openmp/CMakeLists.txt
@@ -0,0 +1,17 @@
+add_flang_library(flangTidyOpenMPModule STATIC
+  OpenMPTidyModule.cpp
+
+  LINK_LIBS
+  FortranSupport
+  FortranParser
+  FortranEvaluate
+  FortranSemantics
+  LLVMSupport
+  flangTidy
+
+  LINK_COMPONENTS
+  Support
+  FrontendOpenMP
+  FrontendOpenACC
+  TargetParser
+  )
diff --git a/flang/tools/flang-tidy/openmp/OpenMPTidyModule.cpp b/flang/tools/flang-tidy/openmp/OpenMPTidyModule.cpp
new file mode 100644
index 0000000000000..456bb3dbc6fbf
--- /dev/null
+++ b/flang/tools/flang-tidy/openmp/OpenMPTidyModule.cpp
@@ -0,0 +1,32 @@
+//===--- OpenMPTidyModule.cpp - flang-tidy --------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "../FlangTidyModule.h"
+#include "../FlangTidyModuleRegistry.h"
+
+namespace Fortran::tidy {
+namespace openmp {
+
+class OpenMPModule : public FlangTidyModule {
+public:
+  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {}
+};
+
+} // namespace openmp
+
+// Register the OpenMPTidyModule using this statically initialized variable.
+static FlangTidyModuleRegistry::Add<openmp::OpenMPModule>
+    X("openmp-module", "Adds checks for OpenMP parallelization.");
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the OpenMPTidyModule.
+
+// NOLINTNEXTLINE
+volatile int OpenMPModuleAnchorSource = 0;
+
+} // namespace Fortran::tidy

>From 503dac0e103699b8006261d6cb1a221867ea9400 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 11:50:27 +0200
Subject: [PATCH 08/31] [flang-tidy] add performance module

---
 flang/tools/flang-tidy/CMakeLists.txt         |  2 ++
 flang/tools/flang-tidy/FlangTidyForceLinker.h |  5 +++
 .../flang-tidy/performance/CMakeLists.txt     | 17 ++++++++++
 .../performance/PerformanceTidyModule.cpp     | 32 +++++++++++++++++++
 4 files changed, 56 insertions(+)
 create mode 100644 flang/tools/flang-tidy/performance/CMakeLists.txt
 create mode 100644 flang/tools/flang-tidy/performance/PerformanceTidyModule.cpp

diff --git a/flang/tools/flang-tidy/CMakeLists.txt b/flang/tools/flang-tidy/CMakeLists.txt
index 78d0564f411a7..8bb639403e14f 100644
--- a/flang/tools/flang-tidy/CMakeLists.txt
+++ b/flang/tools/flang-tidy/CMakeLists.txt
@@ -23,11 +23,13 @@ target_link_libraries(flangTidy
 add_subdirectory(bugprone)
 add_subdirectory(modernize)
 add_subdirectory(openmp)
+add_subdirectory(performance)
 
 set(ALL_FLANG_TIDY_CHECKS
   flangTidyBugproneModule
   flangTidyModernizeModule
   flangTidyOpenMPModule
+  flangTidyPerformanceModule
   )
 
 set(ALL_FLANG_TIDY_CHECKS ${ALL_FLANG_TIDY_CHECKS} PARENT_SCOPE)
diff --git a/flang/tools/flang-tidy/FlangTidyForceLinker.h b/flang/tools/flang-tidy/FlangTidyForceLinker.h
index 74a0f2c6f68b1..4d90045d69471 100644
--- a/flang/tools/flang-tidy/FlangTidyForceLinker.h
+++ b/flang/tools/flang-tidy/FlangTidyForceLinker.h
@@ -28,6 +28,11 @@ extern volatile int OpenMPModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED OpenMPModuleAnchorDestination =
     OpenMPModuleAnchorSource;
 
+// This anchor is used to force the linker to link the PerformanceModule.
+extern volatile int PerformanceModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED PerformanceModuleAnchorDestination =
+    PerformanceModuleAnchorSource;
+
 } // namespace Fortran::tidy
 
 #endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYFORCELINKER_H
diff --git a/flang/tools/flang-tidy/performance/CMakeLists.txt b/flang/tools/flang-tidy/performance/CMakeLists.txt
new file mode 100644
index 0000000000000..0a2690d24ea3a
--- /dev/null
+++ b/flang/tools/flang-tidy/performance/CMakeLists.txt
@@ -0,0 +1,17 @@
+add_flang_library(flangTidyPerformanceModule STATIC
+  PerformanceTidyModule.cpp
+
+  LINK_LIBS
+  FortranSupport
+  FortranParser
+  FortranEvaluate
+  FortranSemantics
+  LLVMSupport
+  flangTidy
+
+  LINK_COMPONENTS
+  Support
+  FrontendOpenMP
+  FrontendOpenACC
+  TargetParser
+  )
diff --git a/flang/tools/flang-tidy/performance/PerformanceTidyModule.cpp b/flang/tools/flang-tidy/performance/PerformanceTidyModule.cpp
new file mode 100644
index 0000000000000..70eda2ecf838e
--- /dev/null
+++ b/flang/tools/flang-tidy/performance/PerformanceTidyModule.cpp
@@ -0,0 +1,32 @@
+//===--- PerformanceTidyModule.cpp - flang-tidy ---------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "../FlangTidyModule.h"
+#include "../FlangTidyModuleRegistry.h"
+
+namespace Fortran::tidy {
+namespace performance {
+
+class PerformanceTidyModule : public FlangTidyModule {
+public:
+  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {}
+};
+
+} // namespace performance
+
+// Register the PerformanceTidyModule using this statically initialized
+// variable.
+static FlangTidyModuleRegistry::Add<performance::PerformanceTidyModule>
+    X("performance-module", "Performance Tidy Module");
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the PerformanceModule.
+// NOLINTNEXTLINE
+volatile int PerformanceModuleAnchorSource = 0;
+
+} // namespace Fortran::tidy

>From 02bc28e15d1b104e4d777e8abc21a39af48b773e Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 11:53:57 +0200
Subject: [PATCH 09/31] [flang-tidy] add readability module

---
 flang/tools/flang-tidy/CMakeLists.txt         |  2 ++
 flang/tools/flang-tidy/FlangTidyForceLinker.h |  5 +++
 .../flang-tidy/readability/CMakeLists.txt     | 17 ++++++++++
 .../readability/ReadabilityTidyModule.cpp     | 33 +++++++++++++++++++
 4 files changed, 57 insertions(+)
 create mode 100644 flang/tools/flang-tidy/readability/CMakeLists.txt
 create mode 100644 flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp

diff --git a/flang/tools/flang-tidy/CMakeLists.txt b/flang/tools/flang-tidy/CMakeLists.txt
index 8bb639403e14f..080d43033b1f3 100644
--- a/flang/tools/flang-tidy/CMakeLists.txt
+++ b/flang/tools/flang-tidy/CMakeLists.txt
@@ -24,12 +24,14 @@ add_subdirectory(bugprone)
 add_subdirectory(modernize)
 add_subdirectory(openmp)
 add_subdirectory(performance)
+add_subdirectory(readability)
 
 set(ALL_FLANG_TIDY_CHECKS
   flangTidyBugproneModule
   flangTidyModernizeModule
   flangTidyOpenMPModule
   flangTidyPerformanceModule
+  flangTidyReadabilityModule
   )
 
 set(ALL_FLANG_TIDY_CHECKS ${ALL_FLANG_TIDY_CHECKS} PARENT_SCOPE)
diff --git a/flang/tools/flang-tidy/FlangTidyForceLinker.h b/flang/tools/flang-tidy/FlangTidyForceLinker.h
index 4d90045d69471..59c6754d6afcf 100644
--- a/flang/tools/flang-tidy/FlangTidyForceLinker.h
+++ b/flang/tools/flang-tidy/FlangTidyForceLinker.h
@@ -33,6 +33,11 @@ extern volatile int PerformanceModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED PerformanceModuleAnchorDestination =
     PerformanceModuleAnchorSource;
 
+// This anchor is used to force the linker to link the ReadabilityModule.
+extern volatile int ReadabilityModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination =
+    ReadabilityModuleAnchorSource;
+
 } // namespace Fortran::tidy
 
 #endif // LLVM_FLANG_TOOLS_FLANG_TIDY_FLANGTIDYFORCELINKER_H
diff --git a/flang/tools/flang-tidy/readability/CMakeLists.txt b/flang/tools/flang-tidy/readability/CMakeLists.txt
new file mode 100644
index 0000000000000..6f8e5df4127f2
--- /dev/null
+++ b/flang/tools/flang-tidy/readability/CMakeLists.txt
@@ -0,0 +1,17 @@
+add_flang_library(flangTidyReadabilityModule STATIC
+  ReadabilityTidyModule.cpp
+
+  LINK_LIBS
+  FortranSupport
+  FortranParser
+  FortranEvaluate
+  FortranSemantics
+  LLVMSupport
+  flangTidy
+
+  LINK_COMPONENTS
+  Support
+  FrontendOpenMP
+  FrontendOpenACC
+  TargetParser
+  )
diff --git a/flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp b/flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp
new file mode 100644
index 0000000000000..1f217dd5eea4f
--- /dev/null
+++ b/flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp
@@ -0,0 +1,33 @@
+//===--- ReadabilityTidyModule.cpp - flang-tidy ---------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "../FlangTidyModule.h"
+#include "../FlangTidyModuleRegistry.h"
+
+namespace Fortran::tidy {
+namespace readability {
+
+class ReadabilityTidyModule : public FlangTidyModule {
+public:
+  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {}
+};
+
+} // namespace readability
+
+// Register the ReadabilityTidyModule using this statically initialized
+// variable.
+static FlangTidyModuleRegistry::Add<readability::ReadabilityTidyModule>
+    X("readability-module", "Adds checks for readability.");
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the ReadabilityTidyModule.
+
+// NOLINTNEXTLINE
+volatile int ReadabilityModuleAnchorSource = 0;
+
+} // namespace Fortran::tidy

>From db0bee30d07ae720ec4b4cf5520ec84ff4bff373 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 12:03:10 +0200
Subject: [PATCH 10/31] [flang-tidy] add documentation skeleton

---
 flang/tools/CMakeLists.txt                  |    6 +
 flang/tools/docs/CMakeLists.txt             |  103 +
 flang/tools/docs/ReleaseNotes.rst           |   64 +
 flang/tools/docs/conf.py                    |  253 ++
 flang/tools/docs/doxygen-mainpage.dox       |    9 +
 flang/tools/docs/doxygen.cfg.in             | 2294 +++++++++++++++++++
 flang/tools/docs/flang-tidy/checks/list.rst |   17 +
 flang/tools/docs/flang-tidy/index.rst       |   79 +
 flang/tools/docs/index.rst                  |   43 +
 9 files changed, 2868 insertions(+)
 create mode 100644 flang/tools/docs/CMakeLists.txt
 create mode 100644 flang/tools/docs/ReleaseNotes.rst
 create mode 100644 flang/tools/docs/conf.py
 create mode 100644 flang/tools/docs/doxygen-mainpage.dox
 create mode 100644 flang/tools/docs/doxygen.cfg.in
 create mode 100644 flang/tools/docs/flang-tidy/checks/list.rst
 create mode 100644 flang/tools/docs/flang-tidy/index.rst
 create mode 100644 flang/tools/docs/index.rst

diff --git a/flang/tools/CMakeLists.txt b/flang/tools/CMakeLists.txt
index 5524c1ef365a1..0b5b545638926 100644
--- a/flang/tools/CMakeLists.txt
+++ b/flang/tools/CMakeLists.txt
@@ -17,4 +17,10 @@ add_subdirectory(flang-tidy)
 
 if(FLANG_INCLUDE_TESTS)
   add_subdirectory(test)
+endif()
+
+option(FLANG_TOOLS_INCLUDE_DOCS "Generate build targets for the Flang Tools docs."
+  ${LLVM_INCLUDE_DOCS})
+if( FLANG_TOOLS_INCLUDE_DOCS )
+  add_subdirectory(docs)
 endif()
\ No newline at end of file
diff --git a/flang/tools/docs/CMakeLists.txt b/flang/tools/docs/CMakeLists.txt
new file mode 100644
index 0000000000000..b56a24c4fa6ec
--- /dev/null
+++ b/flang/tools/docs/CMakeLists.txt
@@ -0,0 +1,103 @@
+if (DOXYGEN_FOUND)
+  if (LLVM_ENABLE_DOXYGEN)
+    set(abs_srcdir ${CMAKE_CURRENT_SOURCE_DIR})
+    set(abs_builddir ${CMAKE_CURRENT_BINARY_DIR})
+
+    if (HAVE_DOT)
+      set(DOT ${LLVM_PATH_DOT})
+    endif()
+
+    if (LLVM_DOXYGEN_EXTERNAL_SEARCH)
+      set(enable_searchengine "YES")
+      set(searchengine_url "${LLVM_DOXYGEN_SEARCHENGINE_URL}")
+      set(enable_server_based_search "YES")
+      set(enable_external_search "YES")
+      set(extra_search_mappings "${LLVM_DOXYGEN_SEARCH_MAPPINGS}")
+    else()
+      set(enable_searchengine "NO")
+      set(searchengine_url "")
+      set(enable_server_based_search "NO")
+      set(enable_external_search "NO")
+      set(extra_search_mappings "")
+    endif()
+
+    # If asked, configure doxygen for the creation of a Qt Compressed Help file.
+    if (LLVM_ENABLE_DOXYGEN_QT_HELP)
+      set(FLANG_TOOLS_DOXYGEN_QCH_FILENAME "org.llvm.flang.qch" CACHE STRING
+        "Filename of the Qt Compressed help file")
+      set(FLANG_TOOLS_DOXYGEN_QHP_NAMESPACE "org.llvm.flang" CACHE STRING
+        "Namespace under which the intermediate Qt Help Project file lives")
+      set(FLANG_TOOLS_DOXYGEN_QHP_CUST_FILTER_NAME "Flang ${FLANG_VERSION}" CACHE STRING
+        "See http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-filters")
+      set(FLANG_TOOLS_DOXYGEN_QHP_CUST_FILTER_ATTRS "Flang,${FLANG_VERSION}" CACHE STRING
+        "See http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes")
+      set(flang_tools_doxygen_generate_qhp "YES")
+      set(flang_tools_doxygen_qch_filename "${FLANG_DOXYGEN_QCH_FILENAME}")
+      set(flang_tools_doxygen_qhp_namespace "${FLANG_DOXYGEN_QHP_NAMESPACE}")
+      set(flang_tools_doxygen_qhelpgenerator_path "${LLVM_DOXYGEN_QHELPGENERATOR_PATH}")
+      set(flang_tools_doxygen_qhp_cust_filter_name "${FLANG_DOXYGEN_QHP_CUST_FILTER_NAME}")
+      set(flang_tools_doxygen_qhp_cust_filter_attrs "${FLANG_DOXYGEN_QHP_CUST_FILTER_ATTRS}")
+    else()
+      set(flang_tools_doxygen_generate_qhp "NO")
+      set(flang_tools_doxygen_qch_filename "")
+      set(flang_tools_doxygen_qhp_namespace "")
+      set(flang_tools_doxygen_qhelpgenerator_path "")
+      set(flang_tools_doxygen_qhp_cust_filter_name "")
+      set(flang_tools_doxygen_qhp_cust_filter_attrs "")
+    endif()
+
+    option(LLVM_DOXYGEN_SVG
+      "Use svg instead of png files for doxygen graphs." OFF)
+    if (LLVM_DOXYGEN_SVG)
+      set(DOT_IMAGE_FORMAT "svg")
+    else()
+      set(DOT_IMAGE_FORMAT "png")
+    endif()
+
+    configure_file(${CMAKE_CURRENT_SOURCE_DIR}/doxygen.cfg.in
+      ${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg @ONLY)
+
+    set(abs_top_srcdir)
+    set(abs_top_builddir)
+    set(DOT)
+    set(enable_searchengine)
+    set(searchengine_url)
+    set(enable_server_based_search)
+    set(enable_external_search)
+    set(extra_search_mappings)
+    set(flang_tools_doxygen_generate_qhp)
+    set(flang_tools_doxygen_qch_filename)
+    set(flang_tools_doxygen_qhp_namespace)
+    set(flang_tools_doxygen_qhelpgenerator_path)
+    set(flang_tools_doxygen_qhp_cust_filter_name)
+    set(flang_tools_doxygen_qhp_cust_filter_attrs)
+    set(DOT_IMAGE_FORMAT)
+
+    add_custom_target(doxygen-flang-tools
+      COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg
+      WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
+      COMMENT "Generating flang doxygen documentation." VERBATIM)
+    set_target_properties(doxygen-flang-tools PROPERTIES FOLDER "Flang Tools/Docs")
+
+    if (LLVM_BUILD_DOCS)
+      add_dependencies(doxygen doxygen-flang-tools)
+    endif()
+
+    if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
+      install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/doxygen/html
+        DESTINATION docs/html)
+    endif()
+  endif()
+endif()
+
+if (LLVM_ENABLE_SPHINX)
+  include(AddSphinxTarget)
+  if (SPHINX_FOUND)
+    if (${SPHINX_OUTPUT_HTML})
+      add_sphinx_target(html flang-tools)
+    endif()
+    if (${SPHINX_OUTPUT_MAN})
+      add_sphinx_target(man flang-tools)
+    endif()
+  endif()
+endif()
diff --git a/flang/tools/docs/ReleaseNotes.rst b/flang/tools/docs/ReleaseNotes.rst
new file mode 100644
index 0000000000000..a4a69412881ef
--- /dev/null
+++ b/flang/tools/docs/ReleaseNotes.rst
@@ -0,0 +1,64 @@
+====================================================
+Flang Tools |release| |ReleaseNotesTitle|
+====================================================
+
+.. contents::
+   :local:
+   :depth: 3
+
+Written by the `LLVM Team <https://llvm.org/>`_
+
+.. only:: PreRelease
+
+  .. warning::
+     These are in-progress notes for the upcoming Flang Tools |version| release.
+     Release notes for previous releases can be found on
+     `the Download Page <https://releases.llvm.org/download.html>`_.
+
+Introduction
+============
+
+This document contains the release notes for the Flang Tools, part of the Flang
+release |release|. Here we describe the status of the Flang Tools in some
+detail, including major improvements from the previous release and new feature
+work. All LLVM releases may be downloaded from the `LLVM releases web site
+<https://llvm.org/releases/>`_.
+
+For more information about Flang or LLVM, including information about
+the latest release, please see the `Flang Web Site <https://flang.llvm.org>`_ or
+the `LLVM Web Site <https://llvm.org>`_.
+
+Note that if you are reading this file from a Git checkout or the
+main Flang web page, this document applies to the *next* release, not
+the current one. To see the release notes for a specific release, please
+see the `releases page <https://llvm.org/releases/>`_.
+
+What's New in Flang Tools |release|?
+====================================
+
+Some of the major new features and improvements to Extra Flang Tools are listed
+here. Generic improvements to Extra Flang Tools as a whole or to its underlying
+infrastructure are described first, followed by tool-specific sections.
+
+Major New Features
+------------------
+
+Improvements to flang-tidy
+--------------------------
+
+- New tool :program:`flang-tidy`.
+
+New checks
+^^^^^^^^^^
+
+New check aliases
+^^^^^^^^^^^^^^^^^
+
+Changes in existing checks
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Removed checks
+^^^^^^^^^^^^^^
+
+Miscellaneous
+^^^^^^^^^^^^^
diff --git a/flang/tools/docs/conf.py b/flang/tools/docs/conf.py
new file mode 100644
index 0000000000000..d0554262d314e
--- /dev/null
+++ b/flang/tools/docs/conf.py
@@ -0,0 +1,253 @@
+# -*- coding: utf-8 -*-
+#
+# Flang Tools documentation build configuration file, created by
+# sphinx-quickstart on Wed Feb 13 10:00:18 2013.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys, os
+from datetime import date
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+# sys.path.insert(0, os.path.abspath('.'))
+
+# -- General configuration -----------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+# needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ["sphinx.ext.todo", "sphinx.ext.mathjax"]
+
+# Add any paths that contain templates here, relative to this directory.
+# templates_path = ["_templates"]
+
+# The suffix of source filenames.
+source_suffix = ".rst"
+
+# The encoding of source files.
+# source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = "index"
+
+# General information about the project.
+project = "Flang Tools"
+copyright = "2007-%d, The Flang Team" % date.today().year
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+# language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+# today = ''
+# Else, today_fmt is used as the format for a strftime call.
+# today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ["_build"]
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+# default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+# add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+# add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+# show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = "friendly"
+
+# A list of ignored prefixes for module index sorting.
+# modindex_common_prefix = []
+
+in_progress_title = "(In-Progress) " if tags.has("PreRelease") else ""
+
+rst_epilog = f"""
+.. |ReleaseNotesTitle| replace:: {in_progress_title} Release Notes
+"""
+
+# -- Options for HTML output ---------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages.  See the documentation for
+# a list of builtin themes.
+html_theme = "haiku"
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further.  For a list of options available for each theme, see the
+# documentation.
+# html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+# html_theme_path = []
+
+# The name for this set of Sphinx documents.  If None, it defaults to
+# "<project> v<release> documentation".
+# html_title = None
+
+# A shorter title for the navigation bar.  Default is the same as html_title.
+# html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+# html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+# html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+# html_static_path = ["_static"]
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+# html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+# html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+# html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+# html_additional_pages = {}
+
+# If false, no module index is generated.
+# html_domain_indices = True
+
+# If false, no index is generated.
+# html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+# html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+# html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+# html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+# html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it.  The value of this option must be the
+# base URL from which the finished HTML is served.
+# html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+# html_file_suffix = None
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = "FlangToolsdoc"
+
+
+# -- Options for LaTeX output --------------------------------------------------
+
+latex_elements = {
+    # The paper size ('letterpaper' or 'a4paper').
+    #'papersize': 'letterpaper',
+    # The font size ('10pt', '11pt' or '12pt').
+    #'pointsize': '10pt',
+    # Additional stuff for the LaTeX preamble.
+    #'preamble': '',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass [howto/manual]).
+latex_documents = [
+    (
+        "index",
+        "FlangTools.tex",
+        "Flang Tools Documentation",
+        "The Flang Team",
+        "manual",
+    ),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+# latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+# latex_use_parts = False
+
+# If true, show page references after internal links.
+# latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+# latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+# latex_appendices = []
+
+# If false, no module index is generated.
+# latex_domain_indices = True
+
+
+# -- Options for manual page output --------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+    (
+        "index",
+        "flangtools",
+        "Flang Tools Documentation",
+        ["The Flang Team"],
+        1,
+    )
+]
+
+# If true, show URL addresses after external links.
+# man_show_urls = False
+
+
+# -- Options for Texinfo output ------------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+#  dir menu entry, description, category)
+texinfo_documents = [
+    (
+        "index",
+        "FlangTools",
+        "Flang Tools Documentation",
+        "The Flang Team",
+        "FlangTools",
+        "One line description of project.",
+        "Miscellaneous",
+    ),
+]
+
+# Documents to append as an appendix to all manuals.
+# texinfo_appendices = []
+
+# If false, no module index is generated.
+# texinfo_domain_indices = True
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+# texinfo_show_urls = 'footnote'
diff --git a/flang/tools/docs/doxygen-mainpage.dox b/flang/tools/docs/doxygen-mainpage.dox
new file mode 100644
index 0000000000000..275e7ed4ae903
--- /dev/null
+++ b/flang/tools/docs/doxygen-mainpage.dox
@@ -0,0 +1,9 @@
+/// \mainpage flang-tools
+///
+/// \section main_intro Introduction
+/// Welcome to flang tools.
+///
+/// This documentation describes the **internal** software that makes
+/// up flang tools, not the **external** use of flang tools. For
+/// usage instructions, please see the programmer's guide or reference
+/// manual.
diff --git a/flang/tools/docs/doxygen.cfg.in b/flang/tools/docs/doxygen.cfg.in
new file mode 100644
index 0000000000000..b5e7542d732cd
--- /dev/null
+++ b/flang/tools/docs/doxygen.cfg.in
@@ -0,0 +1,2294 @@
+# Doxyfile 1.8.6
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project.
+#
+# All text after a double hash (##) is considered a comment and is placed in
+# front of the TAG it is preceding.
+#
+# All text after a single hash (#) is considered a comment and will be ignored.
+# The format is:
+# TAG = value [value, ...]
+# For lists, items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (\" \").
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all text
+# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
+# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
+# for the list of possible encodings.
+# The default value is: UTF-8.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
+# double-quotes, unless you are using Doxywizard) that should identify the
+# project for which the documentation is generated. This name is used in the
+# title of most generated pages and in a few other places.
+# The default value is: My Project.
+
+PROJECT_NAME           = flang-tools
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
+# could be handy for archiving the generated documentation or if some version
+# control system is used.
+
+PROJECT_NUMBER         = @PACKAGE_VERSION@
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer a
+# quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          =
+
+# With the PROJECT_LOGO tag one can specify a logo or icon that is included in
+# the documentation. The maximum height of the logo should not exceed 55 pixels
+# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo
+# to the output directory.
+
+PROJECT_LOGO           =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
+# into which the generated documentation will be written. If a relative path is
+# entered, it will be relative to the location where doxygen was started. If
+# left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       = @abs_builddir@/doxygen
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub-
+# directories (in 2 levels) under the output directory of each output format and
+# will distribute the generated files over these directories. Enabling this
+# option can be useful when feeding doxygen a huge amount of source files, where
+# putting all generated files in the same directory would otherwise causes
+# performance problems for the file system.
+# The default value is: NO.
+
+CREATE_SUBDIRS         = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
+# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
+# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
+# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
+# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
+# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
+# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
+# Ukrainian and Vietnamese.
+# The default value is: English.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member
+# descriptions after the members that are listed in the file and class
+# documentation (similar to Javadoc). Set to NO to disable this.
+# The default value is: YES.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief
+# description of a member or function before the detailed description
+#
+# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+# The default value is: YES.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator that is
+# used to form the text in various listings. Each string in this list, if found
+# as the leading text of the brief description, will be stripped from the text
+# and the result, after processing the whole list, is used as the annotated
+# text. Otherwise, the brief description is used as-is. If left blank, the
+# following values are used ($name is automatically replaced with the name of
+# the entity):The $name class, The $name widget, The $name file, is, provides,
+# specifies, contains, represents, a, an and the.
+
+ABBREVIATE_BRIEF       =
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# doxygen will generate a detailed section even if there is only a brief
+# description.
+# The default value is: NO.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+# The default value is: NO.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path
+# before files name in the file list and in the header files. If set to NO the
+# shortest path that makes the file name unique will be used
+# The default value is: YES.
+
+FULL_PATH_NAMES        = NO
+
+# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
+# Stripping is only done if one of the specified strings matches the left-hand
+# part of the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the path to
+# strip.
+#
+# Note that you can specify absolute paths here, but also relative paths, which
+# will be relative from the directory where doxygen is started.
+# This tag requires that the tag FULL_PATH_NAMES is set to YES.
+
+STRIP_FROM_PATH        = ../..
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
+# path mentioned in the documentation of a class, which tells the reader which
+# header file to include in order to use a class. If left blank only the name of
+# the header file containing the class definition is used. Otherwise one should
+# specify the list of include paths that are normally passed to the compiler
+# using the -I flag.
+
+STRIP_FROM_INC_PATH    =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
+# less readable) file names. This can be useful is your file systems doesn't
+# support long names like on DOS, Mac, or CD-ROM.
+# The default value is: NO.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
+# first line (until the first dot) of a Javadoc-style comment as the brief
+# description. If set to NO, the Javadoc-style will behave just like regular Qt-
+# style comments (thus requiring an explicit @brief command for a brief
+# description.)
+# The default value is: NO.
+
+JAVADOC_AUTOBRIEF      = YES
+
+# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
+# line (until the first dot) of a Qt-style comment as the brief description. If
+# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
+# requiring an explicit \brief command for a brief description.)
+# The default value is: NO.
+
+QT_AUTOBRIEF           = YES
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
+# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
+# a brief description. This used to be the default behavior. The new default is
+# to treat a multi-line C++ comment block as a detailed description. Set this
+# tag to YES if you prefer the old behavior instead.
+#
+# Note that setting this tag to YES also means that rational rose comments are
+# not recognized any more.
+# The default value is: NO.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
+# documentation from any documented member that it re-implements.
+# The default value is: YES.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a
+# new page for each member. If set to NO, the documentation of a member will be
+# part of the file/class/namespace that contains it.
+# The default value is: NO.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
+# uses this value to replace tabs by spaces in code fragments.
+# Minimum value: 1, maximum value: 16, default value: 4.
+
+TAB_SIZE               = 2
+
+# This tag can be used to specify a number of aliases that act as commands in
+# the documentation. An alias has the form:
+# name=value
+# For example adding
+# "sideeffect=@par Side Effects:\n"
+# will allow you to put the command \sideeffect (or @sideeffect) in the
+# documentation, which will result in a user-defined paragraph with heading
+# "Side Effects:". You can put \n's in the value part of an alias to insert
+# newlines.
+
+ALIASES                =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding "class=itcl::class"
+# will allow you to use the command class in the itcl::class meaning.
+
+TCL_SUBST              =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
+# only. Doxygen will then generate output that is more tailored for C. For
+# instance, some of the names that are used will be different. The list of all
+# members will be omitted, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_FOR_C  = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
+# Python sources only. Doxygen will then generate output that is more tailored
+# for that language. For instance, namespaces will be presented as packages,
+# qualified scopes will look different, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources. Doxygen will then generate output that is tailored for Fortran.
+# The default value is: NO.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for VHDL.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension, and
+# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
+# C#, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL. For instance to make
+# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C
+# (default is Fortran), use: inc=Fortran f=C.
+#
+# Note For files without extension you can use no_extension as a placeholder.
+#
+# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
+# the files are not read by doxygen.
+
+EXTENSION_MAPPING      =
+
+# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
+# according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you can
+# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
+# case of backward compatibilities issues.
+# The default value is: YES.
+
+MARKDOWN_SUPPORT       = YES
+
+# When enabled doxygen tries to link words that correspond to documented
+# classes, or namespaces to their corresponding documentation. Such a link can
+# be prevented in individual cases by by putting a % sign in front of the word
+# or globally by setting AUTOLINK_SUPPORT to NO.
+# The default value is: YES.
+
+AUTOLINK_SUPPORT       = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should set this
+# tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string);
+# versus func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+# The default value is: NO.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+# The default value is: NO.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
+# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
+# will parse them like normal C++ but will assume all classes use public instead
+# of private inheritance when no explicit protection keyword is present.
+# The default value is: NO.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate
+# getter and setter methods for a property. Setting this option to YES will make
+# doxygen to replace the get and set methods by a property in the documentation.
+# This will only work if the methods are indeed getting or setting a simple
+# type. If this is not the case, or you want to show the methods anyway, you
+# should set this option to NO.
+# The default value is: YES.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+# The default value is: NO.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# Set the SUBGROUPING tag to YES to allow class member groups of the same type
+# (for instance a group of public functions) to be put as a subgroup of that
+# type (e.g. under the Public Functions section). Set it to NO to prevent
+# subgrouping. Alternatively, this can be done per class using the
+# \nosubgrouping command.
+# The default value is: YES.
+
+SUBGROUPING            = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
+# are shown inside the group in which they are included (e.g. using \ingroup)
+# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
+# and RTF).
+#
+# Note that this feature does not work in combination with
+# SEPARATE_MEMBER_PAGES.
+# The default value is: NO.
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
+# with only public data fields or simple typedef fields will be shown inline in
+# the documentation of the scope in which they are defined (i.e. file,
+# namespace, or group documentation), provided this scope is documented. If set
+# to NO, structs, classes, and unions are shown on a separate page (for HTML and
+# Man pages) or section (for LaTeX and RTF).
+# The default value is: NO.
+
+INLINE_SIMPLE_STRUCTS  = NO
+
+# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
+# enum is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically be
+# useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+# The default value is: NO.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
+# cache is used to resolve symbols given their name and scope. Since this can be
+# an expensive process and often the same symbol appears multiple times in the
+# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
+# doxygen will become slower. If the cache is too large, memory is wasted. The
+# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
+# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
+# symbols. At the end of a run doxygen will report the cache usage and suggest
+# the optimal cache size from a speed point of view.
+# Minimum value: 0, maximum value: 9, default value: 0.
+
+LOOKUP_CACHE_SIZE      = 2
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available. Private
+# class members and static file members will be hidden unless the
+# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
+# Note: This will also disable the warnings about undocumented members that are
+# normally produced when WARNINGS is set to YES.
+# The default value is: NO.
+
+EXTRACT_ALL            = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will
+# be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PRIVATE        = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
+# scope will be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PACKAGE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file will be
+# included in the documentation.
+# The default value is: NO.
+
+EXTRACT_STATIC         = YES
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined
+# locally in source files will be included in the documentation. If set to NO
+# only classes defined in header files are included. Does not have any effect
+# for Java sources.
+# The default value is: YES.
+
+EXTRACT_LOCAL_CLASSES  = YES
+
+# This flag is only useful for Objective-C code. When set to YES local methods,
+# which are defined in the implementation section but not in the interface are
+# included in the documentation. If set to NO only methods in the interface are
+# included.
+# The default value is: NO.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base name of
+# the file that contains the anonymous namespace. By default anonymous namespace
+# are hidden.
+# The default value is: NO.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
+# undocumented members inside documented classes or files. If set to NO these
+# members will be included in the various overviews, but no documentation
+# section is generated. This option has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy. If set
+# to NO these classes will be included in the various overviews. This option has
+# no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
+# (class|struct|union) declarations. If set to NO these declarations will be
+# included in the documentation.
+# The default value is: NO.
+
+HIDE_FRIEND_COMPOUNDS  = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
+# documentation blocks found inside the body of a function. If set to NO these
+# blocks will be appended to the function's detailed documentation block.
+# The default value is: NO.
+
+HIDE_IN_BODY_DOCS      = NO
+
+# The INTERNAL_DOCS tag determines if documentation that is typed after a
+# \internal command is included. If the tag is set to NO then the documentation
+# will be excluded. Set it to YES to include the internal documentation.
+# The default value is: NO.
+
+INTERNAL_DOCS          = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
+# names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+# The default value is: system dependent.
+
+CASE_SENSE_NAMES       = YES
+
+# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
+# their full class and namespace scopes in the documentation. If set to YES the
+# scope will be hidden.
+# The default value is: NO.
+
+HIDE_SCOPE_NAMES       = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
+# the files that are included by a file in the documentation of that file.
+# The default value is: YES.
+
+SHOW_INCLUDE_FILES     = YES
+
+# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
+# grouped member an include statement to the documentation, telling the reader
+# which file to include in order to use the member.
+# The default value is: NO.
+
+SHOW_GROUPED_MEMB_INC  = NO
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
+# files with double quotes in the documentation rather than with sharp brackets.
+# The default value is: NO.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
+# documentation for inline members.
+# The default value is: YES.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
+# (detailed) documentation of file and class members alphabetically by member
+# name. If set to NO the members will appear in declaration order.
+# The default value is: YES.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
+# descriptions of file, namespace and class members alphabetically by member
+# name. If set to NO the members will appear in declaration order. Note that
+# this will also influence the order of the classes in the class list.
+# The default value is: NO.
+
+SORT_BRIEF_DOCS        = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
+# (brief and detailed) documentation of class members so that constructors and
+# destructors are listed first. If set to NO the constructors will appear in the
+# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
+# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
+# member documentation.
+# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
+# detailed member documentation.
+# The default value is: NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
+# of group names into alphabetical order. If set to NO the group names will
+# appear in their defined order.
+# The default value is: NO.
+
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
+# fully-qualified names, including namespaces. If set to NO, the class list will
+# be sorted only by class name, not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the alphabetical
+# list.
+# The default value is: NO.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
+# type resolution of all parameters of a function it will reject a match between
+# the prototype and the implementation of a member function even if there is
+# only one candidate or it is obvious which candidate to choose by doing a
+# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
+# accept a match between prototype and implementation in such cases.
+# The default value is: NO.
+
+STRICT_PROTO_MATCHING  = NO
+
+# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the
+# todo list. This list is created by putting \todo commands in the
+# documentation.
+# The default value is: YES.
+
+GENERATE_TODOLIST      = YES
+
+# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the
+# test list. This list is created by putting \test commands in the
+# documentation.
+# The default value is: YES.
+
+GENERATE_TESTLIST      = YES
+
+# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug
+# list. This list is created by putting \bug commands in the documentation.
+# The default value is: YES.
+
+GENERATE_BUGLIST       = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO)
+# the deprecated list. This list is created by putting \deprecated commands in
+# the documentation.
+# The default value is: YES.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional documentation
+# sections, marked by \if <section_label> ... \endif and \cond <section_label>
+# ... \endcond blocks.
+
+ENABLED_SECTIONS       =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
+# initial value of a variable or macro / define can have for it to appear in the
+# documentation. If the initializer consists of more lines than specified here
+# it will be hidden. Use a value of 0 to hide initializers completely. The
+# appearance of the value of individual variables and macros / defines can be
+# controlled using \showinitializer or \hideinitializer command in the
+# documentation regardless of this setting.
+# Minimum value: 0, maximum value: 10000, default value: 30.
+
+MAX_INITIALIZER_LINES  = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
+# the bottom of the documentation of classes and structs. If set to YES the list
+# will mention the files that were used to generate the documentation.
+# The default value is: YES.
+
+SHOW_USED_FILES        = YES
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
+# will remove the Files entry from the Quick Index and from the Folder Tree View
+# (if specified).
+# The default value is: YES.
+
+SHOW_FILES             = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
+# page. This will remove the Namespaces entry from the Quick Index and from the
+# Folder Tree View (if specified).
+# The default value is: YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command command input-file, where command is the value of the
+# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
+# by doxygen. Whatever the program writes to standard output is used as the file
+# version. For an example see the documentation.
+
+FILE_VERSION_FILTER    =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option. You can
+# optionally specify a file name after the option, if omitted DoxygenLayout.xml
+# will be used as the name of the layout file.
+#
+# Note that if you run doxygen from a directory containing a file called
+# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
+# tag is left empty.
+
+LAYOUT_FILE            =
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
+# the reference definitions. This must be a list of .bib files. The .bib
+# extension is automatically appended if omitted. This requires the bibtex tool
+# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
+# For LaTeX the style of the bibliography can be controlled using
+# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
+# search path. Do not use file names with spaces, bibtex cannot handle them. See
+# also \cite for info how to create references.
+
+CITE_BIB_FILES         =
+
+#---------------------------------------------------------------------------
+# Configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated to
+# standard output by doxygen. If QUIET is set to YES this implies that the
+# messages are off.
+# The default value is: NO.
+
+QUIET                  = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES
+# this implies that the warnings are on.
+#
+# Tip: Turn warnings on while writing the documentation.
+# The default value is: YES.
+
+WARNINGS               = NO
+
+# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate
+# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
+# will automatically be disabled.
+# The default value is: YES.
+
+WARN_IF_UNDOCUMENTED   = NO
+
+# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some parameters
+# in a documented function, or documenting parameters that don't exist or using
+# markup commands wrongly.
+# The default value is: YES.
+
+WARN_IF_DOC_ERROR      = YES
+
+# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
+# are documented, but have no documentation for their parameters or return
+# value. If set to NO doxygen will only warn about wrong or incomplete parameter
+# documentation, but not about the absence of documentation.
+# The default value is: NO.
+
+WARN_NO_PARAMDOC       = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that doxygen
+# can produce. The string should contain the $file, $line, and $text tags, which
+# will be replaced by the file and line number from which the warning originated
+# and the warning text. Optionally the format may contain $version, which will
+# be replaced by the version of the file (if it could be obtained via
+# FILE_VERSION_FILTER)
+# The default value is: $file:$line: $text.
+
+WARN_FORMAT            = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning and error
+# messages should be written. If left blank the output is written to standard
+# error (stderr).
+
+WARN_LOGFILE           =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag is used to specify the files and/or directories that contain
+# documented source files. You may enter file names like myfile.cpp or
+# directories like /usr/src/myproject. Separate the files or directories with
+# spaces.
+# Note: If this tag is empty the current directory is searched.
+
+INPUT                  =  \
+                          @abs_srcdir@/../flang-tidy \
+                          @abs_srcdir@/doxygen-mainpage.dox
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
+# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
+# documentation (see: http://www.gnu.org/software/libiconv) for the list of
+# possible encodings.
+# The default value is: UTF-8.
+
+INPUT_ENCODING         = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank the
+# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii,
+# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp,
+# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown,
+# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,
+# *.qsf, *.as and *.js.
+
+FILE_PATTERNS          =
+
+# The RECURSIVE tag can be used to specify whether or not subdirectories should
+# be searched for input files as well.
+# The default value is: NO.
+
+RECURSIVE              = YES
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+#
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE                =
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+# The default value is: NO.
+
+EXCLUDE_SYMLINKS       = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories.
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories use the pattern */test/*
+
+EXCLUDE_SYMBOLS        =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or directories
+# that contain example code fragments that are included (see the \include
+# command).
+
+EXAMPLE_PATH           =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank all
+# files are included.
+
+EXAMPLE_PATTERNS       =
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude commands
+# irrespective of the value of the RECURSIVE tag.
+# The default value is: NO.
+
+EXAMPLE_RECURSIVE      = YES
+
+# The IMAGE_PATH tag can be used to specify one or more files or directories
+# that contain images that are to be included in the documentation (see the
+# \image command).
+
+IMAGE_PATH             =
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command:
+#
+# <filter> <input-file>
+#
+# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
+# name of an input file. Doxygen will then use the output that the filter
+# program writes to standard output. If FILTER_PATTERNS is specified, this tag
+# will be ignored.
+#
+# Note that the filter must not add or remove lines; it is applied before the
+# code is scanned, but not when the output code is generated. If lines are added
+# or removed, the anchors will not be placed correctly.
+
+INPUT_FILTER           =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis. Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match. The filters are a list of the form: pattern=filter
+# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
+# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
+# patterns match the file name, INPUT_FILTER is applied.
+
+FILTER_PATTERNS        =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER ) will also be used to filter the input files that are used for
+# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
+# The default value is: NO.
+
+FILTER_SOURCE_FILES    = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
+# it is also possible to disable source filtering for a specific pattern using
+# *.ext= (so without naming a filter).
+# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
+
+FILTER_SOURCE_PATTERNS =
+
+# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
+# is part of the input, its contents will be placed on the main page
+# (index.html). This can be useful if you have a project on for instance GitHub
+# and want to reuse the introduction page also for the doxygen output.
+
+USE_MDFILE_AS_MAINPAGE =
+
+#---------------------------------------------------------------------------
+# Configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
+# generated. Documented entities will be cross-referenced with these sources.
+#
+# Note: To get rid of all source code in the generated output, make sure that
+# also VERBATIM_HEADERS is set to NO.
+# The default value is: NO.
+
+SOURCE_BROWSER         = YES
+
+# Setting the INLINE_SOURCES tag to YES will include the body of functions,
+# classes and enums directly into the documentation.
+# The default value is: NO.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
+# special comment blocks from generated source code fragments. Normal C, C++ and
+# Fortran comments will always remain visible.
+# The default value is: YES.
+
+STRIP_CODE_COMMENTS    = NO
+
+# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
+# function all documented functions referencing it will be listed.
+# The default value is: NO.
+
+REFERENCED_BY_RELATION = YES
+
+# If the REFERENCES_RELATION tag is set to YES then for each documented function
+# all documented entities called/used by that function will be listed.
+# The default value is: NO.
+
+REFERENCES_RELATION    = YES
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
+# to YES, then the hyperlinks from functions in REFERENCES_RELATION and
+# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
+# link to the documentation.
+# The default value is: YES.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
+# source code will show a tooltip with additional information such as prototype,
+# brief description and links to the definition and documentation. Since this
+# will make the HTML file larger and loading of large files a bit slower, you
+# can opt to disable this feature.
+# The default value is: YES.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+SOURCE_TOOLTIPS        = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code will
+# point to the HTML generated by the htags(1) tool instead of doxygen built-in
+# source browser. The htags tool is part of GNU's global source tagging system
+# (see http://www.gnu.org/software/global/global.html). You will need version
+# 4.8.6 or higher.
+#
+# To use it do the following:
+# - Install the latest version of global
+# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
+# - Make sure the INPUT points to the root of the source tree
+# - Run doxygen as normal
+#
+# Doxygen will invoke htags (and that will in turn invoke gtags), so these
+# tools must be available from the command line (i.e. in the search path).
+#
+# The result: instead of the source browser generated by doxygen, the links to
+# source code will now point to the output of htags.
+# The default value is: NO.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
+# verbatim copy of the header file for each class for which an include is
+# specified. Set to NO to disable this.
+# See also: Section \class.
+# The default value is: YES.
+
+VERBATIM_HEADERS       = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
+# compounds will be generated. Enable this if the project contains a lot of
+# classes, structs, unions or interfaces.
+# The default value is: YES.
+
+ALPHABETICAL_INDEX     = YES
+
+# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
+# which the alphabetical index list will be split.
+# Minimum value: 1, maximum value: 20, default value: 5.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+COLS_IN_ALPHA_INDEX    = 4
+
+# In case all classes in a project start with a common prefix, all classes will
+# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
+# can be used to specify a prefix (or a list of prefixes) that should be ignored
+# while generating the index headers.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+IGNORE_PREFIX          = flang::
+
+#---------------------------------------------------------------------------
+# Configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output
+# The default value is: YES.
+
+GENERATE_HTML          = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_OUTPUT            = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
+# generated HTML page (for example: .htm, .php, .asp).
+# The default value is: .html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
+# each generated HTML page. If the tag is left blank doxygen will generate a
+# standard header.
+#
+# To get valid HTML the header file that includes any scripts and style sheets
+# that doxygen needs, which is dependent on the configuration options used (e.g.
+# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
+# default header using
+# doxygen -w html new_header.html new_footer.html new_stylesheet.css
+# YourConfigFile
+# and then modify the file new_header.html. See also section "Doxygen usage"
+# for information on how to generate the default header that doxygen normally
+# uses.
+# Note: The header is subject to change so you typically have to regenerate the
+# default header when upgrading to a newer version of doxygen. For a description
+# of the possible markers and block names see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_HEADER            =
+
+# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
+# generated HTML page. If the tag is left blank doxygen will generate a standard
+# footer. See HTML_HEADER for more information on how to generate a default
+# footer and what special commands can be used inside the footer. See also
+# section "Doxygen usage" for information on how to generate the default footer
+# that doxygen normally uses.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FOOTER            =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
+# sheet that is used by each HTML page. It can be used to fine-tune the look of
+# the HTML output. If left blank doxygen will generate a default style sheet.
+# See also section "Doxygen usage" for information on how to generate the style
+# sheet that doxygen normally uses.
+# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
+# it is more robust and this tag (HTML_STYLESHEET) will in the future become
+# obsolete.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_STYLESHEET        =
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional user-
+# defined cascading style sheet that is included after the standard style sheets
+# created by doxygen. Using this option one can overrule certain style aspects.
+# This is preferred over using HTML_STYLESHEET since it does not replace the
+# standard style sheet and is therefor more robust against future updates.
+# Doxygen will copy the style sheet file to the output directory. For an example
+# see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_STYLESHEET  =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
+# files will be copied as-is; there are no commands or markers available.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_FILES       =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
+# will adjust the colors in the stylesheet and background images according to
+# this color. Hue is specified as an angle on a colorwheel, see
+# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
+# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
+# purple, and 360 is red again.
+# Minimum value: 0, maximum value: 359, default value: 220.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
+# in the HTML output. For a value of 0 the output will use grayscales only. A
+# value of 255 will produce the most vivid colors.
+# Minimum value: 0, maximum value: 255, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
+# luminance component of the colors in the HTML output. Values below 100
+# gradually make the output lighter, whereas values above 100 make the output
+# darker. The value divided by 100 is the actual gamma applied, so 80 represents
+# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
+# change the gamma.
+# Minimum value: 40, maximum value: 240, default value: 80.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting this
+# to NO can help when comparing the output of multiple runs.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_TIMESTAMP         = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
+# shown in the various tree structured indices initially; the user can expand
+# and collapse entries dynamically later on. Doxygen will expand the tree to
+# such a level that at most the specified number of entries are visible (unless
+# a fully collapsed tree already exceeds this amount). So setting the number of
+# entries 1 will produce a full collapsed tree by default. 0 is a special value
+# representing an infinite number of entries and will result in a full expanded
+# tree by default.
+# Minimum value: 0, maximum value: 9999, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files will be
+# generated that can be used as input for Apple's Xcode 3 integrated development
+# environment (see: http://developer.apple.com/tools/xcode/), introduced with
+# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
+# Makefile in the HTML output directory. Running make will produce the docset in
+# that directory and running make install will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
+# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_DOCSET        = NO
+
+# This tag determines the name of the docset feed. A documentation feed provides
+# an umbrella under which multiple documentation sets from a single provider
+# (such as a company or product suite) can be grouped.
+# The default value is: Doxygen generated docs.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# This tag specifies a string that should uniquely identify the documentation
+# set bundle. This should be a reverse domain-name style string, e.g.
+# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
+# string, e.g. com.mycompany.MyDocSet.documentation.
+# The default value is: org.doxygen.Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
+# The default value is: Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
+# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
+# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
+# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
+# Windows.
+#
+# The HTML Help Workshop contains a compiler that can convert all HTML output
+# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
+# files are now used as the Windows 98 help format, and will replace the old
+# Windows help format (.hlp) on all Windows platforms in the future. Compressed
+# HTML files also contain an index, a table of contents, and you can search for
+# words in the documentation. The HTML workshop also contains a viewer for
+# compressed HTML files.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_HTMLHELP      = NO
+
+# The CHM_FILE tag can be used to specify the file name of the resulting .chm
+# file. You can add a path in front of the file if the result should not be
+# written to the html output directory.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_FILE               =
+
+# The HHC_LOCATION tag can be used to specify the location (absolute path
+# including file name) of the HTML help compiler ( hhc.exe). If non-empty
+# doxygen will try to run the HTML help compiler on the generated index.hhp.
+# The file has to be specified with full path.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+HHC_LOCATION           =
+
+# The GENERATE_CHI flag controls if a separate .chi index file is generated (
+# YES) or that it should be included in the main .chm file ( NO).
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+GENERATE_CHI           = NO
+
+# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc)
+# and project file content.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_INDEX_ENCODING     =
+
+# The BINARY_TOC flag controls whether a binary table of contents is generated (
+# YES) or a normal table of contents ( NO) in the .chm file.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members to
+# the table of contents of the HTML help documentation and to the tree view.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+TOC_EXPAND             = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
+# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
+# (.qch) of the generated HTML documentation.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_QHP           = @flang_tools_doxygen_generate_qhp@
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
+# the file name of the resulting .qch file. The path specified is relative to
+# the HTML output folder.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QCH_FILE               = @flang_tools_doxygen_qch_filename@
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
+# Project output. For more information please see Qt Help Project / Namespace
+# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_NAMESPACE          = @flang_tools_doxygen_qhp_namespace@
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
+# Help Project output. For more information please see Qt Help Project / Virtual
+# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
+# folders).
+# The default value is: doc.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
+# filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_NAME   = @flang_tools_doxygen_qhp_cust_filter_name@
+
+# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_ATTRS  = @flang_tools_doxygen_qhp_cust_filter_attrs@
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's filter section matches. Qt Help Project / Filter Attributes (see:
+# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_SECT_FILTER_ATTRS  =
+
+# The QHG_LOCATION tag can be used to specify the location of Qt's
+# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
+# generated .qhp file.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHG_LOCATION           = @flang_tools_doxygen_qhelpgenerator_path@
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
+# generated, together with the HTML files, they form an Eclipse help plugin. To
+# install this plugin and make it available under the help contents menu in
+# Eclipse, the contents of the directory containing the HTML and XML files needs
+# to be copied into the plugins directory of eclipse. The name of the directory
+# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
+# After copying Eclipse needs to be restarted before the help appears.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the Eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have this
+# name. Each documentation set should have its own identifier.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# If you want full control over the layout of the generated HTML pages it might
+# be necessary to disable the index and replace it with your own. The
+# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
+# of each HTML page. A value of NO enables the index and the value YES disables
+# it. Since the tabs in the index contain the same information as the navigation
+# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+DISABLE_INDEX          = NO
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information. If the tag
+# value is set to YES, a side panel will be generated containing a tree-like
+# index structure (just like the one that is generated for HTML Help). For this
+# to work a browser that supports JavaScript, DHTML, CSS and frames is required
+# (i.e. any modern browser). Windows users are probably better off using the
+# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can
+# further fine-tune the look of the index. As an example, the default style
+# sheet generated by doxygen has an example that shows how to put an image at
+# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
+# the same information as the tab index, you could consider setting
+# DISABLE_INDEX to YES when enabling this option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_TREEVIEW      = NO
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
+# doxygen will group on one line in the generated HTML documentation.
+#
+# Note that a value of 0 will completely suppress the enum values from appearing
+# in the overview section.
+# Minimum value: 0, maximum value: 20, default value: 4.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
+# to set the initial width (in pixels) of the frame in which the tree is shown.
+# Minimum value: 0, maximum value: 1500, default value: 250.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+TREEVIEW_WIDTH         = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to
+# external symbols imported via tag files in a separate window.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of LaTeX formulas included as images in
+# the HTML documentation. When you change the font size after a successful
+# doxygen run you need to manually remove any form_*.png images from the HTML
+# output directory to force them to be regenerated.
+# Minimum value: 8, maximum value: 50, default value: 10.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_FONTSIZE       = 10
+
+# Use the FORMULA_TRANSPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are not
+# supported properly for IE 6.0, but are supported on all modern browsers.
+#
+# Note that when changing this option you need to delete any form_*.png files in
+# the HTML output directory before the changes have effect.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_TRANSPARENT    = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
+# http://www.mathjax.org) which uses client side Javascript for the rendering
+# instead of using prerendered bitmaps. Use this if you do not have LaTeX
+# installed or if you want to formulas look prettier in the HTML output. When
+# enabled you may also need to install MathJax separately and configure the path
+# to it using the MATHJAX_RELPATH option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+USE_MATHJAX            = NO
+
+# When MathJax is enabled you can set the default output format to be used for
+# the MathJax output. See the MathJax site (see:
+# http://docs.mathjax.org/en/latest/output.html) for more details.
+# Possible values are: HTML-CSS (which is slower, but has the best
+# compatibility), NativeMML (i.e. MathML) and SVG.
+# The default value is: HTML-CSS.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_FORMAT         = HTML-CSS
+
+# When MathJax is enabled you need to specify the location relative to the HTML
+# output directory using the MATHJAX_RELPATH option. The destination directory
+# should contain the MathJax.js script. For instance, if the mathjax directory
+# is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
+# Content Delivery Network so you can quickly see the result without installing
+# MathJax. However, it is strongly recommended to install a local copy of
+# MathJax from http://www.mathjax.org before deployment.
+# The default value is: http://cdn.mathjax.org/mathjax/latest.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
+# extension names that should be enabled during MathJax rendering. For example
+# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_EXTENSIONS     =
+
+# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
+# of code that will be used on startup of the MathJax code. See the MathJax site
+# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
+# example see the documentation.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_CODEFILE       =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
+# the HTML output. The underlying search engine uses javascript and DHTML and
+# should work on any modern browser. Note that when using HTML help
+# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
+# there is already a search function so this one should typically be disabled.
+# For large projects the javascript based search engine can be slow, then
+# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
+# search using the keyboard; to jump to the search box use <access key> + S
+# (what the <access key> is depends on the OS and browser, but it is typically
+# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
+# key> to jump into the search results window, the results can be navigated
+# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
+# the search. The filter options can be selected when the cursor is inside the
+# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
+# to select a filter and <Enter> or <escape> to activate or cancel the filter
+# option.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+SEARCHENGINE           = @enable_searchengine@
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a web server instead of a web client using Javascript. There
+# are two flavours of web server based searching depending on the
+# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for
+# searching and an index file used by the script. When EXTERNAL_SEARCH is
+# enabled the indexing and searching needs to be provided by external tools. See
+# the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SERVER_BASED_SEARCH    = @enable_server_based_search@
+
+# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
+# script for searching. Instead the search results are written to an XML file
+# which needs to be processed by an external indexer. Doxygen will invoke an
+# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
+# search results.
+#
+# Doxygen ships with an example indexer ( doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/).
+#
+# See the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH        = @enable_external_search@
+
+# The SEARCHENGINE_URL should point to a search engine hosted by a web server
+# which will return the search results when EXTERNAL_SEARCH is enabled.
+#
+# Doxygen ships with an example indexer ( doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/). See the section "External Indexing and
+# Searching" for details.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHENGINE_URL       = @searchengine_url@
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
+# search data is written to a file for indexing by an external tool. With the
+# SEARCHDATA_FILE tag the name of this file can be specified.
+# The default file is: searchdata.xml.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHDATA_FILE        = searchdata.xml
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
+# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
+# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
+# projects and redirect the results back to the right project.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH_ID     = flang-tools
+
+# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
+# projects other than the one defined by this configuration file, but that are
+# all added to the same external search index. Each project needs to have a
+# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
+# to a relative location where the documentation can be found. The format is:
+# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTRA_SEARCH_MAPPINGS  = @extra_search_mappings@
+
+#---------------------------------------------------------------------------
+# Configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES doxygen will generate LaTeX output.
+# The default value is: YES.
+
+GENERATE_LATEX         = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked.
+#
+# Note that when enabling USE_PDFLATEX this option is only used for generating
+# bitmaps for formulas in the HTML output, but not in the Makefile that is
+# written to the output directory.
+# The default file is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
+# index for LaTeX.
+# The default file is: makeindex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES doxygen generates more compact LaTeX
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used by the
+# printer.
+# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
+# 14 inches) and executive (7.25 x 10.5 inches).
+# The default value is: a4.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PAPER_TYPE             = a4
+
+# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
+# that should be included in the LaTeX output. To get the times font for
+# instance you can specify
+# EXTRA_PACKAGES=times
+# If left blank no extra packages will be included.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+EXTRA_PACKAGES         =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
+# generated LaTeX document. The header should contain everything until the first
+# chapter. If it is left blank doxygen will generate a standard header. See
+# section "Doxygen usage" for information on how to let doxygen write the
+# default header to a separate file.
+#
+# Note: Only use a user-defined header if you know what you are doing! The
+# following commands have a special meaning inside the header: $title,
+# $datetime, $date, $doxygenversion, $projectname, $projectnumber. Doxygen will
+# replace them by respectively the title of the page, the current date and time,
+# only the current date, the version number of doxygen, the project name (see
+# PROJECT_NAME), or the project number (see PROJECT_NUMBER).
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HEADER           =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
+# generated LaTeX document. The footer should contain everything after the last
+# chapter. If it is left blank doxygen will generate a standard footer.
+#
+# Note: Only use a user-defined footer if you know what you are doing!
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_FOOTER           =
+
+# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the LATEX_OUTPUT output
+# directory. Note that the files will be copied as-is; there are no commands or
+# markers available.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_FILES      =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
+# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
+# contain links (just like the HTML output) instead of page references. This
+# makes the output suitable for online browsing using a PDF viewer.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PDF_HYPERLINKS         = YES
+
+# If the LATEX_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
+# the PDF file directly from the LaTeX files. Set this option to YES to get a
+# higher quality PDF documentation.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
+# command to the generated LaTeX files. This will instruct LaTeX to keep running
+# if errors occur, instead of asking the user for help. This option is also used
+# when generating formulas in HTML.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BATCHMODE        = NO
+
+# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
+# index chapters (such as File Index, Compound Index, etc.) in the output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HIDE_INDICES     = NO
+
+# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
+# code with syntax highlighting in the LaTeX output.
+#
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_SOURCE_CODE      = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. See
+# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
+# The default value is: plain.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BIB_STYLE        = plain
+
+#---------------------------------------------------------------------------
+# Configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES doxygen will generate RTF output. The
+# RTF output is optimized for Word 97 and may not look too pretty with other RTF
+# readers/editors.
+# The default value is: NO.
+
+GENERATE_RTF           = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: rtf.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_OUTPUT             = rtf
+
+# If the COMPACT_RTF tag is set to YES doxygen generates more compact RTF
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+COMPACT_RTF            = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
+# contain hyperlink fields. The RTF file will contain links (just like the HTML
+# output) instead of page references. This makes the output suitable for online
+# browsing using Word or some other Word compatible readers that support those
+# fields.
+#
+# Note: WordPad (write) and others do not support links.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_HYPERLINKS         = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's config
+# file, i.e. a series of assignments. You only have to provide replacements,
+# missing definitions are set to their default value.
+#
+# See also section "Doxygen usage" for information on how to generate the
+# default style sheet that doxygen normally uses.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_STYLESHEET_FILE    =
+
+# Set optional variables used in the generation of an RTF document. Syntax is
+# similar to doxygen's config file. A template extensions file can be generated
+# using doxygen -e rtf extensionFile.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_EXTENSIONS_FILE    =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES doxygen will generate man pages for
+# classes and files.
+# The default value is: NO.
+
+GENERATE_MAN           = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it. A directory man3 will be created inside the directory specified by
+# MAN_OUTPUT.
+# The default directory is: man.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to the generated
+# man pages. In case the manual section does not start with a number, the number
+# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
+# optional.
+# The default value is: .3.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_EXTENSION          = .3
+
+# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
+# will generate one additional man file for each entity documented in the real
+# man page(s). These additional files only source the real man page, but without
+# them the man command would be unable to find the correct page.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_LINKS              = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES doxygen will generate an XML file that
+# captures the structure of the code including all documentation.
+# The default value is: NO.
+
+GENERATE_XML           = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: xml.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_OUTPUT             = xml
+
+# If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program
+# listings (including syntax highlighting and cross-referencing information) to
+# the XML output. Note that enabling this will significantly increase the size
+# of the XML output.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the DOCBOOK output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_DOCBOOK tag is set to YES doxygen will generate Docbook files
+# that can be used to generate PDF.
+# The default value is: NO.
+
+GENERATE_DOCBOOK       = NO
+
+# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
+# front of it.
+# The default directory is: docbook.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_OUTPUT         = docbook
+
+#---------------------------------------------------------------------------
+# Configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES doxygen will generate an AutoGen
+# Definitions (see http://autogen.sf.net) file that captures the structure of
+# the code including all documentation. Note that this feature is still
+# experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_AUTOGEN_DEF   = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES doxygen will generate a Perl module
+# file that captures the structure of the code including all documentation.
+#
+# Note that this feature is still experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_PERLMOD       = NO
+
+# If the PERLMOD_LATEX tag is set to YES doxygen will generate the necessary
+# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
+# output from the Perl module output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_LATEX          = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be nicely
+# formatted so it can be parsed by a human reader. This is useful if you want to
+# understand what is going on. On the other hand, if this tag is set to NO the
+# size of the Perl module output will be much smaller and Perl will parse it
+# just the same.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_PRETTY         = YES
+
+# The names of the make variables in the generated doxyrules.make file are
+# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
+# so different doxyrules.make files included by the same Makefile don't
+# overwrite each other's variables.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES doxygen will evaluate all
+# C-preprocessor directives found in the sources and include files.
+# The default value is: YES.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES doxygen will expand all macro names
+# in the source code. If set to NO only conditional compilation will be
+# performed. Macro expansion can be done in a controlled way by setting
+# EXPAND_ONLY_PREDEF to YES.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+MACRO_EXPANSION        = YES
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
+# the macro expansion is limited to the macros specified with the PREDEFINED and
+# EXPAND_AS_DEFINED tags.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_ONLY_PREDEF     = YES
+
+# If the SEARCH_INCLUDES tag is set to YES the includes files in the
+# INCLUDE_PATH will be searched if a #include is found.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by the
+# preprocessor.
+# This tag requires that the tag SEARCH_INCLUDES is set to YES.
+
+INCLUDE_PATH           = @abs_srcdir@/../../../include \
+                         @abs_srcdir@/../../../../../include
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will be
+# used.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+INCLUDE_FILE_PATTERNS  =
+
+# The PREDEFINED tag can be used to specify one or more macro names that are
+# defined before the preprocessor is started (similar to the -D option of e.g.
+# gcc). The argument of the tag is a list of macros of the form: name or
+# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
+# is assumed. To prevent a macro definition from being undefined via #undef or
+# recursively expanded use the := operator instead of the = operator.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+PREDEFINED             =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
+# tag can be used to specify a list of macro names that should be expanded. The
+# macro definition that is found in the sources will be used. Use the PREDEFINED
+# tag if you want to use a different macro definition that overrules the
+# definition found in the source code.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_AS_DEFINED      =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
+# remove all references to function-like macros that are alone on a line, have an
+# all uppercase name, and do not end with a semicolon. Such function macros are
+# typically used for boiler-plate code, and will confuse the parser if not
+# removed.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES tag can be used to specify one or more tag files. For each tag
+# file the location of the external documentation should be added. The format of
+# a tag file without this location is as follows:
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where loc1 and loc2 can be relative or absolute paths or URLs. See the
+# section "Linking to external documentation" for more information about the use
+# of tag files.
+# Note: Each tag file must have an unique name (where the name does NOT include
+# the path). If a tag file is not located in the directory in which doxygen is
+# run, you must also specify the path to the tagfile here.
+
+TAGFILES               =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
+# tag file that is based on the input files it reads. See section "Linking to
+# external documentation" for more information about the usage of tag files.
+
+GENERATE_TAGFILE       =
+
+# If the ALLEXTERNALS tag is set to YES all external class will be listed in the
+# class index. If set to NO only the inherited external classes will be listed.
+# The default value is: NO.
+
+ALLEXTERNALS           = YES
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed in
+# the modules index. If set to NO, only the current project's groups will be
+# listed.
+# The default value is: YES.
+
+EXTERNAL_GROUPS        = YES
+
+# If the EXTERNAL_PAGES tag is set to YES all external pages will be listed in
+# the related pages index. If set to NO, only the current project's pages will
+# be listed.
+# The default value is: YES.
+
+EXTERNAL_PAGES         = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of 'which perl').
+# The default file (with absolute path) is: /usr/bin/perl.
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES doxygen will generate a class diagram
+# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
+# NO turns the diagrams off. Note that this option also works with HAVE_DOT
+# disabled, but it is recommended to install and use dot, since it yields more
+# powerful graphs.
+# The default value is: YES.
+
+CLASS_DIAGRAMS         = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see:
+# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            =
+
+# You can include diagrams made with dia in doxygen documentation. Doxygen will
+# then run dia to produce the diagram and insert it in the documentation. The
+# DIA_PATH tag allows you to specify the directory where the dia binary resides.
+# If left empty dia is assumed to be found in the default search path.
+
+DIA_PATH               =
+
+# If set to YES, the inheritance and collaboration graphs will hide inheritance
+# and usage relations if the target is undocumented or is not a class.
+# The default value is: YES.
+
+HIDE_UNDOC_RELATIONS   = NO
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz (see:
+# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
+# Bell Labs. The other options in this section have no effect if this option is
+# set to NO
+# The default value is: NO.
+
+HAVE_DOT               = YES
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
+# to run in parallel. When set to 0 doxygen will base this on the number of
+# processors available in the system. You can set it explicitly to a value
+# larger than 0 to get control over the balance between CPU load and processing
+# speed.
+# Minimum value: 0, maximum value: 32, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_NUM_THREADS        = 0
+
+# When you want a differently looking font n the dot files that doxygen
+# generates you can specify the font name using DOT_FONTNAME. You need to make
+# sure dot is able to find the font, which can be done by putting it in a
+# standard location or by setting the DOTFONTPATH environment variable or by
+# setting DOT_FONTPATH to the directory containing the font.
+# The default value is: Helvetica.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
+# dot graphs.
+# Minimum value: 4, maximum value: 24, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the default font as specified with
+# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
+# the path where dot can find it using this tag.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTPATH           =
+
+# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
+# each documented class showing the direct and indirect inheritance relations.
+# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
+# graph for each documented class showing the direct and indirect implementation
+# dependencies (inheritance, containment, and class references variables) of the
+# class with other documented classes.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+COLLABORATION_GRAPH    = NO
+
+# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
+# groups, showing the direct groups dependencies.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LOOK               = NO
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
+# class node. If there are many fields or methods and many nodes the graph may
+# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
+# number of items for each type to make the size more manageable. Set this to 0
+# for no limit. Note that the threshold may be exceeded by 50% before the limit
+# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
+# but if the number exceeds 15, the total amount of fields shown is limited to
+# 10.
+# Minimum value: 0, maximum value: 100, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LIMIT_NUM_FIELDS   = 10
+
+# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
+# collaboration graphs will show the relations between templates and their
+# instances.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+TEMPLATE_RELATIONS     = YES
+
+# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
+# YES then doxygen will generate a graph for each documented file showing the
+# direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDE_GRAPH          = NO
+
+# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
+# set to YES then doxygen will generate a graph for each documented file showing
+# the direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDED_BY_GRAPH      = NO
+
+# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable call graphs for selected
+# functions only using the \callgraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable caller graphs for selected
+# functions only using the \callergraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
+# hierarchy of all classes instead of a textual one.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GRAPHICAL_HIERARCHY    = YES
+
+# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
+# dependencies a directory has on other directories in a graphical way. The
+# dependency relations are determined by the #include relations between the
+# files in the directories.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot.
+# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
+# to make the SVG files visible in IE 9+ (other browsers do not have this
+# requirement).
+# Possible values are: png, jpg, gif and svg.
+# The default value is: png.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_IMAGE_FORMAT       = @DOT_IMAGE_FORMAT@
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+#
+# Note that this requires a modern browser other than Internet Explorer. Tested
+# and working are Firefox, Chrome, Safari, and Opera.
+# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
+# the SVG files visible. Older versions of IE do not have SVG support.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INTERACTIVE_SVG        = NO
+
+# The DOT_PATH tag can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_PATH               = @DOT@
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the \dotfile
+# command).
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOTFILE_DIRS           =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the \mscfile
+# command).
+
+MSCFILE_DIRS           =
+
+# The DIAFILE_DIRS tag can be used to specify one or more directories that
+# contain dia files that are included in the documentation (see the \diafile
+# command).
+
+DIAFILE_DIRS           =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
+# that will be shown in the graph. If the number of nodes in a graph becomes
+# larger than this value, doxygen will truncate the graph, which is visualized
+# by representing a node as a red box. Note that doxygen if the number of direct
+# children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
+# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+# Minimum value: 0, maximum value: 10000, default value: 50.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
+# generated by dot. A depth value of 3 means that only nodes reachable from the
+# root by following a path via at most 3 edges will be shown. Nodes that lay
+# further from the root node will be omitted. Note that setting this option to 1
+# or 2 may greatly reduce the computation time needed for large code bases. Also
+# note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+# Minimum value: 0, maximum value: 1000, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+MAX_DOT_GRAPH_DEPTH    = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not seem
+# to support this out of the box.
+#
+# Warning: Depending on the platform used, enabling this option may lead to
+# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
+# read).
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_TRANSPARENT        = YES
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10) support
+# this, this feature is disabled by default.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_MULTI_TARGETS      = YES
+
+# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
+# explaining the meaning of the various boxes and arrows in the dot generated
+# graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES doxygen will remove the intermediate dot
+# files that are used to generate the various graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_CLEANUP            = YES
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
new file mode 100644
index 0000000000000..5190645af9f31
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -0,0 +1,17 @@
+.. title:: flang-tidy - Flang-Tidy Checks
+
+Flang-Tidy Checks
+=================
+
+.. toctree::
+   :glob:
+   :hidden:
+
+   bugprone/*
+   modernize/*
+   openmp/*
+   performance/*
+   readability/*
+
+.. csv-table::
+   :header: "Name", "Offers fixes"
diff --git a/flang/tools/docs/flang-tidy/index.rst b/flang/tools/docs/flang-tidy/index.rst
new file mode 100644
index 0000000000000..29145f4050f7d
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/index.rst
@@ -0,0 +1,79 @@
+==========
+Flang-Tidy
+==========
+
+.. contents::
+
+See also:
+
+.. toctree::
+   :maxdepth: 1
+
+   The list of flang-tidy checks <checks/list>
+
+:program:`flang-tidy` is a flang-based Fortran "linter" tool. Its purpose is to
+provide an extensible framework for diagnosing and fixing typical programming
+errors, like style violations, interface misuse, or bugs that can be deduced via
+static analysis. :program:`flang-tidy` is modular and provides a convenient
+interface for writing new checks.
+
+
+Using flang-tidy
+================
+
+:program:`flang-tidy` is a flang-based tool, and it's easier to work with if you
+set up a compile command database for your project. You can also specify
+compilation options on the command line after ``--``:
+
+.. code-block:: console
+
+  $ flang-tidy test.cpp -- -Imy_project/include -DMY_DEFINES ...
+
+:program:`flang-tidy` has its own checks. Each check has a name and the checks
+to run can be chosen using the ``-checks=`` option, which specifies a
+comma-separated list of positive and negative (prefixed with ``-``)
+globs. Positive globs add subsets of checks, and negative globs remove them. For
+example,
+
+.. code-block:: console
+
+  $ flang-tidy test.cpp -checks=-*,bugprone-*,-bugprone-arithmetic-*
+
+will disable all default checks (``-*``) and enable all ``bugprone-*``
+checks except for ``bugprone-arithmetic-*`` ones.
+
+The ``-list-checks`` option lists all the enabled checks. When used without
+``-checks=``, it shows checks enabled by default. Use ``-checks=*`` to see all
+available checks or with any other value of ``-checks=`` to see which checks are
+enabled by this value.
+
+There are currently the following groups of checks:
+
+====================== =========================================================
+Name prefix            Description
+====================== =========================================================
+``bugprone-``          Checks that target bug-prone code constructs.
+``modernize-``         Checks that advocate usage of modern language constructs.
+``openmp-``            Checks that target OpenMP constructs.
+``performance-``       Checks that target performance-related issues.
+``readability-``       Checks that target readability-related issues.
+====================== =========================================================
+
+Flang diagnostics are not treated by :program:`flang-tidy` and can currently not
+be filtered out using the ``-checks=`` option.
+
+
+Suppressing Undesired Diagnostics
+=================================
+
+:program:`flang-tidy` diagnostics are intended to call out code that does not
+adhere to a coding standard, or is otherwise problematic in some way. However,
+if the code is known to be correct, it may be useful to silence the warning.
+
+If a specific suppression mechanism is not available for a certain warning, or
+its use is not desired for some reason, :program:`flang-tidy` has a generic
+mechanism to suppress diagnostics using ``NOLINT``.
+
+The ``NOLINT`` comment instructs :program:`flang-tidy` to ignore warnings on the
+*same line* (it doesn't apply to a function, a block of code or any other
+language construct; it applies to the line of code it is on).
diff --git a/flang/tools/docs/index.rst b/flang/tools/docs/index.rst
new file mode 100644
index 0000000000000..300b0520fe274
--- /dev/null
+++ b/flang/tools/docs/index.rst
@@ -0,0 +1,43 @@
+.. title:: Welcome to Flang Tools's documentation!
+
+Introduction
+============
+Welcome to the flang-tools project which contains tools built using
+Flang's tooling APIs.
+
+.. toctree::
+   :maxdepth: 1
+
+   ReleaseNotes
+
+Contents
+========
+.. toctree::
+   :maxdepth: 2
+
+   flang-tidy/index
+
+
+Doxygen Documentation
+=====================
+The Doxygen documentation describes the **internal** software that makes up the
+tools of flang-tools, not the **external** use of these tools. The Doxygen
+documentation contains no instructions about how to use the tools, only the APIs
+that make up the software. For usage instructions, please see the user's guide
+or reference manual for each tool.
+
+* `Doxygen documentation`_
+
+.. _`Doxygen documentation`: doxygen/annotated.html
+
+.. note::
+    This documentation is generated directly from the source code with doxygen.
+    Since the tools of flang-tools are constantly under active
+    development, what you're about to read is out of date!
+
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`search`

>From 098be98c20d658234d20311a2cc62e807ffda1bf Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 12:58:02 +0200
Subject: [PATCH 11/31] [flang-tidy][bugprone] add arithmetic goto check

---
 .../checks/bugprone/arithmetic-goto.rst       | 19 ++++++++++++
 flang/tools/docs/flang-tidy/checks/list.rst   |  2 ++
 .../bugprone/ArithmeticGotoCheck.cpp          | 21 +++++++++++++
 .../flang-tidy/bugprone/ArithmeticGotoCheck.h | 30 +++++++++++++++++++
 .../bugprone/BugproneTidyModule.cpp           |  6 +++-
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |  1 +
 .../tools/test/flang-tidy/arithmetic-goto.f90 | 10 +++++++
 7 files changed, 88 insertions(+), 1 deletion(-)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/arithmetic-goto.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/ArithmeticGotoCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/ArithmeticGotoCheck.h
 create mode 100644 flang/tools/test/flang-tidy/arithmetic-goto.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/arithmetic-goto.rst b/flang/tools/docs/flang-tidy/checks/bugprone/arithmetic-goto.rst
new file mode 100644
index 0000000000000..eaf515d6dc531
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/arithmetic-goto.rst
@@ -0,0 +1,19 @@
+.. title:: flang-tidy - bugprone-arithmetic-goto
+
+bugprone-arithmetic-goto
+========================
+
+Warns about the use of computed GOTO statements, which are considered problematic for code maintainability and clarity. The arithmetic (computed) GOTO is an obsolescent feature in Fortran that allows for complex and hard-to-maintain transfer of control logic. Modern code should use more structured control statements instead.
+
+.. code-block:: fortran
+
+    program example
+      integer :: i = 2
+      go to (10, 20, 30), i  ! This will trigger a warning
+    10 print *, "Label 10"
+      stop
+    20 print *, "Label 20"
+      stop
+    30 print *, "Label 30"
+      stop
+    end program
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 5190645af9f31..e942c5021bc9c 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -15,3 +15,5 @@ Flang-Tidy Checks
 
 .. csv-table::
    :header: "Name", "Offers fixes"
+
+   :doc:`bugprone-arithmetic-goto <bugprone/arithmetic-goto>`,
diff --git a/flang/tools/flang-tidy/bugprone/ArithmeticGotoCheck.cpp b/flang/tools/flang-tidy/bugprone/ArithmeticGotoCheck.cpp
new file mode 100644
index 0000000000000..3b9436e423b04
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/ArithmeticGotoCheck.cpp
@@ -0,0 +1,21 @@
+//===--- ArithmeticGotoCheck.cpp - flang-tidy -----------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "ArithmeticGotoCheck.h"
+
+namespace Fortran::tidy::bugprone {
+
+using namespace parser::literals;
+void ArithmeticGotoCheck::Enter(const parser::ComputedGotoStmt &gotoStmt) {
+  if (context()->getSemanticsContext().location().has_value()) {
+    Say(context()->getSemanticsContext().location().value(),
+        "Arithmetic goto statements are not recommended"_warn_en_US);
+  }
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/ArithmeticGotoCheck.h b/flang/tools/flang-tidy/bugprone/ArithmeticGotoCheck.h
new file mode 100644
index 0000000000000..eff2296290cc6
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/ArithmeticGotoCheck.h
@@ -0,0 +1,30 @@
+//===--- ArithmeticGotoCheck.h - flang-tidy ---------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_ARITHMETICGOTOCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_ARITHMETICGOTOCHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check detects the use of arithmetic GOTO statements in Fortran code.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/bugprone-arithmetic-goto.html
+class ArithmeticGotoCheck : public FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~ArithmeticGotoCheck() = default;
+  void Enter(const parser::ComputedGotoStmt &) override;
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_ARITHMETICGOTOCHECK_H
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index 9db2db341fdd6..3e9a269f59096 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -8,13 +8,17 @@
 
 #include "../FlangTidyModule.h"
 #include "../FlangTidyModuleRegistry.h"
+#include "ArithmeticGotoCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
 
 class BugproneModule : public FlangTidyModule {
 public:
-  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {}
+  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {
+    CheckFactories.registerCheck<ArithmeticGotoCheck>(
+        "bugprone-arithmetic-goto");
+  }
 };
 
 } // namespace bugprone
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index e248b365cccfb..db7c3316e1519 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -1,4 +1,5 @@
 add_flang_library(flangTidyBugproneModule STATIC
+  ArithmeticGotoCheck.cpp
   BugproneTidyModule.cpp
 
   LINK_LIBS
diff --git a/flang/tools/test/flang-tidy/arithmetic-goto.f90 b/flang/tools/test/flang-tidy/arithmetic-goto.f90
new file mode 100644
index 0000000000000..9418973318aad
--- /dev/null
+++ b/flang/tools/test/flang-tidy/arithmetic-goto.f90
@@ -0,0 +1,10 @@
+! RUN: %check_flang_tidy %s bugprone-arithmetic-goto %t
+subroutine s(i)
+  integer, intent(in) :: i
+  goto (10, 20, 30), i
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Arithmetic goto statements are not recommended
+
+  10 continue
+  20 continue
+  30 continue
+end subroutine s

>From 1b7486f049e16a0ac193b65b1c1e0bf6f34b0986 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:01:36 +0200
Subject: [PATCH 12/31] [flang-tidy][bugprone] add arithmetic if check

---
 .../checks/bugprone/arithmetic-if.rst         | 19 ++++++++++++
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../bugprone/ArithmeticIfStmtCheck.cpp        | 21 +++++++++++++
 .../bugprone/ArithmeticIfStmtCheck.h          | 30 +++++++++++++++++++
 .../bugprone/BugproneTidyModule.cpp           |  3 ++
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |  1 +
 flang/tools/test/flang-tidy/arithmetic-if.f90 | 12 ++++++++
 7 files changed, 87 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/arithmetic-if.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/ArithmeticIfStmtCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/ArithmeticIfStmtCheck.h
 create mode 100644 flang/tools/test/flang-tidy/arithmetic-if.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/arithmetic-if.rst b/flang/tools/docs/flang-tidy/checks/bugprone/arithmetic-if.rst
new file mode 100644
index 0000000000000..ffa6c39646fdb
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/arithmetic-if.rst
@@ -0,0 +1,19 @@
+.. title:: flang-tidy - bugprone-arithmetic-if
+
+bugprone-arithmetic-if
+======================
+
+Detects the use of arithmetic IF statements, which are obsolescent in Fortran and should be replaced with more structured IF constructs for better readability and maintainability.
+
+.. code-block:: fortran
+
+    program example
+      real :: x = -1.0
+      if (x) 10, 20, 30  ! This will trigger a warning
+    10 print *, "X is negative"
+      stop
+    20 print *, "X is zero"
+      stop
+    30 print *, "X is positive"
+      stop
+    end program
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index e942c5021bc9c..395499eb445cf 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -17,3 +17,4 @@ Flang-Tidy Checks
    :header: "Name", "Offers fixes"
 
    :doc:`bugprone-arithmetic-goto <bugprone/arithmetic-goto>`,
+    :doc:`bugprone-arithmetic-if <bugprone/arithmetic-if>`,
diff --git a/flang/tools/flang-tidy/bugprone/ArithmeticIfStmtCheck.cpp b/flang/tools/flang-tidy/bugprone/ArithmeticIfStmtCheck.cpp
new file mode 100644
index 0000000000000..b9d876a796fdf
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/ArithmeticIfStmtCheck.cpp
@@ -0,0 +1,21 @@
+//===--- ArithmeticIfStmtCheck.cpp - flang-tidy ---------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "ArithmeticIfStmtCheck.h"
+
+namespace Fortran::tidy::bugprone {
+
+using namespace parser::literals;
+void ArithmeticIfStmtCheck::Enter(const parser::ArithmeticIfStmt &ifStmt) {
+  if (context()->getSemanticsContext().location().has_value()) {
+    Say(context()->getSemanticsContext().location().value(),
+        "Arithmetic if statements are not recommended"_warn_en_US);
+  }
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/ArithmeticIfStmtCheck.h b/flang/tools/flang-tidy/bugprone/ArithmeticIfStmtCheck.h
new file mode 100644
index 0000000000000..cb45a69520547
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/ArithmeticIfStmtCheck.h
@@ -0,0 +1,30 @@
+//===--- ArithmeticIfStmtCheck.h - flang-tidy -------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_ARITHMETICIFSTMTCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_ARITHMETICIFSTMTCHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check detects the use of arithmetic IF statements.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/arithmetic-if-statement.html
+class ArithmeticIfStmtCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~ArithmeticIfStmtCheck() = default;
+  void Enter(const parser::ArithmeticIfStmt &) override;
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_ARITHMETICIFSTMTCHECK_H
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index 3e9a269f59096..e1bc649b2f003 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -9,6 +9,7 @@
 #include "../FlangTidyModule.h"
 #include "../FlangTidyModuleRegistry.h"
 #include "ArithmeticGotoCheck.h"
+#include "ArithmeticIfStmtCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
@@ -18,6 +19,8 @@ class BugproneModule : public FlangTidyModule {
   void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {
     CheckFactories.registerCheck<ArithmeticGotoCheck>(
         "bugprone-arithmetic-goto");
+    CheckFactories.registerCheck<ArithmeticIfStmtCheck>(
+        "bugprone-arithmetic-if");
   }
 };
 
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index db7c3316e1519..db3ca7c45eb72 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -1,5 +1,6 @@
 add_flang_library(flangTidyBugproneModule STATIC
   ArithmeticGotoCheck.cpp
+  ArithmeticIfStmtCheck.cpp
   BugproneTidyModule.cpp
 
   LINK_LIBS
diff --git a/flang/tools/test/flang-tidy/arithmetic-if.f90 b/flang/tools/test/flang-tidy/arithmetic-if.f90
new file mode 100644
index 0000000000000..3160abe170a2a
--- /dev/null
+++ b/flang/tools/test/flang-tidy/arithmetic-if.f90
@@ -0,0 +1,12 @@
+! RUN: %check_flang_tidy %s bugprone-arithmetic-if %t
+subroutine s
+  real :: x = -1.0
+  if (x) 10, 20, 30
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Arithmetic if statements are not recommended
+10 print *, "X is negative"
+   stop
+20 print *, "X is zero"
+   stop
+30 print *, "X is positive"
+   stop
+end subroutine s

>From 81ca658d585a5a8765f590612f3b7d3207d12dda Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:05:52 +0200
Subject: [PATCH 13/31] [flang-tidy][bugprone] add contiguous array check

---
 .../checks/bugprone/contiguous-array.rst      | 20 +++++++
 flang/tools/docs/flang-tidy/checks/list.rst   |  3 +-
 .../bugprone/BugproneTidyModule.cpp           |  3 +
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |  1 +
 .../bugprone/ContiguousArrayCheck.cpp         | 55 +++++++++++++++++++
 .../bugprone/ContiguousArrayCheck.h           | 34 ++++++++++++
 flang/tools/test/flang-tidy/contiguous01.f90  | 13 +++++
 7 files changed, 128 insertions(+), 1 deletion(-)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/contiguous-array.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/ContiguousArrayCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/ContiguousArrayCheck.h
 create mode 100644 flang/tools/test/flang-tidy/contiguous01.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/contiguous-array.rst b/flang/tools/docs/flang-tidy/checks/bugprone/contiguous-array.rst
new file mode 100644
index 0000000000000..fbd223e7caeb5
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/contiguous-array.rst
@@ -0,0 +1,20 @@
+.. title:: flang-tidy - bugprone-contiguous-array
+
+bugprone-contiguous-array
+=========================
+
+Verifies that assumed-shape arrays passed to interfaces are declared with the CONTIGUOUS attribute. Using contiguous arrays can lead to better performance by allowing the compiler to optimize memory access patterns.
+
+.. code-block:: fortran
+
+    module example
+      interface
+        subroutine contig(A)
+          real, contiguous, intent(in) :: A(:)
+        end subroutine contig
+
+        subroutine possibly_noncontig(A) ! This will trigger a warning
+          real, intent(in) :: A(:)
+        end subroutine possibly_noncontig
+      end interface
+    end module example
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 395499eb445cf..3ef288be8b6f3 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -17,4 +17,5 @@ Flang-Tidy Checks
    :header: "Name", "Offers fixes"
 
    :doc:`bugprone-arithmetic-goto <bugprone/arithmetic-goto>`,
-    :doc:`bugprone-arithmetic-if <bugprone/arithmetic-if>`,
+   :doc:`bugprone-arithmetic-if <bugprone/arithmetic-if>`,
+   :doc:`bugprone-contiguous-array <bugprone/contiguous-array>`,
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index e1bc649b2f003..2e717fc957982 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -10,6 +10,7 @@
 #include "../FlangTidyModuleRegistry.h"
 #include "ArithmeticGotoCheck.h"
 #include "ArithmeticIfStmtCheck.h"
+#include "ContiguousArrayCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
@@ -21,6 +22,8 @@ class BugproneModule : public FlangTidyModule {
         "bugprone-arithmetic-goto");
     CheckFactories.registerCheck<ArithmeticIfStmtCheck>(
         "bugprone-arithmetic-if");
+    CheckFactories.registerCheck<ContiguousArrayCheck>(
+        "bugprone-contiguous-array");
   }
 };
 
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index db3ca7c45eb72..8e8826b336a24 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -2,6 +2,7 @@ add_flang_library(flangTidyBugproneModule STATIC
   ArithmeticGotoCheck.cpp
   ArithmeticIfStmtCheck.cpp
   BugproneTidyModule.cpp
+  ContiguousArrayCheck.cpp
 
   LINK_LIBS
   FortranSupport
diff --git a/flang/tools/flang-tidy/bugprone/ContiguousArrayCheck.cpp b/flang/tools/flang-tidy/bugprone/ContiguousArrayCheck.cpp
new file mode 100644
index 0000000000000..d96a443458109
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/ContiguousArrayCheck.cpp
@@ -0,0 +1,55 @@
+//===--- ContiguousArrayCheck.cpp - flang-tidy ----------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "ContiguousArrayCheck.h"
+#include "flang/Semantics/symbol.h"
+
+namespace Fortran::tidy::bugprone {
+
+using namespace parser::literals;
+
+void ContiguousArrayCheck::CheckForContinguousArray(
+    semantics::SemanticsContext &context, const semantics::Scope &scope) {
+  if (scope.IsModuleFile())
+    return;
+
+  for (const auto &pair : scope) {
+    const semantics::Symbol &symbol{*pair.second};
+
+    if (const auto *details{symbol.detailsIf<semantics::SubprogramDetails>()};
+        details && details->isInterface()) {
+      for (const auto &dummyArg : details->dummyArgs()) {
+        if (!dummyArg)
+          continue;
+
+        if (const auto *details{
+                dummyArg->detailsIf<semantics::ObjectEntityDetails>()};
+            details && details->IsAssumedShape() &&
+            !dummyArg->attrs().test(semantics::Attr::CONTIGUOUS)) {
+          const auto dummySymbol{dummyArg->GetUltimate()};
+          Say(dummySymbol.name(),
+              "assumed-shape array '%s' should be contiguous"_warn_en_US,
+              dummySymbol.name());
+        }
+      }
+    }
+  }
+
+  for (const semantics::Scope &child : scope.children()) {
+    CheckForContinguousArray(context, child);
+  }
+}
+
+ContiguousArrayCheck::ContiguousArrayCheck(llvm::StringRef name,
+                                           FlangTidyContext *context)
+    : FlangTidyCheck(name, context) {
+  CheckForContinguousArray(context->getSemanticsContext(),
+                           context->getSemanticsContext().globalScope());
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/ContiguousArrayCheck.h b/flang/tools/flang-tidy/bugprone/ContiguousArrayCheck.h
new file mode 100644
index 0000000000000..457b48275fd0e
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/ContiguousArrayCheck.h
@@ -0,0 +1,34 @@
+//===--- ContiguousArrayCheck.h - flang-tidy --------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_CONTIGUOUSARRAYCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_CONTIGUOUSARRAYCHECK_H
+
+#include "../FlangTidyCheck.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check verifies that assumed-shape arrays passed to interfaces are
+/// contiguous.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/contiguous-array.html
+class ContiguousArrayCheck : public FlangTidyCheck {
+public:
+  explicit ContiguousArrayCheck(llvm::StringRef name,
+                                FlangTidyContext *context);
+  virtual ~ContiguousArrayCheck() = default;
+
+private:
+  void CheckForContinguousArray(semantics::SemanticsContext &,
+                                const semantics::Scope &);
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_CONTIGUOUSARRAYCHECK_H
diff --git a/flang/tools/test/flang-tidy/contiguous01.f90 b/flang/tools/test/flang-tidy/contiguous01.f90
new file mode 100644
index 0000000000000..139a5674defea
--- /dev/null
+++ b/flang/tools/test/flang-tidy/contiguous01.f90
@@ -0,0 +1,13 @@
+ ! RUN: %check_flang_tidy %s bugprone-contiguous-array %t
+module test
+  interface
+     subroutine contig(a)
+       real, contiguous, intent(in) :: a(:)
+     end subroutine contig
+
+     ! CHECK-MESSAGES: :[[@LINE+2]]:28: warning: assumed-shape array 'a' should be contiguous
+     subroutine possibly_noncontig(a)
+       real, intent(in) :: a(:)
+     end subroutine possibly_noncontig
+  end interface
+end module test

>From 20cf06463aee7263b2117908f2e3862dceb20b7a Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:08:40 +0200
Subject: [PATCH 14/31] [flang-tidy][bugprone] add implicit decl check

---
 .../checks/bugprone/implicit-declaration.rst  | 16 ++++++++
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../bugprone/BugproneTidyModule.cpp           |  3 ++
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |  1 +
 .../flang-tidy/bugprone/ImplicitDeclCheck.cpp | 41 +++++++++++++++++++
 .../flang-tidy/bugprone/ImplicitDeclCheck.h   | 34 +++++++++++++++
 flang/tools/test/flang-tidy/implicit01.f90    |  8 ++++
 flang/tools/test/flang-tidy/implicit02.f90    |  5 +++
 8 files changed, 109 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/implicit-declaration.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/ImplicitDeclCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/ImplicitDeclCheck.h
 create mode 100644 flang/tools/test/flang-tidy/implicit01.f90
 create mode 100644 flang/tools/test/flang-tidy/implicit02.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/implicit-declaration.rst b/flang/tools/docs/flang-tidy/checks/bugprone/implicit-declaration.rst
new file mode 100644
index 0000000000000..a9894bf6030b3
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/implicit-declaration.rst
@@ -0,0 +1,16 @@
+.. title:: flang-tidy - bugprone-implicit-declaration
+
+bugprone-implicit-declaration
+=============================
+
+Warns about implicitly declared variables, which can lead to subtle bugs. All variables should be explicitly declared to catch typos and ensure proper typing.
+
+.. code-block:: fortran
+
+    program example
+      ! Missing: implicit none
+      integer :: i
+      i = 10
+      j = 20  ! This will trigger a warning - j is implicitly declared
+      print *, i + j
+    end program
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 3ef288be8b6f3..82d64e00ed6a3 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -19,3 +19,4 @@ Flang-Tidy Checks
    :doc:`bugprone-arithmetic-goto <bugprone/arithmetic-goto>`,
    :doc:`bugprone-arithmetic-if <bugprone/arithmetic-if>`,
    :doc:`bugprone-contiguous-array <bugprone/contiguous-array>`,
+   :doc:`bugprone-implicit-declaration <bugprone/implicit-declaration>`,
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index 2e717fc957982..514a3d24fbe56 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -11,6 +11,7 @@
 #include "ArithmeticGotoCheck.h"
 #include "ArithmeticIfStmtCheck.h"
 #include "ContiguousArrayCheck.h"
+#include "ImplicitDeclCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
@@ -24,6 +25,8 @@ class BugproneModule : public FlangTidyModule {
         "bugprone-arithmetic-if");
     CheckFactories.registerCheck<ContiguousArrayCheck>(
         "bugprone-contiguous-array");
+    CheckFactories.registerCheck<ImplicitDeclCheck>(
+        "bugprone-implicit-declaration");
   }
 };
 
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index 8e8826b336a24..c67ccc96baceb 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -3,6 +3,7 @@ add_flang_library(flangTidyBugproneModule STATIC
   ArithmeticIfStmtCheck.cpp
   BugproneTidyModule.cpp
   ContiguousArrayCheck.cpp
+  ImplicitDeclCheck.cpp
 
   LINK_LIBS
   FortranSupport
diff --git a/flang/tools/flang-tidy/bugprone/ImplicitDeclCheck.cpp b/flang/tools/flang-tidy/bugprone/ImplicitDeclCheck.cpp
new file mode 100644
index 0000000000000..8df1ecfafdfd8
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/ImplicitDeclCheck.cpp
@@ -0,0 +1,41 @@
+//===--- ImplicitDeclCheck.cpp - flang-tidy -------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "ImplicitDeclCheck.h"
+
+namespace Fortran::tidy::bugprone {
+
+using namespace parser::literals;
+void ImplicitDeclCheck::CheckForImplicitDeclarations(
+    semantics::SemanticsContext &context, const semantics::Scope &scope) {
+  if (scope.IsModuleFile())
+    return;
+
+  for (const auto &pair : scope) {
+    const semantics::Symbol &symbol = *pair.second;
+    if (symbol.test(semantics::Symbol::Flag::Implicit) &&
+        !symbol.test(semantics::Symbol::Flag::Function) &&
+        !symbol.test(semantics::Symbol::Flag::Subroutine)) {
+      Say(symbol.name(), "Implicit declaration of symbol '%s'"_warn_en_US,
+          symbol.name());
+    }
+  }
+
+  for (const semantics::Scope &child : scope.children()) {
+    CheckForImplicitDeclarations(context, child);
+  }
+}
+
+ImplicitDeclCheck::ImplicitDeclCheck(llvm::StringRef name,
+                                     FlangTidyContext *context)
+    : FlangTidyCheck{name, context} {
+  CheckForImplicitDeclarations(context->getSemanticsContext(),
+                               context->getSemanticsContext().globalScope());
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/ImplicitDeclCheck.h b/flang/tools/flang-tidy/bugprone/ImplicitDeclCheck.h
new file mode 100644
index 0000000000000..a95c025a7977b
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/ImplicitDeclCheck.h
@@ -0,0 +1,34 @@
+//===--- ImplicitDeclCheck.h - flang-tidy -----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_IMPLICITDECLCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_IMPLICITDECLCHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "../FlangTidyContext.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check verifies that all variables are declared before use.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/implicit-declaration.html
+class ImplicitDeclCheck : public virtual FlangTidyCheck {
+public:
+  ImplicitDeclCheck(llvm::StringRef name, FlangTidyContext *context);
+  virtual ~ImplicitDeclCheck() = default;
+
+private:
+  void CheckForImplicitDeclarations(semantics::SemanticsContext &,
+                                    const semantics::Scope &);
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_IMPLICITDECLCHECK_H
diff --git a/flang/tools/test/flang-tidy/implicit01.f90 b/flang/tools/test/flang-tidy/implicit01.f90
new file mode 100644
index 0000000000000..fd45500fb0d74
--- /dev/null
+++ b/flang/tools/test/flang-tidy/implicit01.f90
@@ -0,0 +1,8 @@
+! RUN: %check_flang_tidy %s bugprone-implicit-declaration %t
+subroutine s
+  integer :: i, j
+  i = 1
+  j = 2
+  k = i + j
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Implicit declaration of symbol 'k'
+end subroutine s
diff --git a/flang/tools/test/flang-tidy/implicit02.f90 b/flang/tools/test/flang-tidy/implicit02.f90
new file mode 100644
index 0000000000000..f793288c23174
--- /dev/null
+++ b/flang/tools/test/flang-tidy/implicit02.f90
@@ -0,0 +1,5 @@
+! RUN: %check_flang_tidy %s bugprone-implicit-declaration %t
+subroutine s(a, n)
+  real, intent(in) :: a(n)
+  ! CHECK-MESSAGES: :[[@LINE-2]]:17: warning: Implicit declaration of symbol 'n'
+end

>From cb9280d045aff4280ddcfdaafc06a7c9cec21e39 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:13:30 +0200
Subject: [PATCH 15/31] [flang-tidy][bugprone] add implied save check

---
 .../checks/bugprone/implied-save.rst          | 15 ++++++++++
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../bugprone/BugproneTidyModule.cpp           |  2 ++
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |  1 +
 .../flang-tidy/bugprone/ImpliedSaveCheck.cpp  | 30 +++++++++++++++++++
 .../flang-tidy/bugprone/ImpliedSaveCheck.h    | 30 +++++++++++++++++++
 .../tools/test/flang-tidy/implied-save01.f90  | 13 ++++++++
 7 files changed, 92 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/implied-save.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/ImpliedSaveCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/ImpliedSaveCheck.h
 create mode 100644 flang/tools/test/flang-tidy/implied-save01.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/implied-save.rst b/flang/tools/docs/flang-tidy/checks/bugprone/implied-save.rst
new file mode 100644
index 0000000000000..197967327647a
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/implied-save.rst
@@ -0,0 +1,15 @@
+.. title:: flang-tidy - bugprone-implied-save
+
+bugprone-implied-save
+=====================
+
+Identifies variables that are implicitly saved between procedure invocations. Variables with implied SAVE status can cause unexpected behavior and side effects, particularly in parallel code.
+
+.. code-block:: fortran
+
+    subroutine example
+      integer :: counter = 0  ! This will trigger a warning - implied SAVE
+      ! Should be: integer, save :: counter = 0
+      counter = counter + 1
+      print *, "Called", counter, "times"
+    end subroutine
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 82d64e00ed6a3..784bd7f3b8be2 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -20,3 +20,4 @@ Flang-Tidy Checks
    :doc:`bugprone-arithmetic-if <bugprone/arithmetic-if>`,
    :doc:`bugprone-contiguous-array <bugprone/contiguous-array>`,
    :doc:`bugprone-implicit-declaration <bugprone/implicit-declaration>`,
+   :doc:`bugprone-implied-save <bugprone/implied-save>`,
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index 514a3d24fbe56..1e15cf4b425f5 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -12,6 +12,7 @@
 #include "ArithmeticIfStmtCheck.h"
 #include "ContiguousArrayCheck.h"
 #include "ImplicitDeclCheck.h"
+#include "ImpliedSaveCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
@@ -27,6 +28,7 @@ class BugproneModule : public FlangTidyModule {
         "bugprone-contiguous-array");
     CheckFactories.registerCheck<ImplicitDeclCheck>(
         "bugprone-implicit-declaration");
+    CheckFactories.registerCheck<ImpliedSaveCheck>("bugprone-implied-save");
   }
 };
 
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index c67ccc96baceb..5d88df08c836b 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -4,6 +4,7 @@ add_flang_library(flangTidyBugproneModule STATIC
   BugproneTidyModule.cpp
   ContiguousArrayCheck.cpp
   ImplicitDeclCheck.cpp
+  ImpliedSaveCheck.cpp
 
   LINK_LIBS
   FortranSupport
diff --git a/flang/tools/flang-tidy/bugprone/ImpliedSaveCheck.cpp b/flang/tools/flang-tidy/bugprone/ImpliedSaveCheck.cpp
new file mode 100644
index 0000000000000..61c3cb266589b
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/ImpliedSaveCheck.cpp
@@ -0,0 +1,30 @@
+//===--- ImpliedSaveCheck.cpp - flang-tidy --------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "ImpliedSaveCheck.h"
+#include "flang/Evaluate/tools.h"
+#include "flang/Parser/parse-tree.h"
+#include "flang/Semantics/attr.h"
+#include "flang/Semantics/symbol.h"
+#include "flang/Semantics/tools.h"
+#include "flang/Semantics/type.h"
+
+namespace Fortran::tidy::bugprone {
+
+using namespace parser::literals;
+void ImpliedSaveCheck::Enter(const parser::EntityDecl &entityDecl) {
+  const auto &objectName = std::get<parser::ObjectName>(entityDecl.t);
+  const auto *symbol = objectName.symbol;
+  if (symbol && semantics::IsSaved(*symbol) &&
+      !symbol->attrs().test(semantics::Attr::SAVE)) {
+    Say(symbol->name(), "Implicit SAVE on symbol '%s'"_warn_en_US,
+        symbol->name());
+  }
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/ImpliedSaveCheck.h b/flang/tools/flang-tidy/bugprone/ImpliedSaveCheck.h
new file mode 100644
index 0000000000000..6b724dc61a04b
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/ImpliedSaveCheck.h
@@ -0,0 +1,30 @@
+//===--- ImpliedSaveCheck.h - flang-tidy ------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_IMPLIEDSAVECHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_IMPLIEDSAVECHECK_H
+
+#include "../FlangTidyCheck.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check warns about variables that are implicitly saved.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/implicit-save.html
+class ImpliedSaveCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~ImpliedSaveCheck() = default;
+
+  void Enter(const parser::EntityDecl &) override;
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_IMPLIEDSAVECHECK_H
diff --git a/flang/tools/test/flang-tidy/implied-save01.f90 b/flang/tools/test/flang-tidy/implied-save01.f90
new file mode 100644
index 0000000000000..a6fbbb6877b70
--- /dev/null
+++ b/flang/tools/test/flang-tidy/implied-save01.f90
@@ -0,0 +1,13 @@
+! RUN: %check_flang_tidy %s bugprone-implied-save %t
+subroutine s
+  integer :: counter = 0
+  ! CHECK-MESSAGES: :[[@LINE-1]]:14: warning: Implicit SAVE on symbol 'counter'
+  counter = counter + 1
+  print *, "Called", counter, "times"
+end subroutine s
+
+subroutine explicit_save
+  integer, save :: counter = 0  ! No warning - explicitly saved
+  counter = counter + 1
+  print *, "Called", counter, "times"
+end subroutine explicit_save

>From 20c156de901f1b593df4d8651d3f30566506cafa Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:19:18 +0200
Subject: [PATCH 16/31] [flang-tidy][bugprone] add mismatched intent check

---
 .../checks/bugprone/mismatched-intent.rst     | 21 ++++
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../bugprone/BugproneTidyModule.cpp           |  3 +
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |  1 +
 .../bugprone/MismatchedIntentCheck.cpp        | 95 +++++++++++++++++++
 .../bugprone/MismatchedIntentCheck.h          | 32 +++++++
 flang/tools/test/flang-tidy/mismatch01.f90    | 26 +++++
 flang/tools/test/flang-tidy/mismatch02.f90    | 18 ++++
 8 files changed, 197 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/mismatched-intent.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/MismatchedIntentCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/MismatchedIntentCheck.h
 create mode 100644 flang/tools/test/flang-tidy/mismatch01.f90
 create mode 100644 flang/tools/test/flang-tidy/mismatch02.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/mismatched-intent.rst b/flang/tools/docs/flang-tidy/checks/bugprone/mismatched-intent.rst
new file mode 100644
index 0000000000000..78d31f86a0444
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/mismatched-intent.rst
@@ -0,0 +1,21 @@
+.. title:: flang-tidy - bugprone-mismatched-intent
+
+bugprone-mismatched-intent
+==========================
+
+
+Warns when a variable is passed multiple times to a procedure with conflicting INTENT attributes or when a component of a variable is passed with less restrictive intent than its parent object.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+      real :: x = 1.0
+      call update(x, x)  ! This will trigger a warning
+    contains
+      subroutine update(a, b)
+        real, intent(in) :: a
+        real, intent(out) :: b
+        b = a * 2.0
+      end subroutine
+    end program
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 784bd7f3b8be2..532a45beb9f89 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -21,3 +21,4 @@ Flang-Tidy Checks
    :doc:`bugprone-contiguous-array <bugprone/contiguous-array>`,
    :doc:`bugprone-implicit-declaration <bugprone/implicit-declaration>`,
    :doc:`bugprone-implied-save <bugprone/implied-save>`,
+   :doc:`bugprone-mismatched-intent <bugprone/mismatched-intent>`,
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index 1e15cf4b425f5..ac7b999922654 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -13,6 +13,7 @@
 #include "ContiguousArrayCheck.h"
 #include "ImplicitDeclCheck.h"
 #include "ImpliedSaveCheck.h"
+#include "MismatchedIntentCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
@@ -29,6 +30,8 @@ class BugproneModule : public FlangTidyModule {
     CheckFactories.registerCheck<ImplicitDeclCheck>(
         "bugprone-implicit-declaration");
     CheckFactories.registerCheck<ImpliedSaveCheck>("bugprone-implied-save");
+    CheckFactories.registerCheck<MismatchedIntentCheck>(
+        "bugprone-mismatched-intent");
   }
 };
 
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index 5d88df08c836b..5f8441b54f6a1 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -5,6 +5,7 @@ add_flang_library(flangTidyBugproneModule STATIC
   ContiguousArrayCheck.cpp
   ImplicitDeclCheck.cpp
   ImpliedSaveCheck.cpp
+  MismatchedIntentCheck.cpp
 
   LINK_LIBS
   FortranSupport
diff --git a/flang/tools/flang-tidy/bugprone/MismatchedIntentCheck.cpp b/flang/tools/flang-tidy/bugprone/MismatchedIntentCheck.cpp
new file mode 100644
index 0000000000000..8535ab16afab1
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/MismatchedIntentCheck.cpp
@@ -0,0 +1,95 @@
+//===--- MismatchedIntentCheck.cpp - flang-tidy ---------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "MismatchedIntentCheck.h"
+#include "flang/Evaluate/tools.h"
+#include "flang/Parser/parse-tree.h"
+#include "flang/Semantics/tools.h"
+#include <unordered_map>
+
+namespace Fortran::tidy::bugprone {
+
+using namespace parser::literals;
+
+static std::string IntentToString(common::Intent intent) {
+  switch (intent) {
+  case common::Intent::In:
+    return "in";
+  case common::Intent::Out:
+    return "out";
+  case common::Intent::InOut:
+    return "inout";
+  default:
+    return "unknown";
+  }
+}
+
+static bool IsMoreRestrictive(common::Intent first, common::Intent second) {
+  if (first == common::Intent::In &&
+      (second == common::Intent::InOut || second == common::Intent::Out)) {
+    return true;
+  }
+  return false;
+}
+
+static bool AreConflictingIntents(common::Intent first, common::Intent second) {
+  if ((first == common::Intent::In && second == common::Intent::Out) ||
+      (first == common::Intent::Out && second == common::Intent::In)) {
+    return true;
+  }
+  return false;
+}
+
+void MismatchedIntentCheck::Enter(const parser::CallStmt &callStmt) {
+  const auto *procedureRef = callStmt.typedCall.get();
+  if (!procedureRef) {
+    return;
+  }
+
+  std::unordered_map<const semantics::Symbol *, common::Intent> argIntents;
+
+  for (const auto &arg : procedureRef->arguments()) {
+    if (!arg)
+      continue;
+
+    (void)IntentToString;
+    common::Intent intent{arg->dummyIntent()};
+
+    if (const auto *expr{arg->UnwrapExpr()}) {
+      if (const auto *symbol{evaluate::UnwrapWholeSymbolDataRef(*expr)}) {
+        if (argIntents.find(symbol) != argIntents.end()) {
+          common::Intent existingIntent = argIntents[symbol];
+
+          if (existingIntent != intent &&
+              (IsMoreRestrictive(existingIntent, intent) ||
+               AreConflictingIntents(existingIntent, intent))) {
+            Say(callStmt.source,
+                "argument '%s' has mismatched intent"_warn_en_US,
+                symbol->name());
+          }
+        } else {
+          argIntents[symbol] = intent;
+        }
+      } else if (const auto component{evaluate::ExtractDataRef(*expr, true)}) {
+        const semantics::Symbol &baseSymbol = component->GetFirstSymbol();
+
+        if (argIntents.find(&baseSymbol) != argIntents.end()) {
+          common::Intent baseIntent = argIntents[&baseSymbol];
+
+          if (IsMoreRestrictive(baseIntent, intent)) {
+            Say(callStmt.source,
+                "mismatched intent between class '%s' and its member '%s'"_warn_en_US,
+                baseSymbol.name(), component->GetLastSymbol().name());
+          }
+        }
+      }
+    }
+  }
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/MismatchedIntentCheck.h b/flang/tools/flang-tidy/bugprone/MismatchedIntentCheck.h
new file mode 100644
index 0000000000000..b2e24b14db07c
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/MismatchedIntentCheck.h
@@ -0,0 +1,32 @@
+//===--- MismatchedIntentCheck.h - flang-tidy -------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_MISMATCHEDINTENTCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_MISMATCHEDINTENTCHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check warns if a variable is passed to a procedure multiple times with
+/// mismatched intent.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/mismatched-intent.html
+class MismatchedIntentCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~MismatchedIntentCheck() = default;
+
+  void Enter(const parser::CallStmt &) override;
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_MISMATCHEDINTENTCHECK_H
diff --git a/flang/tools/test/flang-tidy/mismatch01.f90 b/flang/tools/test/flang-tidy/mismatch01.f90
new file mode 100644
index 0000000000000..abdb4290b292f
--- /dev/null
+++ b/flang/tools/test/flang-tidy/mismatch01.f90
@@ -0,0 +1,26 @@
+ ! RUN: %check_flang_tidy %s bugprone-mismatched-intent %t
+module test
+  type :: child_t
+     integer :: i
+  end type child_t
+
+  type :: parent_t
+     type(child_t) :: child
+  end type parent_t
+
+  interface
+     subroutine mutate_member(parent, child)
+       import parent_t
+       import child_t
+       type(parent_t), intent(in) :: parent
+       type(child_t), intent(inout) :: child
+    end subroutine mutate_member
+ end interface
+
+contains
+  subroutine check(parent)
+    type(parent_t), intent(inout) :: parent
+    call mutate_member(parent, parent%child)
+    ! CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mismatched intent between class 'parent' and its member 'child'
+  end subroutine check
+end module test
diff --git a/flang/tools/test/flang-tidy/mismatch02.f90 b/flang/tools/test/flang-tidy/mismatch02.f90
new file mode 100644
index 0000000000000..d2451a5a5d655
--- /dev/null
+++ b/flang/tools/test/flang-tidy/mismatch02.f90
@@ -0,0 +1,18 @@
+ ! RUN: %check_flang_tidy %s bugprone-mismatched-intent %t
+module matrix
+
+  interface
+     subroutine inverse(src, dst)
+       real, intent(in) :: src(:,:)
+       real, intent(out) :: dst(:,:)
+     end subroutine inverse
+  end interface
+
+contains
+
+  subroutine check(A)
+    real, intent(inout) :: A(:,:)
+    call inverse(A, A)
+    ! CHECK-MESSAGES: :[[@LINE-1]]:5: warning: argument 'a' has mismatched intent
+  end subroutine check
+end module matrix

>From 6bcf06e7aeab06706173202a8d421933742ce936 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:22:52 +0200
Subject: [PATCH 17/31] [flang-tidy][bugprone] add missing action check

---
 .../checks/bugprone/missing-action.rst        | 18 +++++++
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../bugprone/BugproneTidyModule.cpp           |  2 +
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |  1 +
 .../bugprone/MissingActionCheck.cpp           | 50 +++++++++++++++++++
 .../flang-tidy/bugprone/MissingActionCheck.h  | 33 ++++++++++++
 .../test/flang-tidy/missing-action01.f90      | 14 ++++++
 7 files changed, 119 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/missing-action.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/MissingActionCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/MissingActionCheck.h
 create mode 100644 flang/tools/test/flang-tidy/missing-action01.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/missing-action.rst b/flang/tools/docs/flang-tidy/checks/bugprone/missing-action.rst
new file mode 100644
index 0000000000000..bbb64d01bed55
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/missing-action.rst
@@ -0,0 +1,18 @@
+.. title:: flang-tidy - bugprone-missing-action
+
+bugprone-missing-action
+=======================
+
+Verifies that all OPEN statements include an ACTION specifier, and that file unit numbers are not constant literals. This helps ensure proper file handling behavior and avoids hard-coded unit numbers.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+      integer :: unit = 10
+      open(10, file="data.txt")  ! This will trigger two warnings:
+                                 ! Missing ACTION and constant unit number
+      ! Better: open(unit, file="data.txt", action="read")
+      write(10,*) "Hello"
+      close(10)
+    end program
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 532a45beb9f89..1c5d49fcb1f49 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -22,3 +22,4 @@ Flang-Tidy Checks
    :doc:`bugprone-implicit-declaration <bugprone/implicit-declaration>`,
    :doc:`bugprone-implied-save <bugprone/implied-save>`,
    :doc:`bugprone-mismatched-intent <bugprone/mismatched-intent>`,
+   :doc:`bugprone-missing-action <bugprone/missing-action>`,
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index ac7b999922654..28de91609d914 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -14,6 +14,7 @@
 #include "ImplicitDeclCheck.h"
 #include "ImpliedSaveCheck.h"
 #include "MismatchedIntentCheck.h"
+#include "MissingActionCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
@@ -32,6 +33,7 @@ class BugproneModule : public FlangTidyModule {
     CheckFactories.registerCheck<ImpliedSaveCheck>("bugprone-implied-save");
     CheckFactories.registerCheck<MismatchedIntentCheck>(
         "bugprone-mismatched-intent");
+    CheckFactories.registerCheck<MissingActionCheck>("bugprone-missing-action");
   }
 };
 
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index 5f8441b54f6a1..8be859ce45a70 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -6,6 +6,7 @@ add_flang_library(flangTidyBugproneModule STATIC
   ImplicitDeclCheck.cpp
   ImpliedSaveCheck.cpp
   MismatchedIntentCheck.cpp
+  MissingActionCheck.cpp
 
   LINK_LIBS
   FortranSupport
diff --git a/flang/tools/flang-tidy/bugprone/MissingActionCheck.cpp b/flang/tools/flang-tidy/bugprone/MissingActionCheck.cpp
new file mode 100644
index 0000000000000..7d636a63f96e6
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/MissingActionCheck.cpp
@@ -0,0 +1,50 @@
+//===--- MissingActionCheck.cpp - flang-tidy ------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "MissingActionCheck.h"
+#include "flang/Evaluate/check-expression.h"
+#include "flang/Parser/parse-tree.h"
+#include "flang/Semantics/tools.h"
+#include "flang/Semantics/type.h"
+
+#include <algorithm>
+
+namespace Fortran::tidy::bugprone {
+
+using namespace parser::literals;
+
+void MissingActionCheck::Leave(const parser::FileUnitNumber &fileUnit) {
+  // warn if its a const expr
+  const auto *expr =
+      semantics::GetExpr(context()->getSemanticsContext(), fileUnit.v);
+
+  if (expr && evaluate::IsConstantExpr(*expr)) {
+    Say(context()->getSemanticsContext().location().value(),
+        "File unit number is a constant literal"_warn_en_US);
+  }
+}
+
+void MissingActionCheck::Leave(const parser::OpenStmt &openStmt) {
+  const auto &source = context()->getSemanticsContext().location().value();
+
+  const auto &connectSpec = openStmt.v;
+
+  const auto &action = std::find_if(
+      connectSpec.begin(), connectSpec.end(), [](const auto &spec) {
+        return std::holds_alternative<parser::ConnectSpec::CharExpr>(spec.u) &&
+               std::get<parser::ConnectSpec::CharExpr::Kind>(
+                   std::get<parser::ConnectSpec::CharExpr>(spec.u).t) ==
+                   parser::ConnectSpec::CharExpr::Kind::Action;
+      });
+
+  if (action == connectSpec.end()) {
+    Say(source, "ACTION specifier is missing"_warn_en_US);
+  }
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/MissingActionCheck.h b/flang/tools/flang-tidy/bugprone/MissingActionCheck.h
new file mode 100644
index 0000000000000..dbebea46e0aa9
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/MissingActionCheck.h
@@ -0,0 +1,33 @@
+//===--- MissingActionCheck.h - flang-tidy ----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_MISSINGACTIONCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_MISSINGACTIONCHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check verifies that all OPEN statements have an ACTION clause, and that
+/// the FILE UNIT NUMBER is not a constant literal.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/missing-action.html
+class MissingActionCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~MissingActionCheck() = default;
+
+  void Leave(const parser::FileUnitNumber &) override;
+  void Leave(const parser::OpenStmt &) override;
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_MISSINGACTIONCHECK_H
diff --git a/flang/tools/test/flang-tidy/missing-action01.f90 b/flang/tools/test/flang-tidy/missing-action01.f90
new file mode 100644
index 0000000000000..ffea483212156
--- /dev/null
+++ b/flang/tools/test/flang-tidy/missing-action01.f90
@@ -0,0 +1,14 @@
+! RUN: %check_flang_tidy %s bugprone-missing-action %t
+program open_test
+  integer :: unit = 10
+
+  open(10, file="data.txt")  ! This will trigger a warning for missing ACTION
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: File unit number is a constant literal
+  ! CHECK-MESSAGES: :[[@LINE-2]]:3: warning: ACTION specifier is missing
+
+  open(unit, file="data2.txt")  ! This will trigger a warning for constant unit
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ACTION specifier is missing
+
+  close(10)
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: File unit number is a constant literal
+end program open_test

>From 6c1e887f6541625a73267600c968106a8380ab59 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:25:57 +0200
Subject: [PATCH 18/31] [flang-tidy][bugprone] add missing default case check

---
 .../checks/bugprone/missing-default-case.rst  | 20 ++++++++++
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../bugprone/BugproneTidyModule.cpp           |  3 ++
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |  1 +
 .../bugprone/MissingDefaultCheck.cpp          | 37 +++++++++++++++++++
 .../flang-tidy/bugprone/MissingDefaultCheck.h | 31 ++++++++++++++++
 .../test/flang-tidy/missing-default-case.f90  | 24 ++++++++++++
 7 files changed, 117 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/missing-default-case.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/MissingDefaultCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/MissingDefaultCheck.h
 create mode 100644 flang/tools/test/flang-tidy/missing-default-case.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/missing-default-case.rst b/flang/tools/docs/flang-tidy/checks/bugprone/missing-default-case.rst
new file mode 100644
index 0000000000000..c56d0fe819009
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/missing-default-case.rst
@@ -0,0 +1,20 @@
+.. title:: flang-tidy - bugprone-missing-default-case
+
+bugprone-missing-default-case
+=============================
+
+Ensures that all SELECT CASE constructs include a DEFAULT case to handle unexpected values. This makes code more robust by providing a catch-all for unforeseen values.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+      integer :: i = 3
+      select case (i)  ! This will trigger a warning
+        case (1)
+          print *, "One"
+        case (2)
+          print *, "Two"
+        ! Missing: case default
+      end select
+    end program
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 1c5d49fcb1f49..69dd23aba8939 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -23,3 +23,4 @@ Flang-Tidy Checks
    :doc:`bugprone-implied-save <bugprone/implied-save>`,
    :doc:`bugprone-mismatched-intent <bugprone/mismatched-intent>`,
    :doc:`bugprone-missing-action <bugprone/missing-action>`,
+   :doc:`bugprone-missing-default-case <bugprone/missing-default-case>`,
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index 28de91609d914..3e79ceb27e173 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -15,6 +15,7 @@
 #include "ImpliedSaveCheck.h"
 #include "MismatchedIntentCheck.h"
 #include "MissingActionCheck.h"
+#include "MissingDefaultCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
@@ -34,6 +35,8 @@ class BugproneModule : public FlangTidyModule {
     CheckFactories.registerCheck<MismatchedIntentCheck>(
         "bugprone-mismatched-intent");
     CheckFactories.registerCheck<MissingActionCheck>("bugprone-missing-action");
+    CheckFactories.registerCheck<MissingDefaultCheck>(
+        "bugprone-missing-default-case");
   }
 };
 
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index 8be859ce45a70..1f2ed528af5d6 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -7,6 +7,7 @@ add_flang_library(flangTidyBugproneModule STATIC
   ImpliedSaveCheck.cpp
   MismatchedIntentCheck.cpp
   MissingActionCheck.cpp
+  MissingDefaultCheck.cpp
 
   LINK_LIBS
   FortranSupport
diff --git a/flang/tools/flang-tidy/bugprone/MissingDefaultCheck.cpp b/flang/tools/flang-tidy/bugprone/MissingDefaultCheck.cpp
new file mode 100644
index 0000000000000..0ea8cfbca590a
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/MissingDefaultCheck.cpp
@@ -0,0 +1,37 @@
+//===--- MissingDefaultCheck.cpp - flang-tidy -----------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "MissingDefaultCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+#include <algorithm>
+
+namespace Fortran::tidy::bugprone {
+
+using namespace parser::literals;
+void MissingDefaultCheck::Enter(const parser::CaseConstruct &caseConstruct) {
+  const auto &source =
+      std::get<parser::Statement<parser::SelectCaseStmt>>(caseConstruct.t)
+          .source;
+
+  const auto &cases =
+      std::get<std::list<parser::CaseConstruct::Case>>(caseConstruct.t);
+
+  bool hasDefault = std::any_of(cases.begin(), cases.end(), [](const auto &c) {
+    const auto &caseSelector = std::get<parser::CaseSelector>(
+        std::get<parser::Statement<parser::CaseStmt>>(c.t).statement.t);
+
+    return std::holds_alternative<parser::Default>(caseSelector.u);
+  });
+
+  if (!hasDefault) {
+    Say(source, "SELECT CASE construct has no DEFAULT case"_warn_en_US);
+  }
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/MissingDefaultCheck.h b/flang/tools/flang-tidy/bugprone/MissingDefaultCheck.h
new file mode 100644
index 0000000000000..20bb735a2e1c5
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/MissingDefaultCheck.h
@@ -0,0 +1,31 @@
+//===--- MissingDefaultCheck.h - flang-tidy ---------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_MISSINGDEFAULTCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_MISSINGDEFAULTCHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check verifies that all CASE constructs have a default case.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/missing-default.html
+class MissingDefaultCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~MissingDefaultCheck() = default;
+
+  void Enter(const parser::CaseConstruct &) override;
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_MISSINGDEFAULTCHECK_H
diff --git a/flang/tools/test/flang-tidy/missing-default-case.f90 b/flang/tools/test/flang-tidy/missing-default-case.f90
new file mode 100644
index 0000000000000..2f92e35c102e8
--- /dev/null
+++ b/flang/tools/test/flang-tidy/missing-default-case.f90
@@ -0,0 +1,24 @@
+! RUN: %check_flang_tidy %s bugprone-missing-default-case %t
+program case_test
+  integer :: i = 2
+
+  select case (i)  ! This will trigger a warning
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: SELECT CASE construct has no DEFAULT case
+    case (1)
+      print *, "One"
+    case (2)
+      print *, "Two"
+    ! Missing: case default
+  end select
+
+  ! Correct form:
+  select case (i)
+    case (1)
+      print *, "One"
+    case (2)
+      print *, "Two"
+    case default
+      print *, "Other"
+  end select
+
+end program case_test

>From 8b4426211848b9f9ffd057ccfc95b7ea7057f6bf Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:28:10 +0200
Subject: [PATCH 19/31] [flang-tidy][bugprone] add precision loss check

---
 .../checks/bugprone/precision-loss.rst        |  16 +++
 flang/tools/docs/flang-tidy/checks/list.rst   |   1 +
 .../bugprone/BugproneTidyModule.cpp           |   2 +
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |   1 +
 .../bugprone/PrecisionLossCheck.cpp           | 108 ++++++++++++++++++
 .../flang-tidy/bugprone/PrecisionLossCheck.h  |  29 +++++
 .../tools/test/flang-tidy/precisionloss01.f90 |  10 ++
 .../tools/test/flang-tidy/precisionloss02.f90 |   8 ++
 .../tools/test/flang-tidy/precisionloss03.f90 |  31 +++++
 9 files changed, 206 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/precision-loss.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/PrecisionLossCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/PrecisionLossCheck.h
 create mode 100644 flang/tools/test/flang-tidy/precisionloss01.f90
 create mode 100644 flang/tools/test/flang-tidy/precisionloss02.f90
 create mode 100644 flang/tools/test/flang-tidy/precisionloss03.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/precision-loss.rst b/flang/tools/docs/flang-tidy/checks/bugprone/precision-loss.rst
new file mode 100644
index 0000000000000..5325f881ddfb6
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/precision-loss.rst
@@ -0,0 +1,16 @@
+.. title:: flang-tidy - bugprone-precision-loss
+
+bugprone-precision-loss
+=======================
+
+Detects potential loss of precision in assignments between variables of different types or kind parameters. This helps prevent subtle numerical errors in computation.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+      real(kind=8) :: x = 1.0d0
+      real(kind=4) :: y
+      y = x  ! This will trigger a warning - precision loss
+      print *, y
+    end program
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 69dd23aba8939..2021cc6105959 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -24,3 +24,4 @@ Flang-Tidy Checks
    :doc:`bugprone-mismatched-intent <bugprone/mismatched-intent>`,
    :doc:`bugprone-missing-action <bugprone/missing-action>`,
    :doc:`bugprone-missing-default-case <bugprone/missing-default-case>`,
+   :doc:`bugprone-precision-loss <bugprone/precision-loss>`,
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index 3e79ceb27e173..dc0ccdc1618e4 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -16,6 +16,7 @@
 #include "MismatchedIntentCheck.h"
 #include "MissingActionCheck.h"
 #include "MissingDefaultCheck.h"
+#include "PrecisionLossCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
@@ -37,6 +38,7 @@ class BugproneModule : public FlangTidyModule {
     CheckFactories.registerCheck<MissingActionCheck>("bugprone-missing-action");
     CheckFactories.registerCheck<MissingDefaultCheck>(
         "bugprone-missing-default-case");
+    CheckFactories.registerCheck<PrecisionLossCheck>("bugprone-precision-loss");
   }
 };
 
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index 1f2ed528af5d6..aad9c9155804a 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -8,6 +8,7 @@ add_flang_library(flangTidyBugproneModule STATIC
   MismatchedIntentCheck.cpp
   MissingActionCheck.cpp
   MissingDefaultCheck.cpp
+  PrecisionLossCheck.cpp
 
   LINK_LIBS
   FortranSupport
diff --git a/flang/tools/flang-tidy/bugprone/PrecisionLossCheck.cpp b/flang/tools/flang-tidy/bugprone/PrecisionLossCheck.cpp
new file mode 100644
index 0000000000000..d465e00985ae1
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/PrecisionLossCheck.cpp
@@ -0,0 +1,108 @@
+//===--- PrecisionLossCheck.cpp - flang-tidy ------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "PrecisionLossCheck.h"
+#include "flang/Evaluate/expression.h"
+#include "flang/Parser/parse-tree.h"
+#include "flang/Semantics/tools.h"
+#include "flang/Semantics/type.h"
+#include <clang/Basic/SourceLocation.h>
+#include <variant>
+
+namespace Fortran::tidy::bugprone {
+
+static bool IsLossOfPrecision(const semantics::SomeExpr *lhs,
+                              const semantics::SomeExpr *rhs,
+                              bool hasExplicitKind, bool isConstantReal) {
+
+  const auto &lhsType{lhs->GetType()};
+  const auto &rhsType{rhs->GetType()};
+
+  if (!lhsType || !rhsType)
+    return false;
+
+  auto lhsCat = lhsType->category();
+  auto rhsCat = lhsType->category();
+
+  // ignore derived types
+  if (lhsCat == common::TypeCategory::Derived ||
+      rhsCat == common::TypeCategory::Derived)
+    return false;
+
+  int lhsKind = lhsType->kind();
+  int rhsKind = rhsType->kind();
+
+  // integer -> integer, real, complex
+  // real -> integer, real, complex
+  // complex -> integer, real, complex
+  //
+  if (lhsCat == rhsCat && lhsKind < rhsKind)
+    return true;
+
+  if (isConstantReal && lhsKind > rhsKind && !hasExplicitKind) {
+    return true;
+  }
+
+  if (lhsCat == common::TypeCategory::Complex &&
+      rhsCat == common::TypeCategory::Real) {
+    if (lhsKind < rhsKind)
+      return true;
+    return false;
+  }
+
+  if ((lhsCat == common::TypeCategory::Real ||
+       lhsCat == common::TypeCategory::Integer) &&
+      rhsCat == common::TypeCategory::Complex) {
+    return true;
+  }
+
+  if (lhsCat == common::TypeCategory::Integer &&
+      (rhsCat == common::TypeCategory::Real ||
+       rhsCat == common::TypeCategory::Complex)) {
+    return true;
+  }
+
+  if ((lhsCat == common::TypeCategory::Real ||
+       lhsCat == common::TypeCategory::Complex) &&
+      rhsCat == common::TypeCategory::Integer && lhsKind <= rhsKind) {
+    return true;
+  }
+
+  return false;
+}
+
+using namespace parser::literals;
+void PrecisionLossCheck::Enter(const parser::AssignmentStmt &assignment) {
+  const auto &var{std::get<parser::Variable>(assignment.t)};
+  const auto &expr{std::get<parser::Expr>(assignment.t)};
+  const auto *lhs{semantics::GetExpr(context()->getSemanticsContext(), var)};
+  const auto *rhs{semantics::GetExpr(context()->getSemanticsContext(), expr)};
+
+  if (!lhs || !rhs)
+    return;
+
+  bool hasExplicitKind = false;
+  bool isConstantReal = false;
+  if (std::holds_alternative<parser::LiteralConstant>(expr.u)) {
+    const auto &literal = std::get<parser::LiteralConstant>(expr.u);
+    if (std::holds_alternative<parser::RealLiteralConstant>(literal.u)) {
+      const auto &realLiteral =
+          std::get<parser::RealLiteralConstant>(literal.u);
+      hasExplicitKind = realLiteral.kind.has_value();
+      isConstantReal = true;
+    }
+  }
+
+  if (IsLossOfPrecision(lhs, rhs, hasExplicitKind, isConstantReal)) {
+    Say(context()->getSemanticsContext().location().value(),
+        "Possible loss of precision in implicit conversion (%s to %s) "_warn_en_US,
+        rhs->GetType()->AsFortran(), lhs->GetType()->AsFortran());
+  }
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/PrecisionLossCheck.h b/flang/tools/flang-tidy/bugprone/PrecisionLossCheck.h
new file mode 100644
index 0000000000000..07e5765352662
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/PrecisionLossCheck.h
@@ -0,0 +1,29 @@
+//===--- PrecisionLossCheck.h - flang-tidy ----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_PRECISIONLOSSCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_PRECISIONLOSSCHECK_H
+
+#include "../FlangTidyCheck.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check verifies that precision loss is avoided in assignments.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/precision-loss.html
+class PrecisionLossCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~PrecisionLossCheck() = default;
+  void Enter(const parser::AssignmentStmt &) override;
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_PRECISIONLOSSCHECK_H
diff --git a/flang/tools/test/flang-tidy/precisionloss01.f90 b/flang/tools/test/flang-tidy/precisionloss01.f90
new file mode 100644
index 0000000000000..07bf3ef56db49
--- /dev/null
+++ b/flang/tools/test/flang-tidy/precisionloss01.f90
@@ -0,0 +1,10 @@
+! RUN: %check_flang_tidy %s bugprone-precision-loss %t
+subroutine s
+  real(8) :: i
+  real(4) :: j
+  i = 1.0
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Possible loss of precision in implicit conversion (REAL(4) to REAL(8))
+  j = 2.0
+  j = i
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Possible loss of precision in implicit conversion (REAL(8) to REAL(4))
+end subroutine s
diff --git a/flang/tools/test/flang-tidy/precisionloss02.f90 b/flang/tools/test/flang-tidy/precisionloss02.f90
new file mode 100644
index 0000000000000..177fb232532d0
--- /dev/null
+++ b/flang/tools/test/flang-tidy/precisionloss02.f90
@@ -0,0 +1,8 @@
+! RUN: %check_flang_tidy %s bugprone-precision-loss %t
+subroutine s
+  real(8) :: i
+  real(4) :: j
+  i = 1.0_8
+  j = 2.0
+  i = j ! no warning
+end subroutine s
diff --git a/flang/tools/test/flang-tidy/precisionloss03.f90 b/flang/tools/test/flang-tidy/precisionloss03.f90
new file mode 100644
index 0000000000000..f153ec015873a
--- /dev/null
+++ b/flang/tools/test/flang-tidy/precisionloss03.f90
@@ -0,0 +1,31 @@
+! RUN: %check_flang_tidy %s bugprone-precision-loss %t
+subroutine precision_test
+  integer :: i
+  real :: r
+  real(8) :: d
+  complex :: c
+  complex(8) :: z
+
+  ! Integer to real - no precision loss
+  r = i  ! No warning
+
+  ! Real to double - no precision loss
+  d = r  ! No warning
+
+  ! Double to real - precision loss
+  r = d
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Possible loss of precision in implicit conversion (REAL(8) to REAL(4))
+
+  ! Complex to real
+  r = c
+
+  ! Complex(8) to complex(4) - precision loss
+  c = z
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Possible loss of precision in implicit conversion (COMPLEX(8) to COMPLEX(4))
+
+  ! Real to complex - no precision loss
+  c = r  ! No warning
+
+  ! Literal with kind - no precision loss
+  d = 1.0_8  ! No warning
+end subroutine precision_test

>From 6addcb009eeb7c3839ccd84553eb9718259e2001 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:30:48 +0200
Subject: [PATCH 20/31] [flang-tidy][bugprone] add subprogram trampoline check

---
 .../checks/bugprone/subprogram-trampoline.rst | 25 +++++++
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../bugprone/BugproneTidyModule.cpp           |  3 +
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |  1 +
 .../bugprone/SubprogramTrampolineCheck.cpp    | 70 +++++++++++++++++++
 .../bugprone/SubprogramTrampolineCheck.h      | 32 +++++++++
 .../test/flang-tidy/subprogram-trampoline.f90 | 17 +++++
 7 files changed, 149 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/subprogram-trampoline.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/SubprogramTrampolineCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/SubprogramTrampolineCheck.h
 create mode 100644 flang/tools/test/flang-tidy/subprogram-trampoline.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/subprogram-trampoline.rst b/flang/tools/docs/flang-tidy/checks/bugprone/subprogram-trampoline.rst
new file mode 100644
index 0000000000000..a756bfd7f82cd
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/subprogram-trampoline.rst
@@ -0,0 +1,25 @@
+.. title:: flang-tidy - bugprone-subprogram-trampoline
+
+bugprone-subprogram-trampoline
+==============================
+
+Warns when a contained subprogram is passed as an actual argument to another procedure. This pattern can lead to unexpected behavior due to the way procedure pointers and contained subprograms interact.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+      call process(inner)  ! This will trigger a warning
+    contains
+      subroutine inner()
+        print *, "Inside inner"
+      end subroutine
+
+      subroutine process(proc)
+        interface
+          subroutine proc()
+          end subroutine
+        end interface
+        call proc()
+      end subroutine
+    end program
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 2021cc6105959..15dbb159a8951 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -25,3 +25,4 @@ Flang-Tidy Checks
    :doc:`bugprone-missing-action <bugprone/missing-action>`,
    :doc:`bugprone-missing-default-case <bugprone/missing-default-case>`,
    :doc:`bugprone-precision-loss <bugprone/precision-loss>`,
+   :doc:`bugprone-subprogram-trampoline <bugprone/subprogram-trampoline>`,
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index dc0ccdc1618e4..e6ec2243f8a6c 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -17,6 +17,7 @@
 #include "MissingActionCheck.h"
 #include "MissingDefaultCheck.h"
 #include "PrecisionLossCheck.h"
+#include "SubprogramTrampolineCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
@@ -39,6 +40,8 @@ class BugproneModule : public FlangTidyModule {
     CheckFactories.registerCheck<MissingDefaultCheck>(
         "bugprone-missing-default-case");
     CheckFactories.registerCheck<PrecisionLossCheck>("bugprone-precision-loss");
+    CheckFactories.registerCheck<SubprogramTrampolineCheck>(
+        "bugprone-subprogram-trampoline");
   }
 };
 
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index aad9c9155804a..68a71c0310bec 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -9,6 +9,7 @@ add_flang_library(flangTidyBugproneModule STATIC
   MissingActionCheck.cpp
   MissingDefaultCheck.cpp
   PrecisionLossCheck.cpp
+  SubprogramTrampolineCheck.cpp
 
   LINK_LIBS
   FortranSupport
diff --git a/flang/tools/flang-tidy/bugprone/SubprogramTrampolineCheck.cpp b/flang/tools/flang-tidy/bugprone/SubprogramTrampolineCheck.cpp
new file mode 100644
index 0000000000000..0ff4a41e06f91
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/SubprogramTrampolineCheck.cpp
@@ -0,0 +1,70 @@
+//===--- SubprogramTrampolineCheck.cpp - flang-tidy -----------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "SubprogramTrampolineCheck.h"
+#include "../utils/CollectActualArguments.h"
+#include "flang/Evaluate/call.h"
+#include "flang/Evaluate/tools.h"
+#include "flang/Evaluate/variable.h"
+#include "flang/Parser/parse-tree.h"
+#include "flang/Semantics/symbol.h"
+#include "flang/Semantics/tools.h"
+#include "flang/Semantics/type.h"
+
+namespace Fortran::tidy::bugprone {
+
+using namespace parser::literals;
+void SubprogramTrampolineCheck::Enter(const parser::CallStmt &callStmt) {
+  const auto *procedureRef = callStmt.typedCall.get();
+  if (procedureRef) {
+    for (const auto &arg : procedureRef->arguments()) {
+      if (!arg)
+        continue;
+      if (const semantics::SomeExpr *argExpr{arg->UnwrapExpr()}) {
+        if (!evaluate::IsProcedureDesignator(*argExpr))
+          continue;
+        const auto proc = std::get<evaluate::ProcedureDesignator>(argExpr->u);
+        if (const auto *symbol{proc.GetSymbol()}) {
+          if (symbol->has<semantics::SubprogramDetails>()) {
+            Say(callStmt.source,
+                "contained subprogram '%s' is passed as an argument"_warn_en_US,
+                symbol->name().ToString());
+          }
+        }
+      }
+    }
+  }
+}
+
+void SubprogramTrampolineCheck::Enter(const parser::Expr &e) {
+  const auto *expr = semantics::GetExpr(context()->getSemanticsContext(), e);
+  if (!expr) {
+    return;
+  }
+
+  if (std::holds_alternative<common::Indirection<parser::FunctionReference>>(
+          e.u)) {
+    evaluate::ActualArgumentSet argSet{evaluate::CollectActualArguments(*expr)};
+    for (const evaluate::ActualArgumentRef &argRef : argSet) {
+      if (const semantics::SomeExpr *argExpr{argRef->UnwrapExpr()}) {
+        if (!evaluate::IsProcedureDesignator(*argExpr))
+          continue;
+        const auto proc = std::get<evaluate::ProcedureDesignator>(argExpr->u);
+        if (const auto *symbol{proc.GetSymbol()}) {
+          if (symbol->has<semantics::SubprogramDetails>()) {
+            Say(e.source,
+                "contained subprogram '%s' is passed as an argument"_warn_en_US,
+                symbol->name().ToString());
+          }
+        }
+      }
+    }
+  }
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/SubprogramTrampolineCheck.h b/flang/tools/flang-tidy/bugprone/SubprogramTrampolineCheck.h
new file mode 100644
index 0000000000000..41322b87e052f
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/SubprogramTrampolineCheck.h
@@ -0,0 +1,32 @@
+//===--- SubprogramTrampolineCheck.h - flang-tidy ---------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_SUBPROGRAMTRAMPOLINECHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_SUBPROGRAMTRAMPOLINECHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check verifies that a contained subprogram is not passed as an
+/// actual argument to a procedure.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/subprogram-trampoline.html
+class SubprogramTrampolineCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~SubprogramTrampolineCheck() = default;
+  void Enter(const parser::Expr &) override;
+  void Enter(const parser::CallStmt &) override;
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_SUBPROGRAMTRAMPOLINECHECK_H
diff --git a/flang/tools/test/flang-tidy/subprogram-trampoline.f90 b/flang/tools/test/flang-tidy/subprogram-trampoline.f90
new file mode 100644
index 0000000000000..3d3974b6a6e91
--- /dev/null
+++ b/flang/tools/test/flang-tidy/subprogram-trampoline.f90
@@ -0,0 +1,17 @@
+! RUN: %check_flang_tidy %s bugprone-subprogram-trampoline %t
+program trampoline_test
+  call process(inner)  ! This will trigger a warning
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: contained subprogram 'inner' is passed as an argument
+contains
+  subroutine inner()
+    print *, "Inside inner"
+  end subroutine
+
+  subroutine process(proc)
+    interface
+      subroutine proc()
+      end subroutine
+    end interface
+    call proc()
+  end subroutine
+end program trampoline_test

>From 74000ab13dde65e5a0582d3b775a883bc27c8f56 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:33:07 +0200
Subject: [PATCH 21/31] [flang-tidy][bugprone] add undeclared proc check

---
 .../checks/bugprone/undeclared-procedure.rst  | 17 +++++++
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../bugprone/BugproneTidyModule.cpp           |  3 ++
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |  1 +
 .../bugprone/UndeclaredProcCheck.cpp          | 50 +++++++++++++++++++
 .../flang-tidy/bugprone/UndeclaredProcCheck.h | 33 ++++++++++++
 .../tools/test/flang-tidy/implicitproc01.f90  |  5 ++
 7 files changed, 110 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/undeclared-procedure.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/UndeclaredProcCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/UndeclaredProcCheck.h
 create mode 100644 flang/tools/test/flang-tidy/implicitproc01.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/undeclared-procedure.rst b/flang/tools/docs/flang-tidy/checks/bugprone/undeclared-procedure.rst
new file mode 100644
index 0000000000000..3b1f0c3996f90
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/undeclared-procedure.rst
@@ -0,0 +1,17 @@
+.. title:: flang-tidy - bugprone-undeclared-procedure
+
+bugprone-undeclared-procedure
+=============================
+
+Warns about procedures that are implicitly declared or lack an explicit interface. Using procedures without explicit interfaces can lead to subtle bugs and prevents the compiler from performing argument checking.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+      integer :: result
+      external :: no_interface_procedure
+      call no_interface_procedure(5, result)  ! This will trigger a warning (no interface)
+      call implicit_procedure(5, result)  ! This will also trigger a warning (implicit declaration)
+      print *, result
+    end program
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 15dbb159a8951..ea37e59c51328 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -26,3 +26,4 @@ Flang-Tidy Checks
    :doc:`bugprone-missing-default-case <bugprone/missing-default-case>`,
    :doc:`bugprone-precision-loss <bugprone/precision-loss>`,
    :doc:`bugprone-subprogram-trampoline <bugprone/subprogram-trampoline>`,
+   :doc:`bugprone-undeclared-procedure <bugprone/undeclared-procedure>`,
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index e6ec2243f8a6c..36c32935783d4 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -18,6 +18,7 @@
 #include "MissingDefaultCheck.h"
 #include "PrecisionLossCheck.h"
 #include "SubprogramTrampolineCheck.h"
+#include "UndeclaredProcCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
@@ -42,6 +43,8 @@ class BugproneModule : public FlangTidyModule {
     CheckFactories.registerCheck<PrecisionLossCheck>("bugprone-precision-loss");
     CheckFactories.registerCheck<SubprogramTrampolineCheck>(
         "bugprone-subprogram-trampoline");
+    CheckFactories.registerCheck<UndeclaredProcCheck>(
+        "bugprone-undeclared-procedure");
   }
 };
 
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index 68a71c0310bec..78196341c99f6 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -10,6 +10,7 @@ add_flang_library(flangTidyBugproneModule STATIC
   MissingDefaultCheck.cpp
   PrecisionLossCheck.cpp
   SubprogramTrampolineCheck.cpp
+  UndeclaredProcCheck.cpp
 
   LINK_LIBS
   FortranSupport
diff --git a/flang/tools/flang-tidy/bugprone/UndeclaredProcCheck.cpp b/flang/tools/flang-tidy/bugprone/UndeclaredProcCheck.cpp
new file mode 100644
index 0000000000000..30ca1236fd307
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/UndeclaredProcCheck.cpp
@@ -0,0 +1,50 @@
+//===--- UndeclaredProcCheck.cpp - flang-tidy -----------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "UndeclaredProcCheck.h"
+#include "flang/Semantics/attr.h"
+#include "flang/Semantics/symbol.h"
+
+namespace Fortran::tidy::bugprone {
+
+using namespace parser::literals;
+void UndeclaredProcCheck::CheckForUndeclaredProcedures(
+    semantics::SemanticsContext &context, const semantics::Scope &scope) {
+  if (scope.IsModuleFile())
+    return;
+
+  for (const auto &pair : scope) {
+    const semantics::Symbol &symbol = *pair.second;
+    if (auto *details{symbol.detailsIf<semantics::ProcEntityDetails>()};
+        details) {
+      if (symbol.owner().IsGlobal()) { // unknown global procedure
+        Say(symbol.name(), "Implicit declaration of procedure '%s'"_warn_en_US,
+            symbol.name());
+      } else if (!details->HasExplicitInterface() && // no explicit interface
+                 !symbol.attrs().test(
+                     semantics::Attr::INTRINSIC)) { // not an intrinsic
+        Say(symbol.name(),
+            "Procedure '%s' has no explicit interface"_warn_en_US,
+            symbol.name());
+      }
+    }
+  }
+
+  for (const semantics::Scope &child : scope.children()) {
+    CheckForUndeclaredProcedures(context, child);
+  }
+}
+
+UndeclaredProcCheck::UndeclaredProcCheck(llvm::StringRef name,
+                                         FlangTidyContext *context)
+    : FlangTidyCheck{name, context} {
+  CheckForUndeclaredProcedures(context->getSemanticsContext(),
+                               context->getSemanticsContext().globalScope());
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/UndeclaredProcCheck.h b/flang/tools/flang-tidy/bugprone/UndeclaredProcCheck.h
new file mode 100644
index 0000000000000..0650e06d40683
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/UndeclaredProcCheck.h
@@ -0,0 +1,33 @@
+//===--- UndeclaredProcCheck.h - flang-tidy ---------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_UNDECLAREDPROCCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_UNDECLAREDPROCCHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "../FlangTidyContext.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check verifies that all procedures are explicitly declared.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/implicit-procedure-declaration.html
+class UndeclaredProcCheck : public virtual FlangTidyCheck {
+public:
+  UndeclaredProcCheck(llvm::StringRef name, FlangTidyContext *context);
+  virtual ~UndeclaredProcCheck() = default;
+
+private:
+  void CheckForUndeclaredProcedures(semantics::SemanticsContext &,
+                                    const semantics::Scope &);
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_UNDECLAREDPROCCHECK_H
diff --git a/flang/tools/test/flang-tidy/implicitproc01.f90 b/flang/tools/test/flang-tidy/implicitproc01.f90
new file mode 100644
index 0000000000000..d044154e76789
--- /dev/null
+++ b/flang/tools/test/flang-tidy/implicitproc01.f90
@@ -0,0 +1,5 @@
+! RUN: %check_flang_tidy %s bugprone-undeclared-procedure %t
+subroutine s1
+  call s2()
+  ! CHECK-MESSAGES: :[[@LINE-1]]:8: warning: Implicit declaration of procedure 's2'
+end subroutine s1

>From 8b77899ea2d7c0f6f3101d2ba82168d8d60a4e89 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:35:34 +0200
Subject: [PATCH 22/31] [flang-tidy][bugprone] add unused intent check

---
 .../checks/bugprone/unused-intent.rst         | 17 ++++
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../bugprone/BugproneTidyModule.cpp           |  2 +
 .../tools/flang-tidy/bugprone/CMakeLists.txt  |  1 +
 .../flang-tidy/bugprone/UnusedIntentCheck.cpp | 87 +++++++++++++++++++
 .../flang-tidy/bugprone/UnusedIntentCheck.h   | 33 +++++++
 flang/tools/test/flang-tidy/intent01.f90      |  6 ++
 7 files changed, 147 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/bugprone/unused-intent.rst
 create mode 100644 flang/tools/flang-tidy/bugprone/UnusedIntentCheck.cpp
 create mode 100644 flang/tools/flang-tidy/bugprone/UnusedIntentCheck.h
 create mode 100644 flang/tools/test/flang-tidy/intent01.f90

diff --git a/flang/tools/docs/flang-tidy/checks/bugprone/unused-intent.rst b/flang/tools/docs/flang-tidy/checks/bugprone/unused-intent.rst
new file mode 100644
index 0000000000000..df9996e5a5fb3
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/bugprone/unused-intent.rst
@@ -0,0 +1,17 @@
+.. title:: flang-tidy - bugprone-unused-intent
+
+bugprone-unused-intent
+======================
+
+Identifies dummy arguments with INTENT(INOUT) that are never modified, suggesting they should be INTENT(IN) instead. It also warns about dummy arguments without explicit intent declarations, which could lead to confusion about how they're used.
+
+.. code-block:: fortran
+
+    subroutine process(a, b, c)
+      implicit none
+      real, intent(in) :: a
+      real, intent(inout) :: b  ! This will trigger a warning if b is never modified
+      real :: c               ! This will trigger a warning for missing intent
+
+      print *, a, b, c
+    end subroutine
diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index ea37e59c51328..31decff549a5d 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -27,3 +27,4 @@ Flang-Tidy Checks
    :doc:`bugprone-precision-loss <bugprone/precision-loss>`,
    :doc:`bugprone-subprogram-trampoline <bugprone/subprogram-trampoline>`,
    :doc:`bugprone-undeclared-procedure <bugprone/undeclared-procedure>`,
+   :doc:`bugprone-unused-intent <bugprone/unused-intent>`,
diff --git a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
index 36c32935783d4..6f955d65a7aa7 100644
--- a/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/flang/tools/flang-tidy/bugprone/BugproneTidyModule.cpp
@@ -19,6 +19,7 @@
 #include "PrecisionLossCheck.h"
 #include "SubprogramTrampolineCheck.h"
 #include "UndeclaredProcCheck.h"
+#include "UnusedIntentCheck.h"
 
 namespace Fortran::tidy {
 namespace bugprone {
@@ -45,6 +46,7 @@ class BugproneModule : public FlangTidyModule {
         "bugprone-subprogram-trampoline");
     CheckFactories.registerCheck<UndeclaredProcCheck>(
         "bugprone-undeclared-procedure");
+    CheckFactories.registerCheck<UnusedIntentCheck>("bugprone-unused-intent");
   }
 };
 
diff --git a/flang/tools/flang-tidy/bugprone/CMakeLists.txt b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
index 78196341c99f6..47994f914848f 100644
--- a/flang/tools/flang-tidy/bugprone/CMakeLists.txt
+++ b/flang/tools/flang-tidy/bugprone/CMakeLists.txt
@@ -11,6 +11,7 @@ add_flang_library(flangTidyBugproneModule STATIC
   PrecisionLossCheck.cpp
   SubprogramTrampolineCheck.cpp
   UndeclaredProcCheck.cpp
+  UnusedIntentCheck.cpp
 
   LINK_LIBS
   FortranSupport
diff --git a/flang/tools/flang-tidy/bugprone/UnusedIntentCheck.cpp b/flang/tools/flang-tidy/bugprone/UnusedIntentCheck.cpp
new file mode 100644
index 0000000000000..6e02028c73abd
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/UnusedIntentCheck.cpp
@@ -0,0 +1,87 @@
+//===--- UnusedIntentCheck.cpp - flang-tidy -------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "UnusedIntentCheck.h"
+#include "flang/Semantics/attr.h"
+#include "flang/Semantics/symbol.h"
+#include "flang/Semantics/tools.h"
+
+namespace Fortran::tidy::bugprone {
+
+using namespace parser::literals;
+
+static std::unordered_map<const semantics::Symbol *, const semantics::Symbol *>
+    procBindingDetailsSymbolsMap;
+
+void UnusedIntentCheck::CheckUnusedIntentHelper(
+    semantics::SemanticsContext &context, const semantics::Scope &scope) {
+  if (scope.IsModuleFile())
+    return;
+
+  auto WasDefined{[&context](const semantics::Symbol &symbol) {
+    return context.IsSymbolDefined(symbol) ||
+           semantics::IsInitialized(symbol, false, false, false);
+  }};
+  for (const auto &pair : scope) {
+    const semantics::Symbol &symbol = *pair.second;
+    if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()};
+        details && details->isDummy()) {
+      const auto &owningProcScope = symbol.owner();
+      const auto &owningProc = owningProcScope.symbol();
+
+      if (procBindingDetailsSymbolsMap.find(owningProc) !=
+          procBindingDetailsSymbolsMap.end()) {
+        continue;
+      }
+      if (!WasDefined(symbol) && semantics::IsIntentInOut(symbol)) {
+        Say(symbol.name(),
+            "Dummy argument '%s' with intent(inout) is never written to, consider changing to intent(in)"_warn_en_US,
+            symbol.name());
+      }
+      if (!symbol.attrs().HasAny({semantics::Attr::INTENT_IN,
+                                  semantics::Attr::INTENT_INOUT,
+                                  semantics::Attr::INTENT_OUT})) {
+        // warn about dummy arguments without explicit intent
+        Say(symbol.name(),
+            "Dummy argument '%s' has no explicit intent"_warn_en_US,
+            symbol.name());
+      }
+    }
+  }
+
+  for (const semantics::Scope &child : scope.children()) {
+    CheckUnusedIntentHelper(context, child);
+  }
+}
+
+static void MakeProcBindingSymbolSet(semantics::SemanticsContext &context,
+                                     const semantics::Scope &scope) {
+  for (const auto &pair : scope) {
+    const semantics::Symbol &symbol = *pair.second;
+    if (auto *details{symbol.detailsIf<semantics::ProcBindingDetails>()}) {
+      procBindingDetailsSymbolsMap[&details->symbol()] = &symbol;
+    }
+  }
+
+  for (const semantics::Scope &child : scope.children()) {
+    MakeProcBindingSymbolSet(context, child);
+  }
+}
+
+UnusedIntentCheck::UnusedIntentCheck(llvm::StringRef name,
+                                     FlangTidyContext *context)
+    : FlangTidyCheck{name, context} {
+
+  MakeProcBindingSymbolSet(context->getSemanticsContext(),
+                           context->getSemanticsContext().globalScope());
+
+  CheckUnusedIntentHelper(context->getSemanticsContext(),
+                          context->getSemanticsContext().globalScope());
+}
+
+} // namespace Fortran::tidy::bugprone
diff --git a/flang/tools/flang-tidy/bugprone/UnusedIntentCheck.h b/flang/tools/flang-tidy/bugprone/UnusedIntentCheck.h
new file mode 100644
index 0000000000000..147febd9f498a
--- /dev/null
+++ b/flang/tools/flang-tidy/bugprone/UnusedIntentCheck.h
@@ -0,0 +1,33 @@
+//===--- UnusedIntentCheck.h - flang-tidy -----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_UNUSEDINTENTCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_UNUSEDINTENTCHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "../FlangTidyContext.h"
+
+namespace Fortran::tidy::bugprone {
+
+/// This check verifies that all INTENT attributes are used.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/unused-intent.html
+class UnusedIntentCheck : public virtual FlangTidyCheck {
+public:
+  UnusedIntentCheck(llvm::StringRef name, FlangTidyContext *context);
+  virtual ~UnusedIntentCheck() = default;
+
+private:
+  void CheckUnusedIntentHelper(semantics::SemanticsContext &,
+                               const semantics::Scope &);
+};
+
+} // namespace Fortran::tidy::bugprone
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_BUGPRONE_UNUSEDINTENTCHECK_H
diff --git a/flang/tools/test/flang-tidy/intent01.f90 b/flang/tools/test/flang-tidy/intent01.f90
new file mode 100644
index 0000000000000..d62ff08015491
--- /dev/null
+++ b/flang/tools/test/flang-tidy/intent01.f90
@@ -0,0 +1,6 @@
+! RUN: %check_flang_tidy %s bugprone-unused-intent %t
+subroutine s(a, b)
+  integer, intent(inout) :: a, b
+  ! CHECK-MESSAGES: :[[@LINE-1]]:32: warning: Dummy argument 'b' with intent(inout) is never written to, consider changing to intent(in)
+  a = a + 1 - b
+end subroutine s

>From d0e5d98ab2e521f9e9946a4926272d2a08ee49dc Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:40:58 +0200
Subject: [PATCH 23/31] [flang-tidy][modernize] add avoid assign check

---
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../checks/modernize/avoid-assign-stmt.rst    | 23 ++++++++++++++
 .../flang-tidy/modernize/AvoidAssignStmt.cpp  | 29 +++++++++++++++++
 .../flang-tidy/modernize/AvoidAssignStmt.h    | 31 +++++++++++++++++++
 .../tools/flang-tidy/modernize/CMakeLists.txt |  2 +-
 .../modernize/ModernizeTidyModule.cpp         |  6 +++-
 flang/tools/test/flang-tidy/assign.f90        |  9 ++++++
 7 files changed, 99 insertions(+), 2 deletions(-)
 create mode 100644 flang/tools/docs/flang-tidy/checks/modernize/avoid-assign-stmt.rst
 create mode 100644 flang/tools/flang-tidy/modernize/AvoidAssignStmt.cpp
 create mode 100644 flang/tools/flang-tidy/modernize/AvoidAssignStmt.h
 create mode 100644 flang/tools/test/flang-tidy/assign.f90

diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 31decff549a5d..91174c0276e46 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -28,3 +28,4 @@ Flang-Tidy Checks
    :doc:`bugprone-subprogram-trampoline <bugprone/subprogram-trampoline>`,
    :doc:`bugprone-undeclared-procedure <bugprone/undeclared-procedure>`,
    :doc:`bugprone-unused-intent <bugprone/unused-intent>`,
+   :doc:`modernize-avoid-assign-stmt <modernize/avoid-assign-stmt>`,
diff --git a/flang/tools/docs/flang-tidy/checks/modernize/avoid-assign-stmt.rst b/flang/tools/docs/flang-tidy/checks/modernize/avoid-assign-stmt.rst
new file mode 100644
index 0000000000000..6ea49abd11f38
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/modernize/avoid-assign-stmt.rst
@@ -0,0 +1,23 @@
+.. title:: flang-tidy - modernize-avoid-assign-stmt
+
+modernize-avoid-assign-stmt
+===========================
+
+Warns about the use of obsolete ASSIGN and assigned GOTO statements, which were deprecated in Fortran 95 and removed from the Fortran 2018 standard. Modern Fortran code should use more structured alternatives.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+      integer :: i
+
+      assign 100 to i  ! This will trigger a warning
+      goto i, (100, 200, 300)  ! This will trigger a warning
+
+    100 print *, "Label 100"
+      stop
+    200 print *, "Label 200"
+      stop
+    300 print *, "Label 300"
+      stop
+    end program
diff --git a/flang/tools/flang-tidy/modernize/AvoidAssignStmt.cpp b/flang/tools/flang-tidy/modernize/AvoidAssignStmt.cpp
new file mode 100644
index 0000000000000..3010f6dcc0f5a
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/AvoidAssignStmt.cpp
@@ -0,0 +1,29 @@
+//===--- AvoidAssignStmt.cpp - flang-tidy ---------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "AvoidAssignStmt.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::modernize {
+
+using namespace parser::literals;
+void AvoidAssignStmtCheck::Enter(const parser::AssignStmt &) {
+  if (context()->getSemanticsContext().location().has_value()) {
+    Say(context()->getSemanticsContext().location().value(),
+        "Assign statements are not recommended"_warn_en_US);
+  }
+}
+
+void AvoidAssignStmtCheck::Enter(const parser::AssignedGotoStmt &) {
+  if (context()->getSemanticsContext().location().has_value()) {
+    Say(context()->getSemanticsContext().location().value(),
+        "Assigned Goto statements are not recommended"_warn_en_US);
+  }
+}
+
+} // namespace Fortran::tidy::modernize
diff --git a/flang/tools/flang-tidy/modernize/AvoidAssignStmt.h b/flang/tools/flang-tidy/modernize/AvoidAssignStmt.h
new file mode 100644
index 0000000000000..7c6366180a68c
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/AvoidAssignStmt.h
@@ -0,0 +1,31 @@
+//===--- AvoidAssignStmt.h - flang-tidy -------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDASSIGNSTMT_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDASSIGNSTMT_H
+
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::modernize {
+
+/// This check verifies that ASSIGN and ASSIGNED GOTO statements are avoided.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/avoid-assign-stmt.html
+class AvoidAssignStmtCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~AvoidAssignStmtCheck() = default;
+  void Enter(const parser::AssignStmt &) override;
+  void Enter(const parser::AssignedGotoStmt &) override;
+};
+
+} // namespace Fortran::tidy::modernize
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDASSIGNSTMT_H
diff --git a/flang/tools/flang-tidy/modernize/CMakeLists.txt b/flang/tools/flang-tidy/modernize/CMakeLists.txt
index bbb3098f76d9b..074a35ed0f698 100644
--- a/flang/tools/flang-tidy/modernize/CMakeLists.txt
+++ b/flang/tools/flang-tidy/modernize/CMakeLists.txt
@@ -1,4 +1,5 @@
 add_flang_library(flangTidyModernizeModule STATIC
+  AvoidAssignStmt.cpp
   ModernizeTidyModule.cpp
 
   LINK_LIBS
@@ -15,4 +16,3 @@ add_flang_library(flangTidyModernizeModule STATIC
   FrontendOpenACC
   TargetParser
   )
-
diff --git a/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
index f2717adac43ed..3709f6eac61ac 100644
--- a/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
@@ -8,13 +8,17 @@
 
 #include "../FlangTidyModule.h"
 #include "../FlangTidyModuleRegistry.h"
+#include "AvoidAssignStmt.h"
 
 namespace Fortran::tidy {
 namespace modernize {
 
 class ModernizeModule : public FlangTidyModule {
 public:
-  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {}
+  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {
+    CheckFactories.registerCheck<AvoidAssignStmtCheck>(
+        "modernize-avoid-assign-stmt");
+  }
 };
 
 } // namespace modernize
diff --git a/flang/tools/test/flang-tidy/assign.f90 b/flang/tools/test/flang-tidy/assign.f90
new file mode 100644
index 0000000000000..ba3f28df8167d
--- /dev/null
+++ b/flang/tools/test/flang-tidy/assign.f90
@@ -0,0 +1,9 @@
+! RUN: %check_flang_tidy %s modernize-avoid-assign-stmt %t
+subroutine s
+  integer :: i
+  assign 9 to i
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Assign statements are not recommended    
+  go to i
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Assigned Goto statements are not recommended
+9 continue
+end subroutine s

>From f212c664ee12329527eada40f7ddaf6a8253d898 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:43:03 +0200
Subject: [PATCH 24/31] [flang-tidy][modernize] add avoid backspace check

---
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../checks/modernize/avoid-backspace-stmt.rst | 19 ++++++++++++
 .../modernize/AvoidBackspaceStmt.cpp          | 22 ++++++++++++++
 .../flang-tidy/modernize/AvoidBackspaceStmt.h | 30 +++++++++++++++++++
 .../tools/flang-tidy/modernize/CMakeLists.txt |  1 +
 .../modernize/ModernizeTidyModule.cpp         |  3 ++
 .../tools/test/flang-tidy/avoid-backspace.f90 | 13 ++++++++
 7 files changed, 89 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/modernize/avoid-backspace-stmt.rst
 create mode 100644 flang/tools/flang-tidy/modernize/AvoidBackspaceStmt.cpp
 create mode 100644 flang/tools/flang-tidy/modernize/AvoidBackspaceStmt.h
 create mode 100644 flang/tools/test/flang-tidy/avoid-backspace.f90

diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 91174c0276e46..ce32ead03fb8d 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -29,3 +29,4 @@ Flang-Tidy Checks
    :doc:`bugprone-undeclared-procedure <bugprone/undeclared-procedure>`,
    :doc:`bugprone-unused-intent <bugprone/unused-intent>`,
    :doc:`modernize-avoid-assign-stmt <modernize/avoid-assign-stmt>`,
+   :doc:`modernize-avoid-backspace-stmt <modernize/avoid-backspace-stmt>`,
diff --git a/flang/tools/docs/flang-tidy/checks/modernize/avoid-backspace-stmt.rst b/flang/tools/docs/flang-tidy/checks/modernize/avoid-backspace-stmt.rst
new file mode 100644
index 0000000000000..3f1919887282e
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/modernize/avoid-backspace-stmt.rst
@@ -0,0 +1,19 @@
+.. title:: flang-tidy - modernize-avoid-backspace-stmt
+
+modernize-avoid-backspace-stmt
+==============================
+
+Identifies usage of the BACKSPACE statement, which can lead to inefficient I/O operations. Modern Fortran code should use more reliable file positioning methods.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+      integer :: unit = 10, x
+
+      open(unit, file="data.txt", action="read")
+      read(unit, *) x
+      backspace(unit)  ! This will trigger a warning
+      read(unit, *) x
+      close(unit)
+    end program
diff --git a/flang/tools/flang-tidy/modernize/AvoidBackspaceStmt.cpp b/flang/tools/flang-tidy/modernize/AvoidBackspaceStmt.cpp
new file mode 100644
index 0000000000000..ee4ec011e3080
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/AvoidBackspaceStmt.cpp
@@ -0,0 +1,22 @@
+//===--- AvoidBackspaceStmt.cpp - flang-tidy ------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "AvoidBackspaceStmt.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::modernize {
+
+using namespace parser::literals;
+void AvoidBackspaceStmtCheck::Enter(const parser::BackspaceStmt &) {
+  if (context()->getSemanticsContext().location().has_value()) {
+    Say(context()->getSemanticsContext().location().value(),
+        "Assign statements are not recommended"_warn_en_US);
+  }
+}
+
+} // namespace Fortran::tidy::modernize
diff --git a/flang/tools/flang-tidy/modernize/AvoidBackspaceStmt.h b/flang/tools/flang-tidy/modernize/AvoidBackspaceStmt.h
new file mode 100644
index 0000000000000..10a54beb43d88
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/AvoidBackspaceStmt.h
@@ -0,0 +1,30 @@
+//===--- AvoidBackspaceStmt.h - flang-tidy ----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDBACKSPACESTMT_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDBACKSPACESTMT_H
+
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::modernize {
+
+/// This check verifies that BACKSPACE statements are avoided.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/avoid-backspace-stmt.html
+class AvoidBackspaceStmtCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~AvoidBackspaceStmtCheck() = default;
+  void Enter(const parser::BackspaceStmt &) override;
+};
+
+} // namespace Fortran::tidy::modernize
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDBACKSPACESTMT_H
diff --git a/flang/tools/flang-tidy/modernize/CMakeLists.txt b/flang/tools/flang-tidy/modernize/CMakeLists.txt
index 074a35ed0f698..4d8b152b17e22 100644
--- a/flang/tools/flang-tidy/modernize/CMakeLists.txt
+++ b/flang/tools/flang-tidy/modernize/CMakeLists.txt
@@ -1,5 +1,6 @@
 add_flang_library(flangTidyModernizeModule STATIC
   AvoidAssignStmt.cpp
+  AvoidBackspaceStmt.cpp
   ModernizeTidyModule.cpp
 
   LINK_LIBS
diff --git a/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
index 3709f6eac61ac..92ce7ad01c4ff 100644
--- a/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
@@ -9,6 +9,7 @@
 #include "../FlangTidyModule.h"
 #include "../FlangTidyModuleRegistry.h"
 #include "AvoidAssignStmt.h"
+#include "AvoidBackspaceStmt.h"
 
 namespace Fortran::tidy {
 namespace modernize {
@@ -18,6 +19,8 @@ class ModernizeModule : public FlangTidyModule {
   void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {
     CheckFactories.registerCheck<AvoidAssignStmtCheck>(
         "modernize-avoid-assign-stmt");
+    CheckFactories.registerCheck<AvoidBackspaceStmtCheck>(
+        "modernize-avoid-backspace-stmt");
   }
 };
 
diff --git a/flang/tools/test/flang-tidy/avoid-backspace.f90 b/flang/tools/test/flang-tidy/avoid-backspace.f90
new file mode 100644
index 0000000000000..ba7598a470ab1
--- /dev/null
+++ b/flang/tools/test/flang-tidy/avoid-backspace.f90
@@ -0,0 +1,13 @@
+! RUN: %check_flang_tidy %s modernize-avoid-backspace-stmt %t
+program backspace_test
+  integer :: unit = 10, x
+
+  open(unit, file="data.txt", action="readwrite")
+  write(unit, *) 1, 2, 3
+
+  backspace(unit)  ! This will trigger a warning
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Assign statements are not recommended
+
+  read(unit, *) x
+  close(unit)
+end program backspace_test

>From 52768912aecdb72195e206968607f32d270a6d67 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:46:41 +0200
Subject: [PATCH 25/31] [flang-tidy][modernize] add avoid commonblock check

---
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../checks/modernize/avoid-common-blocks.rst  | 26 +++++++++++++++++
 .../modernize/AvoidCommonBlocks.cpp           | 21 ++++++++++++++
 .../flang-tidy/modernize/AvoidCommonBlocks.h  | 29 +++++++++++++++++++
 .../tools/flang-tidy/modernize/CMakeLists.txt |  1 +
 .../modernize/ModernizeTidyModule.cpp         |  3 ++
 flang/tools/test/flang-tidy/commonblock.f90   |  6 ++++
 7 files changed, 87 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/modernize/avoid-common-blocks.rst
 create mode 100644 flang/tools/flang-tidy/modernize/AvoidCommonBlocks.cpp
 create mode 100644 flang/tools/flang-tidy/modernize/AvoidCommonBlocks.h
 create mode 100644 flang/tools/test/flang-tidy/commonblock.f90

diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index ce32ead03fb8d..d68167cf05118 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -30,3 +30,4 @@ Flang-Tidy Checks
    :doc:`bugprone-unused-intent <bugprone/unused-intent>`,
    :doc:`modernize-avoid-assign-stmt <modernize/avoid-assign-stmt>`,
    :doc:`modernize-avoid-backspace-stmt <modernize/avoid-backspace-stmt>`,
+   :doc:`modernize-avoid-common-blocks <modernize/avoid-common-blocks>`,
diff --git a/flang/tools/docs/flang-tidy/checks/modernize/avoid-common-blocks.rst b/flang/tools/docs/flang-tidy/checks/modernize/avoid-common-blocks.rst
new file mode 100644
index 0000000000000..f445ea5d80677
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/modernize/avoid-common-blocks.rst
@@ -0,0 +1,26 @@
+.. title:: flang-tidy - modernize-avoid-common-blocks
+
+modernize-avoid-common-blocks
+=============================
+
+Detects the use of COMMON blocks, which were replaced by modules in Fortran 90 for data sharing. Using modules provides better encapsulation, type safety, and explicit interfaces.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+      integer :: a, b
+      common /data/ a, b  ! This will trigger a warning
+
+      a = 1
+      b = 2
+      call process()
+    end program
+
+    subroutine process()
+      implicit none
+      integer :: a, b
+      common /data/ a, b
+
+      print *, a, b
+    end subroutine
diff --git a/flang/tools/flang-tidy/modernize/AvoidCommonBlocks.cpp b/flang/tools/flang-tidy/modernize/AvoidCommonBlocks.cpp
new file mode 100644
index 0000000000000..f5831a20466f8
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/AvoidCommonBlocks.cpp
@@ -0,0 +1,21 @@
+//===--- AvoidCommonBlocks.cpp - flang-tidy -------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "AvoidCommonBlocks.h"
+
+namespace Fortran::tidy::modernize {
+
+using namespace parser::literals;
+void AvoidCommonBlocksCheck::Enter(const parser::CommonStmt &) {
+  if (context()->getSemanticsContext().location().has_value()) {
+    Say(context()->getSemanticsContext().location().value(),
+        "Common blocks are not recommended"_warn_en_US);
+  }
+}
+
+} // namespace Fortran::tidy::modernize
diff --git a/flang/tools/flang-tidy/modernize/AvoidCommonBlocks.h b/flang/tools/flang-tidy/modernize/AvoidCommonBlocks.h
new file mode 100644
index 0000000000000..f75f8f46850b6
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/AvoidCommonBlocks.h
@@ -0,0 +1,29 @@
+//===--- AvoidCommonBlocks.h - flang-tidy -----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDCOMMONBLOCKS_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDCOMMONBLOCKS_H
+
+#include "../FlangTidyCheck.h"
+
+namespace Fortran::tidy::modernize {
+
+/// This check verifies that COMMON blocks are avoided.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/avoid-common-blocks.html
+class AvoidCommonBlocksCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~AvoidCommonBlocksCheck() = default;
+  void Enter(const parser::CommonStmt &) override;
+};
+
+} // namespace Fortran::tidy::modernize
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDCOMMONBLOCKS_H
diff --git a/flang/tools/flang-tidy/modernize/CMakeLists.txt b/flang/tools/flang-tidy/modernize/CMakeLists.txt
index 4d8b152b17e22..d65c3931ea215 100644
--- a/flang/tools/flang-tidy/modernize/CMakeLists.txt
+++ b/flang/tools/flang-tidy/modernize/CMakeLists.txt
@@ -1,6 +1,7 @@
 add_flang_library(flangTidyModernizeModule STATIC
   AvoidAssignStmt.cpp
   AvoidBackspaceStmt.cpp
+  AvoidCommonBlocks.cpp
   ModernizeTidyModule.cpp
 
   LINK_LIBS
diff --git a/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
index 92ce7ad01c4ff..79d3cbaa43d45 100644
--- a/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
@@ -10,6 +10,7 @@
 #include "../FlangTidyModuleRegistry.h"
 #include "AvoidAssignStmt.h"
 #include "AvoidBackspaceStmt.h"
+#include "AvoidCommonBlocks.h"
 
 namespace Fortran::tidy {
 namespace modernize {
@@ -21,6 +22,8 @@ class ModernizeModule : public FlangTidyModule {
         "modernize-avoid-assign-stmt");
     CheckFactories.registerCheck<AvoidBackspaceStmtCheck>(
         "modernize-avoid-backspace-stmt");
+    CheckFactories.registerCheck<AvoidCommonBlocksCheck>(
+        "modernize-avoid-common-blocks");
   }
 };
 
diff --git a/flang/tools/test/flang-tidy/commonblock.f90 b/flang/tools/test/flang-tidy/commonblock.f90
new file mode 100644
index 0000000000000..58f0c502d321d
--- /dev/null
+++ b/flang/tools/test/flang-tidy/commonblock.f90
@@ -0,0 +1,6 @@
+! RUN: %check_flang_tidy %s modernize-avoid-common-blocks %t
+subroutine s
+  real :: x, y, z
+  common /c/ x, y, z
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Common blocks are not recommended
+end subroutine s

>From 5684c9c5d53f0433ceef5cf6b405752a82098d60 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:48:33 +0200
Subject: [PATCH 26/31] [flang-tidy][modernize] add avoid data-construct check

---
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../modernize/avoid-data-constructs.rst       | 18 ++++++++++++
 .../modernize/AvoidDataConstructs.cpp         | 22 ++++++++++++++
 .../modernize/AvoidDataConstructs.h           | 29 +++++++++++++++++++
 .../tools/flang-tidy/modernize/CMakeLists.txt |  1 +
 .../modernize/ModernizeTidyModule.cpp         |  3 ++
 flang/tools/test/flang-tidy/avoid-data.f90    | 11 +++++++
 7 files changed, 85 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/modernize/avoid-data-constructs.rst
 create mode 100644 flang/tools/flang-tidy/modernize/AvoidDataConstructs.cpp
 create mode 100644 flang/tools/flang-tidy/modernize/AvoidDataConstructs.h
 create mode 100644 flang/tools/test/flang-tidy/avoid-data.f90

diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index d68167cf05118..7b52b50ba8e39 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -31,3 +31,4 @@ Flang-Tidy Checks
    :doc:`modernize-avoid-assign-stmt <modernize/avoid-assign-stmt>`,
    :doc:`modernize-avoid-backspace-stmt <modernize/avoid-backspace-stmt>`,
    :doc:`modernize-avoid-common-blocks <modernize/avoid-common-blocks>`,
+   :doc:`modernize-avoid-data-constructs <modernize/avoid-data-constructs>`,
diff --git a/flang/tools/docs/flang-tidy/checks/modernize/avoid-data-constructs.rst b/flang/tools/docs/flang-tidy/checks/modernize/avoid-data-constructs.rst
new file mode 100644
index 0000000000000..eb2b49661f2af
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/modernize/avoid-data-constructs.rst
@@ -0,0 +1,18 @@
+.. title:: flang-tidy - modernize-avoid-data-constructs
+
+modernize-avoid-data-constructs
+===============================
+
+Warns about the use of DATA statements, which provide a less flexible and less clear way to initialize variables compared to modern initialization approaches.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+      integer :: array(3)
+
+      data array /1, 2, 3/  ! This will trigger a warning
+      ! Better: array = [1, 2, 3]
+
+      print *, array
+    end program
diff --git a/flang/tools/flang-tidy/modernize/AvoidDataConstructs.cpp b/flang/tools/flang-tidy/modernize/AvoidDataConstructs.cpp
new file mode 100644
index 0000000000000..c787c67d88626
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/AvoidDataConstructs.cpp
@@ -0,0 +1,22 @@
+//===--- AvoidDataConstructs.cpp - flang-tidy -----------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "AvoidDataConstructs.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::modernize {
+
+using namespace parser::literals;
+void AvoidDataConstructsCheck::Enter(const parser::DataStmt &) {
+  if (context()->getSemanticsContext().location().has_value()) {
+    Say(context()->getSemanticsContext().location().value(),
+        "Data statements are not recommended"_warn_en_US);
+  }
+}
+
+} // namespace Fortran::tidy::modernize
diff --git a/flang/tools/flang-tidy/modernize/AvoidDataConstructs.h b/flang/tools/flang-tidy/modernize/AvoidDataConstructs.h
new file mode 100644
index 0000000000000..bf301a5c4a14e
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/AvoidDataConstructs.h
@@ -0,0 +1,29 @@
+//===--- AvoidDataConstructs.h - flang-tidy ---------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDDATACONSTRUCTS_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDDATACONSTRUCTS_H
+
+#include "../FlangTidyCheck.h"
+
+namespace Fortran::tidy::modernize {
+
+/// This check verifies that DATA constructs are avoided.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/avoid-data-constructs.html
+class AvoidDataConstructsCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~AvoidDataConstructsCheck() = default;
+  void Enter(const parser::DataStmt &) override;
+};
+
+} // namespace Fortran::tidy::modernize
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDDATACONSTRUCTS_H
diff --git a/flang/tools/flang-tidy/modernize/CMakeLists.txt b/flang/tools/flang-tidy/modernize/CMakeLists.txt
index d65c3931ea215..a49c09f1ab831 100644
--- a/flang/tools/flang-tidy/modernize/CMakeLists.txt
+++ b/flang/tools/flang-tidy/modernize/CMakeLists.txt
@@ -2,6 +2,7 @@ add_flang_library(flangTidyModernizeModule STATIC
   AvoidAssignStmt.cpp
   AvoidBackspaceStmt.cpp
   AvoidCommonBlocks.cpp
+  AvoidDataConstructs.cpp
   ModernizeTidyModule.cpp
 
   LINK_LIBS
diff --git a/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
index 79d3cbaa43d45..9c43f11febc1e 100644
--- a/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
@@ -11,6 +11,7 @@
 #include "AvoidAssignStmt.h"
 #include "AvoidBackspaceStmt.h"
 #include "AvoidCommonBlocks.h"
+#include "AvoidDataConstructs.h"
 
 namespace Fortran::tidy {
 namespace modernize {
@@ -24,6 +25,8 @@ class ModernizeModule : public FlangTidyModule {
         "modernize-avoid-backspace-stmt");
     CheckFactories.registerCheck<AvoidCommonBlocksCheck>(
         "modernize-avoid-common-blocks");
+    CheckFactories.registerCheck<AvoidDataConstructsCheck>(
+        "modernize-avoid-data-constructs");
   }
 };
 
diff --git a/flang/tools/test/flang-tidy/avoid-data.f90 b/flang/tools/test/flang-tidy/avoid-data.f90
new file mode 100644
index 0000000000000..2b8d8541ca110
--- /dev/null
+++ b/flang/tools/test/flang-tidy/avoid-data.f90
@@ -0,0 +1,11 @@
+! RUN: %check_flang_tidy %s modernize-avoid-data-constructs %t
+program data_test
+  integer :: array(3)
+
+  data array /1, 2, 3/  ! This will trigger a warning
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Data statements are not recommended
+
+  ! Better: array = [1, 2, 3]
+
+  print *, array
+end program data_test

>From 880ff9e8be3f830b108cc8356403363f1f9f20b4 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:50:23 +0200
Subject: [PATCH 27/31] [flang-tidy][modernize] add avoid pause check

---
 flang/tools/docs/flang-tidy/checks/list.rst   |  1 +
 .../checks/modernize/avoid-pause-stmt.rst     | 16 ++++++++++
 .../flang-tidy/modernize/AvoidPauseStmt.cpp   | 22 ++++++++++++++
 .../flang-tidy/modernize/AvoidPauseStmt.h     | 30 +++++++++++++++++++
 .../tools/flang-tidy/modernize/CMakeLists.txt |  1 +
 .../modernize/ModernizeTidyModule.cpp         |  3 ++
 flang/tools/test/flang-tidy/avoid-pause.f90   | 11 +++++++
 7 files changed, 84 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/modernize/avoid-pause-stmt.rst
 create mode 100644 flang/tools/flang-tidy/modernize/AvoidPauseStmt.cpp
 create mode 100644 flang/tools/flang-tidy/modernize/AvoidPauseStmt.h
 create mode 100644 flang/tools/test/flang-tidy/avoid-pause.f90

diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 7b52b50ba8e39..fab8fd5bbf8ee 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -32,3 +32,4 @@ Flang-Tidy Checks
    :doc:`modernize-avoid-backspace-stmt <modernize/avoid-backspace-stmt>`,
    :doc:`modernize-avoid-common-blocks <modernize/avoid-common-blocks>`,
    :doc:`modernize-avoid-data-constructs <modernize/avoid-data-constructs>`,
+   :doc:`modernize-avoid-pause-stmt <modernize/avoid-pause-stmt>`,
diff --git a/flang/tools/docs/flang-tidy/checks/modernize/avoid-pause-stmt.rst b/flang/tools/docs/flang-tidy/checks/modernize/avoid-pause-stmt.rst
new file mode 100644
index 0000000000000..4828294a266fe
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/modernize/avoid-pause-stmt.rst
@@ -0,0 +1,16 @@
+.. title:: flang-tidy - modernize-avoid-pause-stmt
+
+modernize-avoid-pause-stmt
+==========================
+
+Identifies usage of the PAUSE statement, which was deprecated in Fortran 95 and removed from the Fortran 2018 standard. Modern code should use READ or other interactive techniques instead.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+
+      print *, "Processing data..."
+      pause  ! This will trigger a warning
+      print *, "Continuing execution..."
+    end program
diff --git a/flang/tools/flang-tidy/modernize/AvoidPauseStmt.cpp b/flang/tools/flang-tidy/modernize/AvoidPauseStmt.cpp
new file mode 100644
index 0000000000000..a9d37a1ebe282
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/AvoidPauseStmt.cpp
@@ -0,0 +1,22 @@
+//===--- AvoidPauseStmt.cpp - flang-tidy ----------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "AvoidPauseStmt.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::modernize {
+
+using namespace parser::literals;
+void AvoidPauseStmtCheck::Enter(const parser::PauseStmt &) {
+  if (context()->getSemanticsContext().location().has_value()) {
+    Say(context()->getSemanticsContext().location().value(),
+        "Pause statements are not recommended"_warn_en_US);
+  }
+}
+
+} // namespace Fortran::tidy::modernize
diff --git a/flang/tools/flang-tidy/modernize/AvoidPauseStmt.h b/flang/tools/flang-tidy/modernize/AvoidPauseStmt.h
new file mode 100644
index 0000000000000..abb32ed56e802
--- /dev/null
+++ b/flang/tools/flang-tidy/modernize/AvoidPauseStmt.h
@@ -0,0 +1,30 @@
+//===--- AvoidPauseStmt.h - flang-tidy --------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDPAUSESTMT_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDPAUSESTMT_H
+
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::modernize {
+
+/// This check verifies that PAUSE statements are avoided.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/avoid-pause-stmt.html
+class AvoidPauseStmtCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~AvoidPauseStmtCheck() = default;
+  void Enter(const parser::PauseStmt &) override;
+};
+
+} // namespace Fortran::tidy::modernize
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_MODERNIZE_AVOIDPAUSESTMT_H
diff --git a/flang/tools/flang-tidy/modernize/CMakeLists.txt b/flang/tools/flang-tidy/modernize/CMakeLists.txt
index a49c09f1ab831..834d11599db00 100644
--- a/flang/tools/flang-tidy/modernize/CMakeLists.txt
+++ b/flang/tools/flang-tidy/modernize/CMakeLists.txt
@@ -3,6 +3,7 @@ add_flang_library(flangTidyModernizeModule STATIC
   AvoidBackspaceStmt.cpp
   AvoidCommonBlocks.cpp
   AvoidDataConstructs.cpp
+  AvoidPauseStmt.cpp
   ModernizeTidyModule.cpp
 
   LINK_LIBS
diff --git a/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
index 9c43f11febc1e..9368c2e109369 100644
--- a/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/flang/tools/flang-tidy/modernize/ModernizeTidyModule.cpp
@@ -12,6 +12,7 @@
 #include "AvoidBackspaceStmt.h"
 #include "AvoidCommonBlocks.h"
 #include "AvoidDataConstructs.h"
+#include "AvoidPauseStmt.h"
 
 namespace Fortran::tidy {
 namespace modernize {
@@ -27,6 +28,8 @@ class ModernizeModule : public FlangTidyModule {
         "modernize-avoid-common-blocks");
     CheckFactories.registerCheck<AvoidDataConstructsCheck>(
         "modernize-avoid-data-constructs");
+    CheckFactories.registerCheck<AvoidPauseStmtCheck>(
+        "modernize-avoid-pause-stmt");
   }
 };
 
diff --git a/flang/tools/test/flang-tidy/avoid-pause.f90 b/flang/tools/test/flang-tidy/avoid-pause.f90
new file mode 100644
index 0000000000000..ea74a3c409935
--- /dev/null
+++ b/flang/tools/test/flang-tidy/avoid-pause.f90
@@ -0,0 +1,11 @@
+! RUN: %check_flang_tidy %s modernize-avoid-pause-stmt %t
+program pause_test
+  print *, "Processing data..."
+
+  pause  ! This will trigger a warning
+  ! CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Pause statements are not recommended
+
+  ! Better: use READ or other interactive techniques instead
+
+  print *, "Continuing execution..."
+end program pause_test

>From a60ad87d6b0624a1395cef6a7bde9dd33e6e99da Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:53:05 +0200
Subject: [PATCH 28/31] [flang-tidy][openmp] add openmp accumulator race check

---
 flang/tools/docs/flang-tidy/checks/list.rst   |   1 +
 .../checks/openmp/accumulator-race.rst        |  29 ++
 .../openmp/AccumulatorRaceCheck.cpp           | 265 ++++++++++++++++++
 .../flang-tidy/openmp/AccumulatorRaceCheck.h  |  42 +++
 flang/tools/flang-tidy/openmp/CMakeLists.txt  |   1 +
 .../flang-tidy/openmp/OpenMPTidyModule.cpp    |   6 +-
 .../test/flang-tidy/openmp-reduction01.f90    |  71 +++++
 7 files changed, 414 insertions(+), 1 deletion(-)
 create mode 100644 flang/tools/docs/flang-tidy/checks/openmp/accumulator-race.rst
 create mode 100644 flang/tools/flang-tidy/openmp/AccumulatorRaceCheck.cpp
 create mode 100644 flang/tools/flang-tidy/openmp/AccumulatorRaceCheck.h
 create mode 100644 flang/tools/test/flang-tidy/openmp-reduction01.f90

diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index fab8fd5bbf8ee..c319c165c30bb 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -33,3 +33,4 @@ Flang-Tidy Checks
    :doc:`modernize-avoid-common-blocks <modernize/avoid-common-blocks>`,
    :doc:`modernize-avoid-data-constructs <modernize/avoid-data-constructs>`,
    :doc:`modernize-avoid-pause-stmt <modernize/avoid-pause-stmt>`,
+   :doc:`openmp-accumulator-race <openmp/accumulator-race>`,
diff --git a/flang/tools/docs/flang-tidy/checks/openmp/accumulator-race.rst b/flang/tools/docs/flang-tidy/checks/openmp/accumulator-race.rst
new file mode 100644
index 0000000000000..7ffaaca90e19e
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/openmp/accumulator-race.rst
@@ -0,0 +1,29 @@
+.. title:: flang-tidy - openmp-accumulator-race
+
+openmp-accumulator-race
+=======================
+
+Detects potential race conditions in OpenMP parallel regions where variables are modified without proper protection. This check identifies assignments to shared variables that could lead to data races and inconsistent results in parallel execution.
+
+.. code-block:: fortran
+
+    program example
+      implicit none
+      integer :: sum = 0
+      integer :: i
+
+      !$omp parallel do
+      do i = 1, 100
+        sum = sum + i  ! This will trigger a warning - race condition
+      end do
+      !$omp end parallel do
+
+      !$omp parallel do
+      do i = 1, 100
+        !$omp atomic update
+        sum = sum + i  ! This is safe
+      end do
+      !$omp end parallel do
+
+      print *, "Sum:", sum
+    end program
diff --git a/flang/tools/flang-tidy/openmp/AccumulatorRaceCheck.cpp b/flang/tools/flang-tidy/openmp/AccumulatorRaceCheck.cpp
new file mode 100644
index 0000000000000..52dab7719b776
--- /dev/null
+++ b/flang/tools/flang-tidy/openmp/AccumulatorRaceCheck.cpp
@@ -0,0 +1,265 @@
+//===--- AccumulatorRaceCheck.cpp - flang-tidy ----------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "AccumulatorRaceCheck.h"
+#include "flang/Evaluate/check-expression.h"
+#include "flang/Evaluate/tools.h"
+#include "flang/Parser/parse-tree.h"
+#include "flang/Semantics/symbol.h"
+#include "flang/Semantics/tools.h"
+#include "llvm/ADT/SmallVector.h"
+#include <algorithm>
+#include <variant>
+#include <vector>
+
+namespace Fortran::tidy::openmp {
+
+using namespace parser::literals;
+
+static std::vector<llvm::SmallVector<const semantics::Symbol *, 4>>
+    currentPrivate{};
+
+void AccumulatorRaceCheck::Enter(
+    const parser::OpenMPBlockConstruct &construct) {
+  ++inParallelRegion_;
+
+  currentPrivate.push_back({});
+
+  const auto &directive = std::get<parser::OmpBeginBlockDirective>(construct.t);
+  const auto &clause = std::get<parser::OmpClauseList>(directive.t);
+
+  // only handle lastprivate, firstprivate, and private for now
+  for (const auto &clause : clause.v) {
+    if (std::holds_alternative<parser::OmpClause::Lastprivate>(clause.u)) {
+      const auto &lastprivateClause =
+          std::get<parser::OmpClause::Lastprivate>(clause.u);
+      const auto &ompObjectList =
+          std::get<parser::OmpObjectList>(lastprivateClause.v.t);
+      for (const auto &ompObject : ompObjectList.v) {
+
+        // TODO: is there a better way to do this?
+        if (const auto *name{std::get_if<parser::Name>(&ompObject.u)}) {
+          const auto *symbol = name->symbol;
+          if (symbol) {
+            currentPrivate.back().emplace_back(symbol);
+          }
+        }
+        // handle Designator -> DataRef -> Name
+        if (const auto *designator{
+                std::get_if<parser::Designator>(&ompObject.u)}) {
+          const auto *name = semantics::getDesignatorNameIfDataRef(*designator);
+          if (name) {
+            const auto *symbol = name->symbol;
+            if (symbol) {
+              currentPrivate.back().emplace_back(symbol);
+            }
+          }
+        }
+      }
+
+    } else if (std::holds_alternative<parser::OmpClause::Firstprivate>(
+                   clause.u)) {
+      const auto &firstprivateClause =
+          std::get<parser::OmpClause::Firstprivate>(clause.u);
+      const auto &ompObjectList = firstprivateClause.v;
+      for (const auto &ompObject : ompObjectList.v) {
+        // get the symbol, only do names for now
+        if (const auto *name{std::get_if<parser::Name>(&ompObject.u)}) {
+          const auto *symbol = name->symbol;
+          if (symbol) {
+            currentPrivate.back().emplace_back(symbol);
+          }
+        }
+        if (const auto *designator{
+                std::get_if<parser::Designator>(&ompObject.u)}) {
+          const auto *name = semantics::getDesignatorNameIfDataRef(*designator);
+          if (name) {
+            const auto *symbol = name->symbol;
+            if (symbol) {
+              currentPrivate.back().emplace_back(symbol);
+            }
+          }
+        }
+      }
+    } else if (std::holds_alternative<parser::OmpClause::Private>(clause.u)) {
+      const auto &privateClause =
+          std::get<parser::OmpClause::Private>(clause.u);
+      const auto &ompObjectList = privateClause.v;
+      for (const auto &ompObject : ompObjectList.v) {
+        // get the symbol, only do names for now
+        if (const auto *name{std::get_if<parser::Name>(&ompObject.u)}) {
+          const auto *symbol = name->symbol;
+          if (symbol) {
+            currentPrivate.back().emplace_back(symbol);
+          }
+        }
+        if (const auto *designator{
+                std::get_if<parser::Designator>(&ompObject.u)}) {
+          const auto *name = semantics::getDesignatorNameIfDataRef(*designator);
+          if (name) {
+            const auto *symbol = name->symbol;
+            if (symbol) {
+              currentPrivate.back().emplace_back(symbol);
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
+void AccumulatorRaceCheck::Leave(const parser::OpenMPBlockConstruct &) {
+  --inParallelRegion_;
+  currentPrivate.pop_back();
+}
+
+void AccumulatorRaceCheck::Enter(const parser::OpenMPLoopConstruct &construct) {
+  ++inParallelRegion_;
+
+  // extract all symbols
+  currentPrivate.push_back({}); // push a new private list
+
+  const auto &directive = std::get<parser::OmpBeginLoopDirective>(construct.t);
+  const auto &clause = std::get<parser::OmpClauseList>(directive.t);
+  for (const auto &clause : clause.v) {
+    if (std::holds_alternative<parser::OmpClause::Lastprivate>(clause.u)) {
+      const auto &lastprivateClause =
+          std::get<parser::OmpClause::Lastprivate>(clause.u);
+      const auto &ompObjectList =
+          std::get<parser::OmpObjectList>(lastprivateClause.v.t);
+      for (const auto &ompObject : ompObjectList.v) {
+        // get the symbol, only do names for now
+        if (const auto *name{std::get_if<parser::Name>(&ompObject.u)}) {
+          const auto *symbol = name->symbol;
+          if (symbol) {
+            currentPrivate.back().emplace_back(symbol);
+          }
+        }
+        if (const auto *designator{
+                std::get_if<parser::Designator>(&ompObject.u)}) {
+          const auto *name = semantics::getDesignatorNameIfDataRef(*designator);
+          if (name) {
+            const auto *symbol = name->symbol;
+            if (symbol) {
+              currentPrivate.back().emplace_back(symbol);
+            }
+          }
+        }
+      }
+
+    } else if (std::holds_alternative<parser::OmpClause::Firstprivate>(
+                   clause.u)) {
+      const auto &firstprivateClause =
+          std::get<parser::OmpClause::Firstprivate>(clause.u);
+      const auto &ompObjectList = firstprivateClause.v;
+      for (const auto &ompObject : ompObjectList.v) {
+        // get the symbol, only do names for now
+        if (const auto *name{std::get_if<parser::Name>(&ompObject.u)}) {
+          const auto *symbol = name->symbol;
+          if (symbol) {
+            currentPrivate.back().emplace_back(symbol);
+          }
+        }
+        if (const auto *designator{
+                std::get_if<parser::Designator>(&ompObject.u)}) {
+          const auto *name = semantics::getDesignatorNameIfDataRef(*designator);
+          if (name) {
+            const auto *symbol = name->symbol;
+            if (symbol) {
+              currentPrivate.back().emplace_back(symbol);
+            }
+          }
+        }
+      }
+    } else if (std::holds_alternative<parser::OmpClause::Private>(clause.u)) {
+      const auto &privateClause =
+          std::get<parser::OmpClause::Private>(clause.u);
+      const auto &ompObjectList = privateClause.v;
+      for (const auto &ompObject : ompObjectList.v) {
+        // get the symbol, only do names for now
+        if (const auto *name{std::get_if<parser::Name>(&ompObject.u)}) {
+          const auto *symbol = name->symbol;
+          if (symbol) {
+            currentPrivate.back().emplace_back(symbol);
+          }
+        }
+        if (const auto *designator{
+                std::get_if<parser::Designator>(&ompObject.u)}) {
+          const auto *name = semantics::getDesignatorNameIfDataRef(*designator);
+          if (name) {
+            const auto *symbol = name->symbol;
+            if (symbol) {
+              currentPrivate.back().emplace_back(symbol);
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
+void AccumulatorRaceCheck::Leave(const parser::OpenMPLoopConstruct &) {
+  --inParallelRegion_;
+  currentPrivate.pop_back();
+}
+
+void AccumulatorRaceCheck::Enter(const parser::OmpAtomicUpdate &) {
+  ++inAtomicUpdate_;
+}
+
+void AccumulatorRaceCheck::Leave(const parser::OmpAtomicUpdate &) {
+  --inAtomicUpdate_;
+}
+
+void AccumulatorRaceCheck::Enter(const parser::OpenMPCriticalConstruct &) {
+  ++inCriticalSection_;
+}
+
+void AccumulatorRaceCheck::Leave(const parser::OpenMPCriticalConstruct &) {
+  --inCriticalSection_;
+}
+
+void AccumulatorRaceCheck::Enter(const parser::AssignmentStmt &stmt) {
+  if (inParallelRegion_ && !inCriticalSection_ && !inAtomicUpdate_) {
+    const auto &var = std::get<parser::Variable>(stmt.t);
+    const auto &expr = std::get<parser::Expr>(stmt.t);
+
+    const auto *lhsExpr =
+        semantics::GetExpr(context()->getSemanticsContext(), var);
+    // if the lhs isnt a whole or component data ref (NO ARRAY), ignore
+    const semantics::Symbol *lhsSymbol =
+        evaluate::UnwrapWholeSymbolOrComponentDataRef(*lhsExpr);
+
+    if (!lhsSymbol) {
+      return;
+    }
+
+    // if the lhs is in any of the private lists, ignore (stack has no begin()
+    // iterator)
+    bool isPrivate =
+        std::any_of(currentPrivate.rbegin(), currentPrivate.rend(),
+                    [&lhsSymbol](const auto &privateList) {
+                      return std::find(privateList.begin(), privateList.end(),
+                                       lhsSymbol) != privateList.end();
+                    });
+
+    if (isPrivate) {
+      return;
+    }
+
+    const auto *rhsExpr =
+        semantics::GetExpr(context()->getSemanticsContext(), expr);
+
+    if (rhsExpr && !evaluate::IsConstantExpr(*rhsExpr) && lhsSymbol) {
+      Say(var.GetSource(), "possible race condition on '%s'"_warn_en_US,
+          lhsSymbol->name());
+    }
+  }
+}
+
+} // namespace Fortran::tidy::openmp
diff --git a/flang/tools/flang-tidy/openmp/AccumulatorRaceCheck.h b/flang/tools/flang-tidy/openmp/AccumulatorRaceCheck.h
new file mode 100644
index 0000000000000..859b202847c40
--- /dev/null
+++ b/flang/tools/flang-tidy/openmp/AccumulatorRaceCheck.h
@@ -0,0 +1,42 @@
+//===--- AccumulatorRaceCheck.h - flang-tidy --------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_OPENMP_ACCUMULATORRACECHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_OPENMP_ACCUMULATORRACECHECK_H
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::openmp {
+
+/// This check tries to detect potential race conditions in OpenMP accumulators.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/accumulator-race.html
+class AccumulatorRaceCheck : public virtual FlangTidyCheck {
+public:
+  using FlangTidyCheck::FlangTidyCheck;
+  virtual ~AccumulatorRaceCheck() = default;
+
+  void Enter(const parser::OpenMPBlockConstruct &) override;
+  void Leave(const parser::OpenMPBlockConstruct &) override;
+  void Enter(const parser::OpenMPLoopConstruct &) override;
+  void Leave(const parser::OpenMPLoopConstruct &) override;
+  void Enter(const parser::OmpAtomicUpdate &) override;
+  void Leave(const parser::OmpAtomicUpdate &) override;
+  void Enter(const parser::OpenMPCriticalConstruct &) override;
+  void Leave(const parser::OpenMPCriticalConstruct &) override;
+  void Enter(const parser::AssignmentStmt &) override;
+
+private:
+  int inParallelRegion_ = 0;
+  int inCriticalSection_ = 0;
+  int inAtomicUpdate_ = 0;
+};
+
+} // namespace Fortran::tidy::openmp
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_OPENMP_ACCUMULATORRACECHECK_H
diff --git a/flang/tools/flang-tidy/openmp/CMakeLists.txt b/flang/tools/flang-tidy/openmp/CMakeLists.txt
index 69e07c16a3c88..d2575dd92c2d4 100644
--- a/flang/tools/flang-tidy/openmp/CMakeLists.txt
+++ b/flang/tools/flang-tidy/openmp/CMakeLists.txt
@@ -1,4 +1,5 @@
 add_flang_library(flangTidyOpenMPModule STATIC
+  AccumulatorRaceCheck.cpp
   OpenMPTidyModule.cpp
 
   LINK_LIBS
diff --git a/flang/tools/flang-tidy/openmp/OpenMPTidyModule.cpp b/flang/tools/flang-tidy/openmp/OpenMPTidyModule.cpp
index 456bb3dbc6fbf..eab0a8548ee26 100644
--- a/flang/tools/flang-tidy/openmp/OpenMPTidyModule.cpp
+++ b/flang/tools/flang-tidy/openmp/OpenMPTidyModule.cpp
@@ -8,13 +8,17 @@
 
 #include "../FlangTidyModule.h"
 #include "../FlangTidyModuleRegistry.h"
+#include "AccumulatorRaceCheck.h"
 
 namespace Fortran::tidy {
 namespace openmp {
 
 class OpenMPModule : public FlangTidyModule {
 public:
-  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {}
+  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {
+    CheckFactories.registerCheck<AccumulatorRaceCheck>(
+        "openmp-accumulator-race");
+  }
 };
 
 } // namespace openmp
diff --git a/flang/tools/test/flang-tidy/openmp-reduction01.f90 b/flang/tools/test/flang-tidy/openmp-reduction01.f90
new file mode 100644
index 0000000000000..2b7b973f927d3
--- /dev/null
+++ b/flang/tools/test/flang-tidy/openmp-reduction01.f90
@@ -0,0 +1,71 @@
+ ! RUN: %check_flang_tidy %s openmp-accumulator-race %t -- --extra-arg=-fopenmp
+subroutine loop1(acc, N)
+  integer, intent(inout) :: acc
+  integer, intent(in) :: N
+  integer :: m
+  !$omp parallel
+  !$omp do
+  do m = 1, N
+     acc = acc + N
+     ! CHECK-MESSAGES: :[[@LINE-1]]:6: warning: possible race condition on 'acc'
+  end do
+  !$omp end parallel
+end subroutine loop1
+
+subroutine loop2(acc, N)
+  integer, intent(inout) :: acc
+  integer, intent(in) :: N
+  integer :: m
+  !$omp parallel do
+  do m = 1, N
+     !$omp critical
+     acc = acc + N
+     !$omp end critical
+  end do
+  !$omp end parallel do
+end subroutine loop2
+
+subroutine loop3(acc, N)
+  integer, intent(inout) :: acc
+  integer, intent(in) :: N
+  integer :: m
+  !$omp parallel do
+  do m = 1, N
+     !$omp atomic update
+     acc = acc + N
+  end do
+  !$omp end parallel do
+end subroutine loop3
+
+subroutine loop4(acc, N)
+  integer, intent(inout) :: acc
+  integer, intent(in) :: N
+  integer :: m
+  !$omp parallel do private(acc)
+  do m = 1, N
+     acc = acc + N
+  end do
+  !$omp end parallel do
+end subroutine loop4
+
+subroutine loop5(acc, N)
+  integer, intent(inout) :: acc
+  integer, intent(in) :: N
+  integer :: m
+  !$omp parallel do firstprivate(acc)
+  do m = 1, N
+     acc = acc + N
+  end do
+  !$omp end parallel do
+end subroutine loop5
+
+subroutine loop6(acc, N)
+  integer, intent(inout) :: acc
+  integer, intent(in) :: N
+  integer :: m
+  !$omp parallel do lastprivate(acc)
+  do m = 1, N
+     acc = acc + N
+  end do
+  !$omp end parallel do
+end subroutine loop6

>From 5384fe8c67e454b2d16dbf4fee5f748bab5f40b9 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:54:57 +0200
Subject: [PATCH 29/31] [flang-tidy][performance] add pure procedure check

---
 flang/tools/docs/flang-tidy/checks/list.rst   |   1 +
 .../checks/performance/pure-procedure.rst     |  24 ++
 .../flang-tidy/performance/CMakeLists.txt     |   1 +
 .../performance/PerformanceTidyModule.cpp     |   6 +-
 .../performance/PureProcedureCheck.cpp        | 293 ++++++++++++++++++
 .../performance/PureProcedureCheck.h          |  61 ++++
 .../tools/test/flang-tidy/pure-procedure.f90  |  25 ++
 7 files changed, 410 insertions(+), 1 deletion(-)
 create mode 100644 flang/tools/docs/flang-tidy/checks/performance/pure-procedure.rst
 create mode 100644 flang/tools/flang-tidy/performance/PureProcedureCheck.cpp
 create mode 100644 flang/tools/flang-tidy/performance/PureProcedureCheck.h
 create mode 100644 flang/tools/test/flang-tidy/pure-procedure.f90

diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index c319c165c30bb..89f4ac10b22e9 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -34,3 +34,4 @@ Flang-Tidy Checks
    :doc:`modernize-avoid-data-constructs <modernize/avoid-data-constructs>`,
    :doc:`modernize-avoid-pause-stmt <modernize/avoid-pause-stmt>`,
    :doc:`openmp-accumulator-race <openmp/accumulator-race>`,
+   :doc:`performance-pure-procedure <performance/pure-procedure>`,
diff --git a/flang/tools/docs/flang-tidy/checks/performance/pure-procedure.rst b/flang/tools/docs/flang-tidy/checks/performance/pure-procedure.rst
new file mode 100644
index 0000000000000..9e53a1e2c9f27
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/performance/pure-procedure.rst
@@ -0,0 +1,24 @@
+.. title:: flang-tidy - performance-pure-procedure
+
+performance-pure-procedure
+==========================
+
+Identifies procedures that could be declared as PURE but are not. PURE procedures have no side effects and can enable compiler optimizations, particularly for array operations and parallel processing. This check analyzes procedures and suggests adding the PURE attribute when possible.
+
+.. code-block:: fortran
+
+    ! This will trigger a warning - could be PURE
+    subroutine add(a, b, result)
+      implicit none
+      integer, intent(in) :: a, b
+      integer, intent(out) :: result
+      result = a + b
+    end subroutine
+
+    ! Fixed version
+    pure subroutine add_pure(a, b, result)
+      implicit none
+      integer, intent(in) :: a, b
+      integer, intent(out) :: result
+      result = a + b
+    end subroutine
diff --git a/flang/tools/flang-tidy/performance/CMakeLists.txt b/flang/tools/flang-tidy/performance/CMakeLists.txt
index 0a2690d24ea3a..8bcac0b322df3 100644
--- a/flang/tools/flang-tidy/performance/CMakeLists.txt
+++ b/flang/tools/flang-tidy/performance/CMakeLists.txt
@@ -1,5 +1,6 @@
 add_flang_library(flangTidyPerformanceModule STATIC
   PerformanceTidyModule.cpp
+  PureProcedureCheck.cpp
 
   LINK_LIBS
   FortranSupport
diff --git a/flang/tools/flang-tidy/performance/PerformanceTidyModule.cpp b/flang/tools/flang-tidy/performance/PerformanceTidyModule.cpp
index 70eda2ecf838e..e16c634d68db6 100644
--- a/flang/tools/flang-tidy/performance/PerformanceTidyModule.cpp
+++ b/flang/tools/flang-tidy/performance/PerformanceTidyModule.cpp
@@ -8,13 +8,17 @@
 
 #include "../FlangTidyModule.h"
 #include "../FlangTidyModuleRegistry.h"
+#include "PureProcedureCheck.h"
 
 namespace Fortran::tidy {
 namespace performance {
 
 class PerformanceTidyModule : public FlangTidyModule {
 public:
-  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {}
+  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {
+    CheckFactories.registerCheck<PureProcedureCheck>(
+        "performance-pure-procedure");
+  }
 };
 
 } // namespace performance
diff --git a/flang/tools/flang-tidy/performance/PureProcedureCheck.cpp b/flang/tools/flang-tidy/performance/PureProcedureCheck.cpp
new file mode 100644
index 0000000000000..61926baca3e8c
--- /dev/null
+++ b/flang/tools/flang-tidy/performance/PureProcedureCheck.cpp
@@ -0,0 +1,293 @@
+//===--- PureProcedureCheck.cpp - flang-tidy ------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "PureProcedureCheck.h"
+#include "../utils/SymbolUtils.h"
+#include "flang/Evaluate/tools.h"
+#include "flang/Semantics/scope.h"
+#include "flang/Semantics/semantics.h"
+#include "flang/Semantics/symbol.h"
+#include "flang/Semantics/tools.h"
+#include "flang/Semantics/type.h"
+
+namespace Fortran::tidy::performance {
+
+static void PopulateProcedures(
+    const semantics::Scope &scope,
+    std::unordered_map<const semantics::Symbol *, bool> &pureProcedures) {
+  if (scope.IsModuleFile())
+    return;
+
+  for (const auto &pair : scope) {
+    const semantics::Symbol &symbol{*pair.second};
+    const auto &ultimate = symbol.GetUltimate();
+    const auto *subprogramDetails =
+        ultimate.detailsIf<semantics::SubprogramDetails>();
+    if (semantics::IsProcedure(symbol) && !utils::IsFromModFileSafe(ultimate) &&
+        (subprogramDetails && !subprogramDetails->isInterface())) {
+      pureProcedures[&ultimate] = true;
+    }
+  }
+
+  for (const auto &child : scope.children()) {
+    PopulateProcedures(child, pureProcedures);
+  }
+}
+
+static bool CheckSymbolIsPure(const semantics::Symbol &symbol,
+                              const semantics::Scope &scope) {
+  if (scope.symbol()) {
+    if (const auto &details =
+            scope.symbol()->detailsIf<semantics::SubprogramDetails>();
+        !(details && details->isInterface()) &&
+        !semantics::FindCommonBlockContaining(symbol) && IsSaved(symbol)) {
+      return false;
+    }
+  }
+
+  if (symbol.attrs().test(semantics::Attr::VOLATILE) && IsDummy(symbol)) {
+    return false;
+  }
+
+  if (IsProcedure(symbol) && !IsPureProcedure(symbol) && IsDummy(symbol)) {
+    return false;
+  }
+
+  return true;
+}
+
+static void CheckPureSymbols(
+    const semantics::Scope &scope,
+    std::unordered_map<const semantics::Symbol *, bool> &pureProcedures) {
+
+  if (scope.IsModuleFile())
+    return;
+
+  if (!scope.IsTopLevel()) {
+    for (const auto &pair : scope) {
+      const semantics::Symbol &symbol{*pair.second};
+      const semantics::Scope &scope2{symbol.owner()};
+      const semantics::Scope &unit{GetProgramUnitContaining(scope2)};
+      // unit should not be an interface
+      if (!CheckSymbolIsPure(symbol, scope) &&
+          unit.symbol() != &symbol.GetUltimate()) {
+        pureProcedures[&unit.symbol()->GetUltimate()] = false;
+      }
+    }
+  }
+  for (const auto &child : scope.children()) {
+    CheckPureSymbols(child, pureProcedures);
+  }
+}
+
+static std::unordered_map<const semantics::Symbol *, const semantics::Symbol *>
+    procBindingDetailsSymbolsMap;
+
+static void MakeProcBindingSymbolSet(semantics::SemanticsContext &context,
+                                     const semantics::Scope &scope) {
+  for (const auto &pair : scope) {
+    const semantics::Symbol &symbol = *pair.second;
+    if (auto *details{symbol.detailsIf<semantics::ProcBindingDetails>()}) {
+      procBindingDetailsSymbolsMap[&details->symbol().GetUltimate()] = &symbol;
+    }
+  }
+
+  for (const semantics::Scope &child : scope.children()) {
+    MakeProcBindingSymbolSet(context, child);
+  }
+}
+
+PureProcedureCheck::PureProcedureCheck(llvm::StringRef name,
+                                       FlangTidyContext *context)
+    : FlangTidyCheck{name, context} {
+  MakeProcBindingSymbolSet(context->getSemanticsContext(),
+                           context->getSemanticsContext().globalScope());
+
+  PopulateProcedures(context->getSemanticsContext().globalScope(),
+                     pureProcedures_);
+  CheckPureSymbols(context->getSemanticsContext().globalScope(),
+                   pureProcedures_);
+}
+
+using namespace parser::literals;
+void PureProcedureCheck::SetImpure() {
+  const auto location{context()->getSemanticsContext().location()};
+  if (!location) {
+    return;
+  }
+
+  const semantics::Scope &scope{
+      context()->getSemanticsContext().FindScope(*location)};
+
+  if (scope.IsTopLevel())
+    return;
+
+  const semantics::Scope &unit{GetProgramUnitContaining(scope)};
+  const auto &ultimateSymbol = unit.symbol()->GetUltimate();
+
+  if (semantics::IsProcedure(unit)) {
+    pureProcedures_[&ultimateSymbol] = false;
+  }
+
+  // propagate impurity to other procedures
+  for (const auto &pair : procBindingDetailsSymbolsMap) {
+    if (pair.first == &ultimateSymbol) {
+      pureProcedures_[pair.second] = false;
+    }
+  }
+}
+
+// C1596: external I/O
+void PureProcedureCheck::Leave(const parser::BackspaceStmt &) { SetImpure(); }
+void PureProcedureCheck::Leave(const parser::CloseStmt &) { SetImpure(); }
+void PureProcedureCheck::Leave(const parser::EndfileStmt &) { SetImpure(); }
+void PureProcedureCheck::Leave(const parser::FlushStmt &) { SetImpure(); }
+void PureProcedureCheck::Leave(const parser::InquireStmt &) { SetImpure(); }
+void PureProcedureCheck::Leave(const parser::OpenStmt &) { SetImpure(); }
+void PureProcedureCheck::Leave(const parser::PrintStmt &) { SetImpure(); }
+void PureProcedureCheck::Leave(const parser::RewindStmt &) { SetImpure(); }
+void PureProcedureCheck::Leave(const parser::WaitStmt &) { SetImpure(); }
+// C1597: read/write
+void PureProcedureCheck::Leave(const parser::ReadStmt &) { SetImpure(); }
+void PureProcedureCheck::Leave(const parser::WriteStmt &) { SetImpure(); }
+
+// assignment
+static bool IsPointerDummyOfPureFunction(const semantics::Symbol &x) {
+  return IsPointerDummy(x) && FindPureProcedureContaining(x.owner()) &&
+         x.owner().symbol() && IsFunction(*x.owner().symbol());
+}
+
+static const char *WhyBaseObjectIsSuspicious(const semantics::Symbol &x,
+                                             const semantics::Scope &scope) {
+  if (IsHostAssociatedIntoSubprogram(x, scope)) {
+    return "host-associated";
+  }
+  if (IsUseAssociated(x, scope)) {
+    return "USE-associated";
+  }
+  if (IsPointerDummyOfPureFunction(x)) {
+    return "a POINTER dummy argument of a pure function";
+  }
+  if (IsIntentIn(x)) {
+    return "an INTENT(IN) dummy argument";
+  }
+  if (FindCommonBlockContaining(x)) {
+    return "in a COMMON block";
+  }
+  return nullptr;
+}
+
+static std::optional<std::string>
+GetPointerComponentDesignatorName(const semantics::SomeExpr &expr) {
+  if (const auto *derived{
+          evaluate::GetDerivedTypeSpec(evaluate::DynamicType::From(expr))}) {
+    semantics::PotentialAndPointerComponentIterator potentials{*derived};
+    if (auto pointer{std::find_if(potentials.begin(), potentials.end(),
+                                  semantics::IsPointer)}) {
+      return pointer.BuildResultDesignatorName();
+    }
+  }
+  return std::nullopt;
+}
+
+// C1593 (4)
+void PureProcedureCheck::Leave(const parser::AssignmentStmt &assignment) {
+  // get the rhs
+  const auto &rhs{std::get<parser::Expr>(assignment.t)};
+  // get the evaluate::Expr
+  const auto *expr{semantics::GetExpr(context()->getSemanticsContext(), rhs)};
+
+  const semantics::Scope &scope{
+      context()->getSemanticsContext().FindScope(rhs.source)};
+
+  if (const semantics::Symbol *base{GetFirstSymbol(expr)}) {
+    if (const char *why{
+            WhyBaseObjectIsSuspicious(base->GetUltimate(), scope)}) {
+      if (auto pointer{GetPointerComponentDesignatorName(*expr)}) {
+        // mark the procedure as impure
+        (void)why;
+        SetImpure();
+      }
+    }
+  }
+}
+
+// C1592
+void PureProcedureCheck::Leave(const parser::Name &n) {
+  if (n.symbol && n.symbol->attrs().test(semantics::Attr::VOLATILE)) {
+    SetImpure();
+  }
+}
+
+// C1598: pure procs cant have image control statements
+void PureProcedureCheck::Enter(const parser::ExecutableConstruct &exec) {
+  if (semantics::IsImageControlStmt(exec)) {
+    SetImpure();
+  }
+}
+
+// check Call Stmt
+void PureProcedureCheck::Enter(const parser::CallStmt &callStmt) {
+  const auto *procedureRef = callStmt.typedCall.get();
+  if (procedureRef) {
+    const auto *symbol{procedureRef->proc().GetSymbol()};
+    if (!symbol) {
+      return;
+    }
+
+    // if the called function isnt pure, we cant be pure
+    if (!semantics::IsPureProcedure(*symbol))
+      SetImpure();
+  }
+}
+
+void PureProcedureCheck::Leave(const parser::Program &program) {
+  // tell us about all the procedure that could be pure, but arent
+  for (const auto &pair : pureProcedures_) {
+    // it should be pure, but isnt - and its not intrinsic, and not elemental,
+    // and not an interface
+    // check if the symbol is the Ultimate symbol
+    const auto &symbol = pair.first->GetUltimate();
+    // if (symbol != *pair.first) {
+    //   continue;
+    // }
+
+    // make sure its not being mapped to from procBindingDetailsSymbolsMap
+    bool cont = false;
+    for (const auto &procBindingPair : procBindingDetailsSymbolsMap) {
+      if (procBindingPair.second == pair.first) {
+        cont = true;
+        break;
+      }
+    }
+    if (cont) {
+      continue;
+    }
+
+    if (utils::IsFromModFileSafe(symbol)) {
+      continue;
+    }
+
+    // TODO: skip interfaces
+    if (pair.second && !pair.first->attrs().test(semantics::Attr::PURE) &&
+        !pair.first->attrs().test(semantics::Attr::INTRINSIC) &&
+        !pair.first->attrs().test(semantics::Attr::ELEMENTAL) &&
+        !pair.first->attrs().test(semantics::Attr::ABSTRACT) &&
+        !pair.first->attrs().test(semantics::Attr::EXTERNAL) &&
+        !pair.first->IsFromModFile()
+        // if its been derived somewhere, we dont care
+        && procBindingDetailsSymbolsMap.find(pair.first) ==
+               procBindingDetailsSymbolsMap.end()) {
+      Say(pair.first->name(),
+          "Procedure '%s' could be PURE but is not"_warn_en_US,
+          pair.first->name());
+    }
+  }
+}
+
+} // namespace Fortran::tidy::performance
diff --git a/flang/tools/flang-tidy/performance/PureProcedureCheck.h b/flang/tools/flang-tidy/performance/PureProcedureCheck.h
new file mode 100644
index 0000000000000..826780829fa4a
--- /dev/null
+++ b/flang/tools/flang-tidy/performance/PureProcedureCheck.h
@@ -0,0 +1,61 @@
+//===--- PureProcedureCheck.h - flang-tidy ----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_PERFORMANCE_PUREPROCEDURECHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_PERFORMANCE_PUREPROCEDURECHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "../FlangTidyContext.h"
+#include "flang/Parser/parse-tree.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace Fortran::tidy::performance {
+
+/// This check warns about procedures that could be pure but are not.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/pure-procedure.html
+class PureProcedureCheck : public virtual FlangTidyCheck {
+public:
+  explicit PureProcedureCheck(llvm::StringRef name, FlangTidyContext *context);
+  virtual ~PureProcedureCheck() = default;
+  void SetImpure();
+
+  // I/O
+  void Leave(const parser::BackspaceStmt &) override;
+  void Leave(const parser::CloseStmt &) override;
+  void Leave(const parser::EndfileStmt &) override;
+  void Leave(const parser::FlushStmt &) override;
+  void Leave(const parser::InquireStmt &) override;
+  void Leave(const parser::OpenStmt &) override;
+  void Leave(const parser::PrintStmt &) override;
+  void Leave(const parser::ReadStmt &) override;
+  void Leave(const parser::RewindStmt &) override;
+  void Leave(const parser::WaitStmt &) override;
+  void Leave(const parser::WriteStmt &) override;
+
+  // Assignment
+  void Leave(const parser::AssignmentStmt &) override;
+
+  void Enter(const parser::ExecutableConstruct &) override;
+  void Enter(const parser::CallStmt &) override;
+
+  // ?
+  void Leave(const parser::Name &) override;
+
+  // Leave the whole program
+  void Leave(const parser::Program &) override;
+
+private:
+  // map of all procedures and their pure status
+  std::unordered_map<const semantics::Symbol *, bool> pureProcedures_;
+};
+
+} // namespace Fortran::tidy::performance
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_PERFORMANCE_PUREPROCEDURECHECK_H
diff --git a/flang/tools/test/flang-tidy/pure-procedure.f90 b/flang/tools/test/flang-tidy/pure-procedure.f90
new file mode 100644
index 0000000000000..9604d1a7e2316
--- /dev/null
+++ b/flang/tools/test/flang-tidy/pure-procedure.f90
@@ -0,0 +1,25 @@
+! RUN: %check_flang_tidy %s performance-pure-procedure %t
+module pure_test
+  implicit none
+contains
+  ! This function could be pure but isn't
+  ! CHECK-MESSAGES: :[[@LINE+1]]:12: warning: Procedure 'add' could be PURE but is not
+  function add(a, b) result(c)
+    integer, intent(in) :: a, b
+    integer :: c
+    c = a + b
+  end function add
+
+  ! I/O statements make this procedure impossible to be pure
+  subroutine print_sum(a, b)
+    integer, intent(in) :: a, b
+    print *, "Sum:", a + b
+  end subroutine print_sum
+
+  ! A properly declared pure function
+  pure function multiply(a, b) result(c)
+    integer, intent(in) :: a, b
+    integer :: c
+    c = a * b
+  end function multiply
+end module pure_test

>From 342e79fa5690c9ec30092e93f41b18e4cf528ea9 Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:56:51 +0200
Subject: [PATCH 30/31] [flang-tidy][readability] add function cognitive
 complexity check

---
 flang/tools/docs/flang-tidy/checks/list.rst   |   1 +
 .../function-cognitive-complexity.rst         |  45 ++++++
 .../flang-tidy/readability/CMakeLists.txt     |   1 +
 .../FunctionCognitiveComplexityCheck.cpp      | 144 ++++++++++++++++++
 .../FunctionCognitiveComplexityCheck.h        |  73 +++++++++
 .../readability/ReadabilityTidyModule.cpp     |   6 +-
 .../test/flang-tidy/function-complexity01.f90 | 128 ++++++++++++++++
 7 files changed, 397 insertions(+), 1 deletion(-)
 create mode 100644 flang/tools/docs/flang-tidy/checks/readability/function-cognitive-complexity.rst
 create mode 100644 flang/tools/flang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
 create mode 100644 flang/tools/flang-tidy/readability/FunctionCognitiveComplexityCheck.h
 create mode 100644 flang/tools/test/flang-tidy/function-complexity01.f90

diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index 89f4ac10b22e9..fb1c1aac34f26 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -35,3 +35,4 @@ Flang-Tidy Checks
    :doc:`modernize-avoid-pause-stmt <modernize/avoid-pause-stmt>`,
    :doc:`openmp-accumulator-race <openmp/accumulator-race>`,
    :doc:`performance-pure-procedure <performance/pure-procedure>`,
+   :doc:`readability-function-cognitive-complexity <readability/function-cognitive-complexity>`,
diff --git a/flang/tools/docs/flang-tidy/checks/readability/function-cognitive-complexity.rst b/flang/tools/docs/flang-tidy/checks/readability/function-cognitive-complexity.rst
new file mode 100644
index 0000000000000..e4264c6fa155b
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/readability/function-cognitive-complexity.rst
@@ -0,0 +1,45 @@
+.. title:: flang-tidy - readability-function-cognitive-complexity
+
+readability-function-cognitive-complexity
+=========================================
+
+Verifies that the cognitive complexity of a function or subroutine does not exceed a threshold (default: 25). Cognitive complexity is a measure of how difficult code is to understand based on nesting, control flow, and logical operations. This check helps maintain readable and maintainable code by identifying overly complex procedures.
+
+.. code-block:: fortran
+
+    ! This will trigger a warning due to high cognitive complexity
+    subroutine complex_procedure(arr, n, threshold)
+      implicit none
+      integer, intent(in) :: n, threshold
+      real, intent(inout) :: arr(n)
+      integer :: i, j, count
+
+      count = 0
+      do i = 1, n
+        if (arr(i) > threshold) then
+          do j = i, n
+            if (arr(j) > 0) then
+              if (arr(j) > arr(i)) then
+                arr(j) = arr(j) - arr(i)
+                if (arr(j) < threshold .and. arr(j) > 0) then
+                  count = count + 1
+                  if (count > n/2) then
+                    do while (arr(j) > 0.1)
+                      arr(j) = arr(j) * 0.9
+                    end do
+                  else if (count > n/3) then
+                    arr(j) = arr(j) * 0.8
+                  end if
+                end if
+              end if
+            end if
+          end do
+        else if (arr(i) < -threshold) then
+          do j = 1, i
+            if (arr(j) < 0 .and. arr(j) < arr(i)) then
+              arr(j) = arr(j) - arr(i)
+            end if
+          end do
+        end if
+      end do
+    end subroutine
diff --git a/flang/tools/flang-tidy/readability/CMakeLists.txt b/flang/tools/flang-tidy/readability/CMakeLists.txt
index 6f8e5df4127f2..4f6603802d503 100644
--- a/flang/tools/flang-tidy/readability/CMakeLists.txt
+++ b/flang/tools/flang-tidy/readability/CMakeLists.txt
@@ -1,4 +1,5 @@
 add_flang_library(flangTidyReadabilityModule STATIC
+  FunctionCognitiveComplexityCheck.cpp
   ReadabilityTidyModule.cpp
 
   LINK_LIBS
diff --git a/flang/tools/flang-tidy/readability/FunctionCognitiveComplexityCheck.cpp b/flang/tools/flang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
new file mode 100644
index 0000000000000..d6dedc0c9e56a
--- /dev/null
+++ b/flang/tools/flang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
@@ -0,0 +1,144 @@
+//===--- FunctionCognitiveComplexityCheck.cpp - flang-tidy ----------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "FunctionCognitiveComplexityCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::readability {
+
+using namespace parser::literals;
+
+FunctionCognitiveComplexityCheck::FunctionCognitiveComplexityCheck(
+    llvm::StringRef name, FlangTidyContext *context)
+    : FlangTidyCheck(name, context),
+      Threshold(Options.get("Threshold", DefaultThreshold)) {}
+
+void FunctionCognitiveComplexityCheck::storeOptions(
+    FlangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "Threshold", Threshold);
+}
+
+void FunctionCognitiveComplexityCheck::Enter(
+    const parser::SubroutineSubprogram &program) {
+  currentNestingLevel_ = -1; // start at -1 to account for the first block
+  maxNestingLevel_ = 0;
+  inProcedure_ = true;
+  cognitiveComplexity_ = 0;
+
+  currentProcLoc_ =
+      std::get<parser::Statement<parser::SubroutineStmt>>(program.t).source;
+}
+
+void FunctionCognitiveComplexityCheck::Leave(
+    const parser::SubroutineSubprogram &) {
+  CheckCognitiveComplexity();
+  inProcedure_ = false;
+}
+
+void FunctionCognitiveComplexityCheck::Enter(
+    const parser::FunctionSubprogram &stmt) {
+  currentNestingLevel_ = -1;
+  maxNestingLevel_ = 0;
+  inProcedure_ = true;
+  cognitiveComplexity_ = 0;
+
+  currentProcLoc_ =
+      std::get<parser::Statement<parser::FunctionStmt>>(stmt.t).source;
+}
+
+void FunctionCognitiveComplexityCheck::Leave(
+    const parser::FunctionSubprogram &) {
+  CheckCognitiveComplexity();
+  inProcedure_ = false;
+}
+
+void FunctionCognitiveComplexityCheck::Enter(const parser::DoConstruct &) {
+  cognitiveComplexity_ += (1 + currentNestingLevel_);
+}
+void FunctionCognitiveComplexityCheck::Enter(
+    const parser::IfConstruct &construct) {
+  cognitiveComplexity_ += (1 + currentNestingLevel_);
+
+  // for each if-then-else, increment the cognitive complexity
+  const auto &elseIf =
+      std::get<std::list<parser::IfConstruct::ElseIfBlock>>(construct.t);
+
+  cognitiveComplexity_ +=
+      (elseIf.size() * currentNestingLevel_ + elseIf.size());
+
+  // if there is an else, increment the cognitive complexity by 1 and the
+  // nesting level
+  if (std::get<std::optional<parser::IfConstruct::ElseBlock>>(construct.t)) {
+    cognitiveComplexity_ += (1 + currentNestingLevel_);
+  }
+}
+
+void FunctionCognitiveComplexityCheck::Enter(const parser::GotoStmt &) {
+  ++cognitiveComplexity_;
+}
+
+void FunctionCognitiveComplexityCheck::Enter(const parser::ComputedGotoStmt &) {
+  ++cognitiveComplexity_;
+}
+
+void FunctionCognitiveComplexityCheck::Enter(const parser::AssignedGotoStmt &) {
+  ++cognitiveComplexity_;
+}
+
+void FunctionCognitiveComplexityCheck::Enter(const parser::CaseConstruct &) {
+  cognitiveComplexity_ += (1 + currentNestingLevel_);
+}
+
+void FunctionCognitiveComplexityCheck::Enter(
+    const parser::SelectRankConstruct &) {
+  cognitiveComplexity_ += (1 + currentNestingLevel_);
+}
+
+void FunctionCognitiveComplexityCheck::Enter(
+    const parser::SelectTypeConstruct &) {
+  cognitiveComplexity_ += (1 + currentNestingLevel_);
+}
+
+void FunctionCognitiveComplexityCheck::Enter(const parser::Expr::AND &) {
+  cognitiveComplexity_ += (1 + currentNestingLevel_);
+}
+
+void FunctionCognitiveComplexityCheck::Enter(const parser::Expr::OR &) {
+  cognitiveComplexity_ += (1 + currentNestingLevel_);
+}
+
+void FunctionCognitiveComplexityCheck::Enter(
+    const parser::AssociateConstruct &) {
+  cognitiveComplexity_ += (1 + currentNestingLevel_);
+}
+
+void FunctionCognitiveComplexityCheck::Enter(const parser::Block &) {
+  if (inProcedure_) {
+    currentNestingLevel_++;
+    UpdateMaxNestingLevel();
+  }
+}
+void FunctionCognitiveComplexityCheck::Leave(const parser::Block &) {
+  if (inProcedure_ && currentNestingLevel_ > 0) {
+    currentNestingLevel_--;
+  }
+}
+
+void FunctionCognitiveComplexityCheck::UpdateMaxNestingLevel() {
+  maxNestingLevel_ = std::max(maxNestingLevel_, currentNestingLevel_);
+}
+
+void FunctionCognitiveComplexityCheck::CheckCognitiveComplexity() {
+  if (Threshold && cognitiveComplexity_ > Threshold) {
+    Say(currentProcLoc_,
+        "%s has a cognitive complexity of %d, which exceeds the threshold of %d"_warn_en_US,
+        currentProcLoc_, cognitiveComplexity_, Threshold.value());
+  }
+}
+
+} // namespace Fortran::tidy::readability
diff --git a/flang/tools/flang-tidy/readability/FunctionCognitiveComplexityCheck.h b/flang/tools/flang-tidy/readability/FunctionCognitiveComplexityCheck.h
new file mode 100644
index 0000000000000..4e8ecc04b7ac4
--- /dev/null
+++ b/flang/tools/flang-tidy/readability/FunctionCognitiveComplexityCheck.h
@@ -0,0 +1,73 @@
+//===--- FunctionCognitiveComplexityCheck.h - flang-tidy --------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_READABILITY_FUNCTIONCOGNITIVECOMPLEXITYCHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_READABILITY_FUNCTIONCOGNITIVECOMPLEXITYCHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::readability {
+
+/// This check verifies that the cognitive complexity of a function is
+/// not too high.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/function-cognitive-complexity.html
+class FunctionCognitiveComplexityCheck : public virtual FlangTidyCheck {
+public:
+  explicit FunctionCognitiveComplexityCheck(llvm::StringRef name,
+                                            FlangTidyContext *context);
+  virtual ~FunctionCognitiveComplexityCheck() = default;
+
+  void storeOptions(FlangTidyOptions::OptionMap &Opts) override;
+
+  void Enter(const parser::SubroutineSubprogram &) override;
+  void Leave(const parser::SubroutineSubprogram &) override;
+  void Enter(const parser::FunctionSubprogram &) override;
+  void Leave(const parser::FunctionSubprogram &) override;
+
+  // DoConstruct, IfConstruct & CaseConstruct
+  void Enter(const parser::DoConstruct &) override;
+  void Enter(const parser::IfConstruct &) override;
+  void Enter(const parser::CaseConstruct &) override;
+
+  // Boolean operators &&, ||
+  void Enter(const parser::Expr::AND &) override;
+  void Enter(const parser::Expr::OR &) override;
+
+  // Select Rank? Select Type? Associate?
+  void Enter(const parser::SelectRankConstruct &) override;
+  void Enter(const parser::SelectTypeConstruct &) override;
+  void Enter(const parser::AssociateConstruct &) override;
+
+  // Goto statements
+  void Enter(const parser::GotoStmt &) override;
+  void Enter(const parser::ComputedGotoStmt &) override;
+  void Enter(const parser::AssignedGotoStmt &) override;
+
+  void Enter(const parser::Block &) override;
+  void Leave(const parser::Block &) override;
+
+private:
+  const std::optional<unsigned> Threshold;
+
+  constexpr static unsigned DefaultThreshold = 25U;
+
+  int maxNestingLevel_;
+  int currentNestingLevel_;
+  int cognitiveComplexity_;
+  parser::CharBlock currentProcLoc_;
+  bool inProcedure_;
+  void UpdateMaxNestingLevel();
+  void CheckCognitiveComplexity();
+};
+
+} // namespace Fortran::tidy::readability
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_READABILITY_FUNCTIONCOGNITIVECOMPLEXITYCHECK_H
diff --git a/flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp b/flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp
index 1f217dd5eea4f..5e2ffc2c9b037 100644
--- a/flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp
+++ b/flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp
@@ -8,13 +8,17 @@
 
 #include "../FlangTidyModule.h"
 #include "../FlangTidyModuleRegistry.h"
+#include "FunctionCognitiveComplexityCheck.h"
 
 namespace Fortran::tidy {
 namespace readability {
 
 class ReadabilityTidyModule : public FlangTidyModule {
 public:
-  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {}
+  void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {
+    CheckFactories.registerCheck<FunctionCognitiveComplexityCheck>(
+        "readability-function-cognitive-complexity");
+  }
 };
 
 } // namespace readability
diff --git a/flang/tools/test/flang-tidy/function-complexity01.f90 b/flang/tools/test/flang-tidy/function-complexity01.f90
new file mode 100644
index 0000000000000..7c68b8510ae09
--- /dev/null
+++ b/flang/tools/test/flang-tidy/function-complexity01.f90
@@ -0,0 +1,128 @@
+! RUN: %check_flang_tidy %s readability-function-cognitive-complexity %t
+MODULE function_size_test
+  IMPLICIT NONE
+
+CONTAINS
+  SUBROUTINE simple_function(n, result)
+    INTEGER, INTENT(IN) :: n
+    INTEGER, INTENT(OUT) :: result
+    INTEGER :: i, temp
+
+    temp = 0
+    DO i = 1, n
+      IF (i > 5) THEN
+        temp = temp + i
+      END IF
+    END DO
+
+    result = temp
+  END SUBROUTINE simple_function
+
+  SUBROUTINE complex_function(arr, n, threshold, result)
+    INTEGER, INTENT(IN) :: arr(:,:), n, threshold
+    INTEGER, INTENT(OUT) :: result
+    INTEGER :: i, j, temp, count
+
+    temp = 0
+    count = 0
+
+    DO i = 1, n                                 ! Level 1
+      DO j = 1, n                               ! Level 2
+        IF (arr(i,j) > threshold) THEN          ! Level 3
+          IF (arr(i,j) < threshold * 2) THEN    ! Level 4
+            DO WHILE (temp < arr(i,j))          ! Level 5
+              IF (temp > 0) THEN                ! Level 6
+                temp = temp + 1
+                count = count + 1
+              END IF
+            END DO
+          END IF
+        END IF
+      END DO
+    END DO
+
+    result = count
+  END SUBROUTINE complex_function
+
+  ! CHECK-MESSAGES: :[[@LINE+1]]:3: warning: subroutine borderline_function(arr, n, result) has a cognitive complexity of 39, which exceeds the threshold of 25
+  SUBROUTINE borderline_function(arr, n, result)
+    INTEGER, INTENT(IN) :: arr(:), n
+    INTEGER, INTENT(OUT) :: result
+    INTEGER :: i, sum, count
+    LOGICAL :: found
+
+    sum = 0
+    count = 0
+    found = .FALSE.
+
+    DO i = 1, n                          ! Level 1
+      IF (arr(i) > 0) THEN               ! Level 2
+        DO WHILE (.NOT. found)           ! Level 3
+          IF (sum < 100) THEN            ! Level 4
+            IF (arr(i) > 10) THEN        ! Level 5
+              sum = sum + arr(i)
+              count = count + 1
+            END IF
+          END IF
+
+          found = (sum >= 100)
+        END DO
+      END IF
+    END DO
+
+    result = count
+  END SUBROUTINE borderline_function
+
+  ! CHECK-MESSAGES: :[[@LINE+1]]:3: warning: subroutine extremely_nested_function(x, result) has a cognitive complexity of 61, which exceeds the threshold of 25
+  SUBROUTINE extremely_nested_function(x, result)
+    INTEGER, INTENT(IN) :: x
+    INTEGER, INTENT(OUT) :: result
+    INTEGER :: i, j, k
+
+    result = 0
+
+    outer: DO i = 1, 10                        ! Level 1
+      middle: DO j = 1, 10                     ! Level 2
+        inner: DO k = 1, 10                    ! Level 3
+          IF (i*j*k > x) THEN                  ! Level 4
+            IF (i*j*k < x*2) THEN              ! Level 5
+              BLOCK                            ! Level 6
+                IF (MOD(i*j*k, 2) == 0) THEN   ! Level 7
+                  result = result + 1
+                END IF
+              END BLOCK
+            END IF
+          END IF
+        END DO inner
+      END DO middle
+    END DO outer
+
+  END SUBROUTINE extremely_nested_function
+
+  ! CHECK-MESSAGES: :[[@LINE+1]]:3: warning: subroutine case_function(x, y, result) has a cognitive complexity of 71, which exceeds the threshold of 25
+  SUBROUTINE case_function(x, y, result)
+    INTEGER, INTENT(IN) :: x, y
+    INTEGER, INTENT(OUT) :: result
+    INTEGER :: i
+
+    result = 0
+
+    DO i = 1, 10                           ! Level 1
+      SELECT CASE (i)                      ! Level 2
+        CASE (1:3)
+          IF (x > 0) THEN                  ! Level 3
+            SELECT CASE (y)                ! Level 4
+              CASE (1:5)
+                result = result + 1
+              CASE DEFAULT
+                result = result + 2
+            END SELECT
+          END IF
+        CASE DEFAULT
+          result = result + 3
+      END SELECT
+    END DO
+
+  END SUBROUTINE case_function
+
+END MODULE function_size_test

>From 0983a499f512aa0d29aae1e41b958745de5b472f Mon Sep 17 00:00:00 2001
From: Originns <68753984+Originns at users.noreply.github.com>
Date: Tue, 20 May 2025 13:58:23 +0200
Subject: [PATCH 31/31] [flang-tidy][readability] add function size check

---
 flang/tools/docs/flang-tidy/checks/list.rst   |   1 +
 .../checks/readability/function-size.rst      |  40 ++++
 .../flang-tidy/readability/CMakeLists.txt     |   1 +
 .../readability/FunctionSizeCheck.cpp         | 188 ++++++++++++++++++
 .../readability/FunctionSizeCheck.h           |  72 +++++++
 .../readability/ReadabilityTidyModule.cpp     |   3 +
 .../tools/test/flang-tidy/function-size01.f90 | 127 ++++++++++++
 7 files changed, 432 insertions(+)
 create mode 100644 flang/tools/docs/flang-tidy/checks/readability/function-size.rst
 create mode 100644 flang/tools/flang-tidy/readability/FunctionSizeCheck.cpp
 create mode 100644 flang/tools/flang-tidy/readability/FunctionSizeCheck.h
 create mode 100644 flang/tools/test/flang-tidy/function-size01.f90

diff --git a/flang/tools/docs/flang-tidy/checks/list.rst b/flang/tools/docs/flang-tidy/checks/list.rst
index fb1c1aac34f26..70008cabbeeda 100644
--- a/flang/tools/docs/flang-tidy/checks/list.rst
+++ b/flang/tools/docs/flang-tidy/checks/list.rst
@@ -36,3 +36,4 @@ Flang-Tidy Checks
    :doc:`openmp-accumulator-race <openmp/accumulator-race>`,
    :doc:`performance-pure-procedure <performance/pure-procedure>`,
    :doc:`readability-function-cognitive-complexity <readability/function-cognitive-complexity>`,
+   :doc:`readability-function-size <readability/function-size>`,
diff --git a/flang/tools/docs/flang-tidy/checks/readability/function-size.rst b/flang/tools/docs/flang-tidy/checks/readability/function-size.rst
new file mode 100644
index 0000000000000..77af584beb500
--- /dev/null
+++ b/flang/tools/docs/flang-tidy/checks/readability/function-size.rst
@@ -0,0 +1,40 @@
+.. title:: flang-tidy - readability-function-size
+
+readability-function-size
+=========================
+
+Enforces size constraints on functions and subroutines based on line count, nesting level, and number of dummy arguments. Default thresholds are 5 for nesting level and 5 for dummy arguments (line count threshold is configurable). This check helps maintain manageable and readable code by preventing procedures from growing too large or complex.
+
+.. code-block:: fortran
+
+    ! This will trigger warnings for excessive arguments and nesting
+    subroutine process_data(data1, data2, data3, data4, data5, data6, options)
+      implicit none
+      real, intent(in) :: data1(:), data2(:), data3(:)
+      real, intent(in) :: data4(:), data5(:), data6(:)
+      integer, intent(in) :: options
+      integer :: i, j, k, m, n
+
+      do i = 1, size(data1)
+        if (data1(i) > 0) then
+          do j = 1, size(data2)
+            if (data2(j) > data1(i)) then
+              do k = 1, size(data3)
+                if (data3(k) > data2(j)) then
+                  do m = 1, size(data4)
+                    if (data4(m) > data3(k)) then
+                      do n = 1, size(data5)
+                        if (data5(n) > data4(m)) then
+                          ! This is at nesting level 10, which exceeds the threshold
+                          print *, "Found match"
+                        end if
+                      end do
+                    end if
+                  end do
+                end if
+              end do
+            end if
+          end do
+        end if
+      end do
+    end subroutine
diff --git a/flang/tools/flang-tidy/readability/CMakeLists.txt b/flang/tools/flang-tidy/readability/CMakeLists.txt
index 4f6603802d503..3efce77d86f78 100644
--- a/flang/tools/flang-tidy/readability/CMakeLists.txt
+++ b/flang/tools/flang-tidy/readability/CMakeLists.txt
@@ -1,5 +1,6 @@
 add_flang_library(flangTidyReadabilityModule STATIC
   FunctionCognitiveComplexityCheck.cpp
+  FunctionSizeCheck.cpp
   ReadabilityTidyModule.cpp
 
   LINK_LIBS
diff --git a/flang/tools/flang-tidy/readability/FunctionSizeCheck.cpp b/flang/tools/flang-tidy/readability/FunctionSizeCheck.cpp
new file mode 100644
index 0000000000000..94d0869e1e27e
--- /dev/null
+++ b/flang/tools/flang-tidy/readability/FunctionSizeCheck.cpp
@@ -0,0 +1,188 @@
+//===--- FunctionSizeCheck.cpp - flang-tidy -------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "FunctionSizeCheck.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::readability {
+
+using namespace parser::literals;
+
+FunctionSizeCheck::FunctionSizeCheck(llvm::StringRef name,
+                                     FlangTidyContext *context)
+    : FlangTidyCheck(name, context),
+      LineThreshold(Options.get("LineThreshold", DefaultLineThreshold)),
+      ParameterThreshold(
+          Options.get("ParameterThreshold", DefaultParameterThreshold)),
+      NestingThreshold(
+          Options.get("NestingThreshold", DefaultNestingThreshold)),
+      inProcedure_(false), currentNestingLevel_(0), maxNestingLevel_(0) {}
+
+void FunctionSizeCheck::storeOptions(FlangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "LineThreshold", LineThreshold);
+  Options.store(Opts, "ParameterThreshold", ParameterThreshold);
+  Options.store(Opts, "NestingThreshold", NestingThreshold);
+}
+
+void FunctionSizeCheck::Enter(const parser::SubroutineSubprogram &program) {
+  currentNestingLevel_ = -1; // start at -1 to account for the subroutine itself
+  maxNestingLevel_ = 0;
+  inProcedure_ = true;
+
+  currentProcLoc_ =
+      std::get<parser::Statement<parser::SubroutineStmt>>(program.t).source;
+
+  if (ParameterThreshold) {
+    const auto &subroutineStmt =
+        std::get<parser::Statement<parser::SubroutineStmt>>(program.t)
+            .statement;
+    const auto &dummyArgs =
+        std::get<std::list<parser::DummyArg>>(subroutineStmt.t);
+    if ((int)dummyArgs.size() > ParameterThreshold) {
+      Say(currentProcLoc_,
+          "%s has %d dummy arguments, which exceeds the threshold of %d"_warn_en_US,
+          currentProcLoc_, dummyArgs.size(), ParameterThreshold.value());
+    }
+  }
+
+  if (LineThreshold) {
+    // get the end of the subroutine
+    const auto &endLoc =
+        std::get<parser::Statement<parser::EndSubroutineStmt>>(program.t)
+            .source;
+
+    const auto &cookedSources =
+        context()->getSemanticsContext().allCookedSources();
+
+    // get the source position of the end location
+    auto endProvenanceRange = cookedSources.GetProvenanceRange(endLoc);
+    auto startProvenanceRange =
+        cookedSources.GetProvenanceRange(currentProcLoc_);
+
+    if (!endProvenanceRange || !startProvenanceRange) {
+      return;
+    }
+
+    // get the source position of the end location
+    auto endSourcePosition = cookedSources.allSources().GetSourcePosition(
+        endProvenanceRange->start());
+    auto startSourcePosition = cookedSources.allSources().GetSourcePosition(
+        startProvenanceRange->start());
+
+    if (!endSourcePosition || !startSourcePosition) {
+      return;
+    }
+
+    auto lineCount = endSourcePosition->line - startSourcePosition->line;
+    if (lineCount > LineThreshold) {
+      Say(currentProcLoc_,
+          "%s has a line count of %d, which exceeds the threshold of %d"_warn_en_US,
+          currentProcLoc_, lineCount, LineThreshold.value());
+    }
+  }
+}
+
+void FunctionSizeCheck::Leave(const parser::SubroutineSubprogram &) {
+  CheckNestingThreshold();
+  inProcedure_ = false;
+}
+
+void FunctionSizeCheck::Enter(
+    const parser::FunctionSubprogram &functionSubprogram) {
+  currentNestingLevel_ = -1;
+  maxNestingLevel_ = 0;
+  inProcedure_ = true;
+
+  currentProcLoc_ =
+      std::get<parser::Statement<parser::FunctionStmt>>(functionSubprogram.t)
+          .source;
+
+  if (ParameterThreshold) {
+    const auto &functionStmt =
+        std::get<parser::Statement<parser::FunctionStmt>>(functionSubprogram.t)
+            .statement;
+    const auto &args = std::get<std::list<parser::Name>>(functionStmt.t);
+    if ((int)args.size() > ParameterThreshold) {
+      Say(currentProcLoc_,
+          "%s has %d dummy arguments, which exceeds the threshold of %d"_warn_en_US,
+          currentProcLoc_, args.size(), ParameterThreshold.value());
+    }
+  }
+
+  if (LineThreshold) {
+    // get the end of the subroutine
+    const auto &endLoc = std::get<parser::Statement<parser::EndFunctionStmt>>(
+                             functionSubprogram.t)
+                             .source;
+
+    const auto &cookedSources =
+        context()->getSemanticsContext().allCookedSources();
+
+    // get the source position of the end location
+    auto endProvenanceRange = cookedSources.GetProvenanceRange(endLoc);
+    auto startProvenanceRange =
+        cookedSources.GetProvenanceRange(currentProcLoc_);
+
+    if (!endProvenanceRange || !startProvenanceRange) {
+      return;
+    }
+
+    // get the source position of the end location
+    auto endSourcePosition = cookedSources.allSources().GetSourcePosition(
+        endProvenanceRange->start());
+    auto startSourcePosition = cookedSources.allSources().GetSourcePosition(
+        startProvenanceRange->start());
+
+    if (!endSourcePosition || !startSourcePosition) {
+      return;
+    }
+
+    auto lineCount = endSourcePosition->line - startSourcePosition->line;
+    if (lineCount > LineThreshold) {
+      Say(currentProcLoc_,
+          "%s has a line count of %d, which exceeds the threshold of %d"_warn_en_US,
+          currentProcLoc_, lineCount, LineThreshold.value());
+    }
+  }
+}
+
+void FunctionSizeCheck::Leave(const parser::FunctionSubprogram &) {
+  CheckNestingThreshold();
+  inProcedure_ = false;
+}
+
+void FunctionSizeCheck::Enter(const parser::Block &) {
+  if (inProcedure_) {
+    currentNestingLevel_++;
+    UpdateMaxNestingLevel();
+  }
+}
+
+void FunctionSizeCheck::Leave(const parser::Block &) {
+  if (inProcedure_ && currentNestingLevel_ > 0) {
+    currentNestingLevel_--;
+  }
+}
+
+void FunctionSizeCheck::UpdateMaxNestingLevel() {
+  maxNestingLevel_ = std::max(maxNestingLevel_, currentNestingLevel_);
+}
+
+void FunctionSizeCheck::CheckNestingThreshold() {
+  if (!NestingThreshold) {
+    return;
+  }
+
+  if (maxNestingLevel_ > NestingThreshold) {
+    Say(currentProcLoc_,
+        "%s has a nesting level of %d, which exceeds the threshold of %d"_warn_en_US,
+        currentProcLoc_, maxNestingLevel_, NestingThreshold.value());
+  }
+}
+
+} // namespace Fortran::tidy::readability
diff --git a/flang/tools/flang-tidy/readability/FunctionSizeCheck.h b/flang/tools/flang-tidy/readability/FunctionSizeCheck.h
new file mode 100644
index 0000000000000..b9221ed977ee8
--- /dev/null
+++ b/flang/tools/flang-tidy/readability/FunctionSizeCheck.h
@@ -0,0 +1,72 @@
+//===--- FunctionSizeCheck.h - flang-tidy -----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_FLANG_TOOLS_FLANG_TIDY_READABILITY_FUNCTIONSIZECHECK_H
+#define LLVM_FLANG_TOOLS_FLANG_TIDY_READABILITY_FUNCTIONSIZECHECK_H
+
+#include "../FlangTidyCheck.h"
+#include "flang/Parser/char-block.h"
+#include "flang/Parser/parse-tree.h"
+
+namespace Fortran::tidy::readability {
+
+/// This check verifies that the size of functions and subroutines is within a
+/// certain threshold.
+///
+/// For the user-facing documentation see:
+/// https://flang.llvm.org/@PLACEHOLDER@/function-size.html
+class FunctionSizeCheck : public virtual FlangTidyCheck {
+public:
+  explicit FunctionSizeCheck(llvm::StringRef name, FlangTidyContext *context);
+  virtual ~FunctionSizeCheck() = default;
+
+  void storeOptions(FlangTidyOptions::OptionMap &Opts) override;
+
+  void Enter(const parser::SubroutineSubprogram &) override;
+  void Leave(const parser::SubroutineSubprogram &) override;
+  void Enter(const parser::FunctionSubprogram &) override;
+  void Leave(const parser::FunctionSubprogram &) override;
+
+  void Enter(const parser::Block &) override;
+  void Leave(const parser::Block &) override;
+
+private:
+  void UpdateMaxNestingLevel();
+  void CheckNestingThreshold();
+
+  const std::optional<unsigned> LineThreshold;
+  const std::optional<unsigned> ParameterThreshold;
+  const std::optional<unsigned> NestingThreshold;
+
+  static constexpr std::optional<unsigned> DefaultLineThreshold = std::nullopt;
+  static constexpr std::optional<unsigned> DefaultParameterThreshold =
+      std::nullopt;
+  static constexpr std::optional<unsigned> DefaultNestingThreshold =
+      std::nullopt;
+
+  bool inProcedure_ = false;
+  int currentNestingLevel_ = 0;
+  int maxNestingLevel_ = 0;
+  parser::CharBlock currentProcLoc_;
+};
+
+/*
+ * TODO: StatementThreshold, BranchThreshold, VariableThreshold
+ LineThreshold(Options.get("LineThreshold", DefaultLineThreshold)),
+ (
+     Options.get("StatementThreshold", DefaultStatementThreshold)),
+ ParameterThreshold(
+     Options.get("ParameterThreshold", DefaultParameterThreshold)),
+ NestingThreshold(
+     Options.get("NestingThreshold", DefaultNestingThreshold)),
+ *
+ */
+
+} // namespace Fortran::tidy::readability
+
+#endif // LLVM_FLANG_TOOLS_FLANG_TIDY_READABILITY_FUNCTIONSIZECHECK_H
diff --git a/flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp b/flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp
index 5e2ffc2c9b037..0fa3303052f30 100644
--- a/flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp
+++ b/flang/tools/flang-tidy/readability/ReadabilityTidyModule.cpp
@@ -9,6 +9,7 @@
 #include "../FlangTidyModule.h"
 #include "../FlangTidyModuleRegistry.h"
 #include "FunctionCognitiveComplexityCheck.h"
+#include "FunctionSizeCheck.h"
 
 namespace Fortran::tidy {
 namespace readability {
@@ -18,6 +19,8 @@ class ReadabilityTidyModule : public FlangTidyModule {
   void addCheckFactories(FlangTidyCheckFactories &CheckFactories) override {
     CheckFactories.registerCheck<FunctionCognitiveComplexityCheck>(
         "readability-function-cognitive-complexity");
+    CheckFactories.registerCheck<FunctionSizeCheck>(
+        "readability-function-size");
   }
 };
 
diff --git a/flang/tools/test/flang-tidy/function-size01.f90 b/flang/tools/test/flang-tidy/function-size01.f90
new file mode 100644
index 0000000000000..5945b21df011f
--- /dev/null
+++ b/flang/tools/test/flang-tidy/function-size01.f90
@@ -0,0 +1,127 @@
+! RUN: %check_flang_tidy %s readability-function-size %t
+MODULE function_size_test
+  IMPLICIT NONE
+
+CONTAINS
+  SUBROUTINE simple_function(n, result)
+    INTEGER, INTENT(IN) :: n
+    INTEGER, INTENT(OUT) :: result
+    INTEGER :: i, temp
+
+    temp = 0
+    DO i = 1, n
+      IF (i > 5) THEN
+        temp = temp + i
+      END IF
+    END DO
+
+    result = temp
+  END SUBROUTINE simple_function
+
+  ! CHECK-MESSAGES: :[[@LINE+1]]:3: warning: subroutine complex_function(arr, n, threshold, result) has a nesting level of 6, which exceeds the threshold of 5
+  SUBROUTINE complex_function(arr, n, threshold, result)
+    INTEGER, INTENT(IN) :: arr(:,:), n, threshold
+    INTEGER, INTENT(OUT) :: result
+    INTEGER :: i, j, temp, count
+
+    temp = 0
+    count = 0
+
+    DO i = 1, n                                 ! Level 1
+      DO j = 1, n                               ! Level 2
+        IF (arr(i,j) > threshold) THEN          ! Level 3
+          IF (arr(i,j) < threshold * 2) THEN    ! Level 4
+            DO WHILE (temp < arr(i,j))          ! Level 5
+              IF (temp > 0) THEN                ! Level 6
+                temp = temp + 1
+                count = count + 1
+              END IF
+            END DO
+          END IF
+        END IF
+      END DO
+    END DO
+
+    result = count
+  END SUBROUTINE complex_function
+
+  SUBROUTINE borderline_function(arr, n, result)
+    INTEGER, INTENT(IN) :: arr(:), n
+    INTEGER, INTENT(OUT) :: result
+    INTEGER :: i, sum, count
+    LOGICAL :: found
+
+    sum = 0
+    count = 0
+    found = .FALSE.
+
+    DO i = 1, n                          ! Level 1
+      IF (arr(i) > 0) THEN               ! Level 2
+        DO WHILE (.NOT. found)           ! Level 3
+          IF (sum < 100) THEN            ! Level 4
+            IF (arr(i) > 10) THEN        ! Level 5
+              sum = sum + arr(i)
+              count = count + 1
+            END IF
+          END IF
+
+          found = (sum >= 100)
+        END DO
+      END IF
+    END DO
+
+    result = count
+  END SUBROUTINE borderline_function
+
+  ! CHECK-MESSAGES: :[[@LINE+1]]:3: warning: subroutine extremely_nested_function(x, result) has a nesting level of 7, which exceeds the threshold of 5
+  SUBROUTINE extremely_nested_function(x, result)
+    INTEGER, INTENT(IN) :: x
+    INTEGER, INTENT(OUT) :: result
+    INTEGER :: i, j, k
+
+    result = 0
+
+    outer: DO i = 1, 10                        ! Level 1
+      middle: DO j = 1, 10                     ! Level 2
+        inner: DO k = 1, 10                    ! Level 3
+          IF (i*j*k > x) THEN                  ! Level 4
+            IF (i*j*k < x*2) THEN              ! Level 5
+              BLOCK                            ! Level 6
+                IF (MOD(i*j*k, 2) == 0) THEN   ! Level 7
+                  result = result + 1
+                END IF
+              END BLOCK
+            END IF
+          END IF
+        END DO inner
+      END DO middle
+    END DO outer
+
+  END SUBROUTINE extremely_nested_function
+
+  SUBROUTINE case_function(x, y, result)
+    INTEGER, INTENT(IN) :: x, y
+    INTEGER, INTENT(OUT) :: result
+    INTEGER :: i
+
+    result = 0
+
+    DO i = 1, 10                           ! Level 1
+      SELECT CASE (i)                      ! Level 2
+        CASE (1:3)
+          IF (x > 0) THEN                  ! Level 3
+            SELECT CASE (y)                ! Level 4
+              CASE (1:5)
+                result = result + 1
+              CASE DEFAULT
+                result = result + 2
+            END SELECT
+          END IF
+        CASE DEFAULT
+          result = result + 3
+      END SELECT
+    END DO
+
+  END SUBROUTINE case_function
+
+END MODULE function_size_test



More information about the flang-commits mailing list