[clang] [llvm] pull (PR #93500)

via cfe-commits cfe-commits at lists.llvm.org
Mon May 27 20:24:36 PDT 2024


https://github.com/cratelschen created https://github.com/llvm/llvm-project/pull/93500

None

>From 421aa0371f834b6ebfad204c85f65695f8de2ae7 Mon Sep 17 00:00:00 2001
From: CratelsChen <cratels at 126.com>
Date: Wed, 10 Apr 2024 19:54:19 +0800
Subject: [PATCH 1/6] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20kickoff=20=E6=96=87?=
 =?UTF-8?q?=E6=A1=A3?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 kick-off.md | 8 ++++++++
 1 file changed, 8 insertions(+)
 create mode 100644 kick-off.md

diff --git a/kick-off.md b/kick-off.md
new file mode 100644
index 0000000000000..97084536fe1eb
--- /dev/null
+++ b/kick-off.md
@@ -0,0 +1,8 @@
+# configuration
+> cmake -S llvm -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
+
+LLVM的工程很大,源码的源头一般认为是 llvm 文件夹,可以看到这里也是从其开始寻找 cmake 文件的。
+当前要求配置时必须制定 build 类型。
+
+# build
+> cmake --build build

>From 443a75daed4a0642e0e8799cf54ac1379a4ae9b9 Mon Sep 17 00:00:00 2001
From: CratelsChen <cratels at 126.com>
Date: Wed, 10 Apr 2024 22:13:29 +0800
Subject: [PATCH 2/6] add comments for cmake file

---
 llvm/CMakeLists.txt | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)

diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index d511376e18ba5..2efcb5a0f1a0b 100644
--- a/llvm/CMakeLists.txt
+++ b/llvm/CMakeLists.txt
@@ -1,24 +1,45 @@
+# -S 指定目录为 llvm 时,cmake 就会从当前路径中查找 CMakeLists.txt 并执行
+#
+# 项目入口处
+#
 # See docs/CMake.html for instructions about how to build LLVM with CMake.
 
+# 指定当前工程支持的 cmake 语法的最小版本。该之前的语法旧语法就不再支持了。
 cmake_minimum_required(VERSION 3.20.0)
 
+# 设置变量LLVM_COMMON_CMAKE_UTILS执行外层 cmake 文件夹的路径。
+# 该路径下面的 Modules 文件夹下有很多 .cmake 文件后续可能会用。
 set(LLVM_COMMON_CMAKE_UTILS ${CMAKE_CURRENT_SOURCE_DIR}/../cmake)
+message(${LLVM_COMMON_CMAKE_UTILS})
+
+message("将 policy 文件引入当前 cmake 文件")
 include(${LLVM_COMMON_CMAKE_UTILS}/Modules/CMakePolicy.cmake
   NO_POLICY_SCOPE)
 
 # Builds with custom install names and installation rpath setups may not work
 # in the build tree. Allow these cases to use CMake's default build tree
 # behavior by setting `LLVM_NO_INSTALL_NAME_DIR_FOR_BUILD_TREE` to do this.
+# 定义 option:LLVM_NO_INSTALL_NAME_DIR_FOR_BUILD_TREE,允许开发者在 build 的时候通过-DOPTION 设置不同的值来影响编译过程。
 option(LLVM_NO_INSTALL_NAME_DIR_FOR_BUILD_TREE "If set, use CMake's default build tree install name directory logic (Darwin only)" OFF)
+
+# 将缓存的变量标记为高级变量。其中,高级变量指的是那些在CMake GUI中,只有当“显示高级选项”被打开时才会被显示的变量。如果CLEAR是第一个选项,参数中的高级变量将变回
+# 非高级变量。如果FORCE是第一个选项,参数中的变量会被提升为高级变量。如果两者都未出现,新的变量会被标记为高级变量;如果这个变量已经是高级/非高级状态的话,它将会维
+# 持原状。该命令在脚本中无效
+# 高级选项通常是那些不经常使用的选项,或者对大多数用户来说可能不重要的选项。
 mark_as_advanced(LLVM_NO_INSTALL_NAME_DIR_FOR_BUILD_TREE)
 if(NOT LLVM_NO_INSTALL_NAME_DIR_FOR_BUILD_TREE)
   set(CMAKE_BUILD_WITH_INSTALL_NAME_DIR ON)
 endif()
 
+message("将 LLVM 的版本信息引入")
 include(${LLVM_COMMON_CMAKE_UTILS}/Modules/LLVMVersion.cmake)
 
+# 设置当前目录和子目录的属性
+# 该属性只在当前目录以及其子目录起作用
+# set_property:设置私属性值,在当前作用于起作用
 set_directory_properties(PROPERTIES LLVM_VERSION_MAJOR "${LLVM_VERSION_MAJOR}")
 
+
 if (NOT PACKAGE_VERSION)
   set(PACKAGE_VERSION
     "${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}${LLVM_VERSION_SUFFIX}")

>From 7766ae8f97fffe7a592f25d0bdb4abd18133ca90 Mon Sep 17 00:00:00 2001
From: CratelsChen <cratels at 126.com>
Date: Wed, 10 Apr 2024 23:48:32 +0800
Subject: [PATCH 3/6] add comments for cmake file

---
 llvm/CMakeLists.txt | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index 2efcb5a0f1a0b..8f8cfbcf6a1e9 100644
--- a/llvm/CMakeLists.txt
+++ b/llvm/CMakeLists.txt
@@ -12,6 +12,15 @@ cmake_minimum_required(VERSION 3.20.0)
 set(LLVM_COMMON_CMAKE_UTILS ${CMAKE_CURRENT_SOURCE_DIR}/../cmake)
 message(${LLVM_COMMON_CMAKE_UTILS})
 
+# message的信息种类:
+# (无) = 重要消息;
+#  STATUS = 非重要消息;
+#  WARNING = CMake 警告, 会继续执行;
+#  AUTHOR_WARNING = CMake 警告 (dev), 会继续执行;
+#  SEND_ERROR = CMake 错误, 继续执行,但是会跳过生成的步骤;
+#  FATAL_ERROR = CMake 错误, 终止所有处理过程;
+
+
 message("将 policy 文件引入当前 cmake 文件")
 include(${LLVM_COMMON_CMAKE_UTILS}/Modules/CMakePolicy.cmake
   NO_POLICY_SCOPE)
@@ -50,6 +59,7 @@ if(NOT DEFINED LLVM_SHLIB_SYMBOL_VERSION)
   set(LLVM_SHLIB_SYMBOL_VERSION "LLVM_${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}")
 endif()
 
+# 如果在 windows 平台下使用生成器Visual Studio,输出 warning 信息
 if ((CMAKE_GENERATOR MATCHES "Visual Studio") AND (MSVC_TOOLSET_VERSION LESS 142) AND (CMAKE_GENERATOR_TOOLSET STREQUAL ""))
   message(WARNING "Visual Studio generators use the x86 host compiler by "
                   "default, even for 64-bit targets. This can result in linker "
@@ -57,16 +67,19 @@ if ((CMAKE_GENERATOR MATCHES "Visual Studio") AND (MSVC_TOOLSET_VERSION LESS 142
                   "host compiler, pass -Thost=x64 on the CMake command line.")
 endif()
 
+# 如果在 MacOS 平台下使用生成器XCode,且不是苹果的芯片架构,设置架构信息为x86_64
 if (CMAKE_GENERATOR STREQUAL "Xcode" AND NOT CMAKE_OSX_ARCHITECTURES)
   # Some CMake features like object libraries get confused if you don't
   # explicitly specify an architecture setting with the Xcode generator.
   set(CMAKE_OSX_ARCHITECTURES "x86_64")
 endif()
 
+# 设置 project 项目名称,项目版本以及实现语言
 project(LLVM
   VERSION ${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}
   LANGUAGES C CXX ASM)
 
+# 设置 install 的路径
 if (NOT DEFINED CMAKE_INSTALL_LIBDIR AND DEFINED LLVM_LIBDIR_SUFFIX)
   # Must go before `include(GNUInstallDirs)`.
   set(CMAKE_INSTALL_LIBDIR "lib${LLVM_LIBDIR_SUFFIX}")
@@ -78,6 +91,7 @@ set(LLVM_LIBDIR_SUFFIX "" CACHE STRING "Define suffix of library directory name
 # Must go after `project(..)`.
 include(GNUInstallDirs)
 
+# 设置LLVM 使用 C++的标准版本
 # This C++ standard is required to build LLVM.
 set(LLVM_REQUIRED_CXX_STANDARD 17)
 
@@ -105,6 +119,7 @@ else()
   set(CMAKE_CXX_EXTENSIONS NO)
 endif()
 
+# 如果未设置 cmake 的 build 类型且未设置 configuration 类型
 if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
   message(FATAL_ERROR "
 No build type selected. You need to pass -DCMAKE_BUILD_TYPE=<type> in order to configure LLVM.
@@ -135,6 +150,7 @@ endif()
 # LLVM_EXTERNAL_${project}_SOURCE_DIR using LLVM_ALL_PROJECTS
 # This allows an easy way of setting up a build directory for llvm and another
 # one for llvm+clang+... using the same sources.
+# 设置 LLVM 工程中的所有的子工程名称,其实是 target
 set(LLVM_ALL_PROJECTS "bolt;clang;clang-tools-extra;compiler-rt;cross-project-tests;libc;libclc;lld;lldb;mlir;openmp;polly;pstl")
 # The flang project is not yet part of "all" projects (see C++ requirements)
 set(LLVM_EXTRA_PROJECTS "flang")

>From 9d78626f91110a433093d4b359c01c078038114c Mon Sep 17 00:00:00 2001
From: CratelsChen <cratels at 126.com>
Date: Fri, 12 Apr 2024 00:02:08 +0800
Subject: [PATCH 4/6] add comments

---
 clang/tools/driver/driver.cpp | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)

diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index 83b5bbb71f521..6cfb55892dd78 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -69,7 +69,7 @@ std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
 
   // This just needs to be some symbol in the binary; C++ doesn't
   // allow taking the address of ::main however.
-  void *P = (void*) (intptr_t) GetExecutablePath;
+  void *P = (void *)(intptr_t)GetExecutablePath;
   return llvm::sys::fs::getMainExecutable(Argv0, P);
 }
 
@@ -102,10 +102,10 @@ static void insertTargetAndModeArgs(const ParsedClangName &NameParts,
   }
 
   if (NameParts.TargetIsValid) {
-    const char *arr[] = {"-target", GetStableCStr(SavedStrings,
-                                                  NameParts.TargetPrefix)};
-    ArgVector.insert(ArgVector.begin() + InsertionPoint,
-                     std::begin(arr), std::end(arr));
+    const char *arr[] = {"-target",
+                         GetStableCStr(SavedStrings, NameParts.TargetPrefix)};
+    ArgVector.insert(ArgVector.begin() + InsertionPoint, std::begin(arr),
+                     std::end(arr));
   }
 }
 
@@ -225,6 +225,8 @@ static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV,
   return 1;
 }
 
+// Cratels:  build 目录下会生成一个 main 方法。在该方法中调用 clang_main
+// 这里是所有程序的入口
 int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
   noteBottomOfStack();
   llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
@@ -316,8 +318,8 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
       CreateAndPopulateDiagOpts(Args);
 
-  TextDiagnosticPrinter *DiagClient
-    = new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
+  TextDiagnosticPrinter *DiagClient =
+      new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
   FixupDiagPrefixExeName(DiagClient, ProgName);
 
   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
@@ -423,8 +425,8 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
   if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"))
     llvm::dbgs() << llvm::getBugReportMsg();
   if (FailingCommand != nullptr &&
-    TheDriver.maybeGenerateCompilationDiagnostics(CommandStatus, ReproLevel,
-                                                  *C, *FailingCommand))
+      TheDriver.maybeGenerateCompilationDiagnostics(CommandStatus, ReproLevel,
+                                                    *C, *FailingCommand))
     Res = 1;
 
   Diags.getClient()->finish();

>From b154b926a09b9e2aae57abc9483a375fc372c69f Mon Sep 17 00:00:00 2001
From: CratelsChen <cratels at 126.com>
Date: Thu, 18 Apr 2024 23:07:41 +0800
Subject: [PATCH 5/6] add comments

---
 clang/tools/driver/driver.cpp            |  13 ++
 llvm/include/llvm/Support/TargetSelect.h | 201 ++++++++++++-----------
 2 files changed, 117 insertions(+), 97 deletions(-)

diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index 6cfb55892dd78..940b88defe2cc 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -227,11 +227,24 @@ static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV,
 
 // Cratels:  build 目录下会生成一个 main 方法。在该方法中调用 clang_main
 // 这里是所有程序的入口
+
+// int clang_main(int argc, char **, const llvm::ToolContext &);
+
+// int main(int argc, char **argv) { // Cratels: 程序入口
+//   llvm::InitLLVM X(argc, argv); // Cratels: 初始化 LLVM
+//   return clang_main(argc, argv, {argv[0], nullptr, false});
+// }
+
+// Cratels: clang 驱动器调用的第一个工具是 clang
+// 本身,给以参数-cc1,关闭编译器驱动器模式而开启编译器模式。
+
 int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
   noteBottomOfStack();
   llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
                         " and include the crash backtrace, preprocessed "
                         "source, and associated run script.\n");
+
+  // Cratels: 自定义 vector 来存放编译参数
   SmallVector<const char *, 256> Args(Argv, Argv + Argc);
 
   if (llvm::sys::Process::FixupStandardFileDescriptors())
diff --git a/llvm/include/llvm/Support/TargetSelect.h b/llvm/include/llvm/Support/TargetSelect.h
index e57614cea758b..de42be5108212 100644
--- a/llvm/include/llvm/Support/TargetSelect.h
+++ b/llvm/include/llvm/Support/TargetSelect.h
@@ -18,27 +18,29 @@
 #include "llvm/Config/llvm-config.h"
 
 extern "C" {
-  // Declare all of the target-initialization functions that are available.
+// Declare all of the target-initialization functions that are available.
 #define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##TargetInfo();
 #include "llvm/Config/Targets.def"
 
 #define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##Target();
 #include "llvm/Config/Targets.def"
 
-  // Declare all of the target-MC-initialization functions that are available.
+// Declare all of the target-MC-initialization functions that are available.
 #define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##TargetMC();
 #include "llvm/Config/Targets.def"
 
-  // Declare all of the available assembly printer initialization functions.
-#define LLVM_ASM_PRINTER(TargetName) void LLVMInitialize##TargetName##AsmPrinter();
+// Declare all of the available assembly printer initialization functions.
+#define LLVM_ASM_PRINTER(TargetName)                                           \
+  void LLVMInitialize##TargetName##AsmPrinter();
 #include "llvm/Config/AsmPrinters.def"
 
-  // Declare all of the available assembly parser initialization functions.
-#define LLVM_ASM_PARSER(TargetName) void LLVMInitialize##TargetName##AsmParser();
+// Declare all of the available assembly parser initialization functions.
+#define LLVM_ASM_PARSER(TargetName)                                            \
+  void LLVMInitialize##TargetName##AsmParser();
 #include "llvm/Config/AsmParsers.def"
 
-  // Declare all of the available disassembler initialization functions.
-#define LLVM_DISASSEMBLER(TargetName) \
+// Declare all of the available disassembler initialization functions.
+#define LLVM_DISASSEMBLER(TargetName)                                          \
   void LLVMInitialize##TargetName##Disassembler();
 #include "llvm/Config/Disassemblers.def"
 
@@ -48,129 +50,134 @@ extern "C" {
 }
 
 namespace llvm {
-  /// InitializeAllTargetInfos - The main program should call this function if
-  /// it wants access to all available targets that LLVM is configured to
-  /// support, to make them available via the TargetRegistry.
-  ///
-  /// It is legal for a client to make multiple calls to this function.
-  inline void InitializeAllTargetInfos() {
+/// InitializeAllTargetInfos - The main program should call this function if
+/// it wants access to all available targets that LLVM is configured to
+/// support, to make them available via the TargetRegistry.
+///
+/// It is legal for a client to make multiple calls to this function.
+inline void InitializeAllTargetInfos() {
+  // Cratels: 调用所有 TargetInfo 方法
 #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetInfo();
+// Cratels: include 的底层操作就是简单复制粘贴,无论是.h文件还是.def文件
 #include "llvm/Config/Targets.def"
-  }
-
-  /// InitializeAllTargets - The main program should call this function if it
-  /// wants access to all available target machines that LLVM is configured to
-  /// support, to make them available via the TargetRegistry.
-  ///
-  /// It is legal for a client to make multiple calls to this function.
-  inline void InitializeAllTargets() {
-    // FIXME: Remove this, clients should do it.
-    InitializeAllTargetInfos();
+}
 
+// Cratels: 初始化所有LLVM 支持的 target
+/// InitializeAllTargets - The main program should call this function if it
+/// wants access to all available target machines that LLVM is configured to
+/// support, to make them available via the TargetRegistry.
+///
+/// It is legal for a client to make multiple calls to this function.
+inline void InitializeAllTargets() {
+  // FIXME: Remove this, clients should do it.
+  InitializeAllTargetInfos();
+
+// Cratels: 调用所有 Target 方法
 #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##Target();
 #include "llvm/Config/Targets.def"
-  }
-
-  /// InitializeAllTargetMCs - The main program should call this function if it
-  /// wants access to all available target MC that LLVM is configured to
-  /// support, to make them available via the TargetRegistry.
-  ///
-  /// It is legal for a client to make multiple calls to this function.
-  inline void InitializeAllTargetMCs() {
+}
+
+/// InitializeAllTargetMCs - The main program should call this function if it
+/// wants access to all available target MC that LLVM is configured to
+/// support, to make them available via the TargetRegistry.
+///
+/// It is legal for a client to make multiple calls to this function.
+inline void InitializeAllTargetMCs() {
 #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetMC();
 #include "llvm/Config/Targets.def"
-  }
-
-  /// InitializeAllAsmPrinters - The main program should call this function if
-  /// it wants all asm printers that LLVM is configured to support, to make them
-  /// available via the TargetRegistry.
-  ///
-  /// It is legal for a client to make multiple calls to this function.
-  inline void InitializeAllAsmPrinters() {
+}
+
+/// InitializeAllAsmPrinters - The main program should call this function if
+/// it wants all asm printers that LLVM is configured to support, to make them
+/// available via the TargetRegistry.
+///
+/// It is legal for a client to make multiple calls to this function.
+inline void InitializeAllAsmPrinters() {
 #define LLVM_ASM_PRINTER(TargetName) LLVMInitialize##TargetName##AsmPrinter();
 #include "llvm/Config/AsmPrinters.def"
-  }
-
-  /// InitializeAllAsmParsers - The main program should call this function if it
-  /// wants all asm parsers that LLVM is configured to support, to make them
-  /// available via the TargetRegistry.
-  ///
-  /// It is legal for a client to make multiple calls to this function.
-  inline void InitializeAllAsmParsers() {
+}
+
+/// InitializeAllAsmParsers - The main program should call this function if it
+/// wants all asm parsers that LLVM is configured to support, to make them
+/// available via the TargetRegistry.
+///
+/// It is legal for a client to make multiple calls to this function.
+inline void InitializeAllAsmParsers() {
 #define LLVM_ASM_PARSER(TargetName) LLVMInitialize##TargetName##AsmParser();
 #include "llvm/Config/AsmParsers.def"
-  }
-
-  /// InitializeAllDisassemblers - The main program should call this function if
-  /// it wants all disassemblers that LLVM is configured to support, to make
-  /// them available via the TargetRegistry.
-  ///
-  /// It is legal for a client to make multiple calls to this function.
-  inline void InitializeAllDisassemblers() {
-#define LLVM_DISASSEMBLER(TargetName) LLVMInitialize##TargetName##Disassembler();
+}
+
+/// InitializeAllDisassemblers - The main program should call this function if
+/// it wants all disassemblers that LLVM is configured to support, to make
+/// them available via the TargetRegistry.
+///
+/// It is legal for a client to make multiple calls to this function.
+inline void InitializeAllDisassemblers() {
+#define LLVM_DISASSEMBLER(TargetName)                                          \
+  LLVMInitialize##TargetName##Disassembler();
 #include "llvm/Config/Disassemblers.def"
-  }
-
-  /// InitializeNativeTarget - The main program should call this function to
-  /// initialize the native target corresponding to the host.  This is useful
-  /// for JIT applications to ensure that the target gets linked in correctly.
-  ///
-  /// It is legal for a client to make multiple calls to this function.
-  inline bool InitializeNativeTarget() {
+}
+
+/// InitializeNativeTarget - The main program should call this function to
+/// initialize the native target corresponding to the host.  This is useful
+/// for JIT applications to ensure that the target gets linked in correctly.
+///
+/// It is legal for a client to make multiple calls to this function.
+inline bool InitializeNativeTarget() {
   // If we have a native target, initialize it to ensure it is linked in.
 #ifdef LLVM_NATIVE_TARGET
-    LLVM_NATIVE_TARGETINFO();
-    LLVM_NATIVE_TARGET();
-    LLVM_NATIVE_TARGETMC();
-    return false;
+  LLVM_NATIVE_TARGETINFO();
+  LLVM_NATIVE_TARGET();
+  LLVM_NATIVE_TARGETMC();
+  return false;
 #else
-    return true;
+  return true;
 #endif
-  }
+}
 
-  /// InitializeNativeTargetAsmPrinter - The main program should call
-  /// this function to initialize the native target asm printer.
-  inline bool InitializeNativeTargetAsmPrinter() {
+/// InitializeNativeTargetAsmPrinter - The main program should call
+/// this function to initialize the native target asm printer.
+inline bool InitializeNativeTargetAsmPrinter() {
   // If we have a native target, initialize the corresponding asm printer.
 #ifdef LLVM_NATIVE_ASMPRINTER
-    LLVM_NATIVE_ASMPRINTER();
-    return false;
+  LLVM_NATIVE_ASMPRINTER();
+  return false;
 #else
-    return true;
+  return true;
 #endif
-  }
+}
 
-  /// InitializeNativeTargetAsmParser - The main program should call
-  /// this function to initialize the native target asm parser.
-  inline bool InitializeNativeTargetAsmParser() {
+/// InitializeNativeTargetAsmParser - The main program should call
+/// this function to initialize the native target asm parser.
+inline bool InitializeNativeTargetAsmParser() {
   // If we have a native target, initialize the corresponding asm parser.
 #ifdef LLVM_NATIVE_ASMPARSER
-    LLVM_NATIVE_ASMPARSER();
-    return false;
+  LLVM_NATIVE_ASMPARSER();
+  return false;
 #else
-    return true;
+  return true;
 #endif
-  }
+}
 
-  /// InitializeNativeTargetDisassembler - The main program should call
-  /// this function to initialize the native target disassembler.
-  inline bool InitializeNativeTargetDisassembler() {
+/// InitializeNativeTargetDisassembler - The main program should call
+/// this function to initialize the native target disassembler.
+inline bool InitializeNativeTargetDisassembler() {
   // If we have a native target, initialize the corresponding disassembler.
 #ifdef LLVM_NATIVE_DISASSEMBLER
-    LLVM_NATIVE_DISASSEMBLER();
-    return false;
+  LLVM_NATIVE_DISASSEMBLER();
+  return false;
 #else
-    return true;
+  return true;
 #endif
-  }
+}
 
-  /// InitializeAllTargetMCAs - The main program should call
-  /// this function to initialize the target CustomBehaviour and
-  /// InstrPostProcess classes.
-  inline void InitializeAllTargetMCAs() {
+/// InitializeAllTargetMCAs - The main program should call
+/// this function to initialize the target CustomBehaviour and
+/// InstrPostProcess classes.
+inline void InitializeAllTargetMCAs() {
 #define LLVM_TARGETMCA(TargetName) LLVMInitialize##TargetName##TargetMCA();
 #include "llvm/Config/TargetMCAs.def"
-  }
 }
+} // namespace llvm
 
 #endif

>From 4f0f05d77cdcaeec2e0726e34ac81ed5b495939f Mon Sep 17 00:00:00 2001
From: CratelsChen <cratels at 126.com>
Date: Thu, 18 Apr 2024 23:22:41 +0800
Subject: [PATCH 6/6] add comments

---
 .../include/clang/Frontend/CompilerInstance.h |  36 ++----
 .../ExecuteCompilerInvocation.cpp             | 118 +++++++++++-------
 clang/tools/driver/cc1_main.cpp               |  11 +-
 clang/tools/driver/driver.cpp                 |   1 +
 4 files changed, 94 insertions(+), 72 deletions(-)

diff --git a/clang/include/clang/Frontend/CompilerInstance.h b/clang/include/clang/Frontend/CompilerInstance.h
index 3464654284f19..109ccd2dc03a8 100644
--- a/clang/include/clang/Frontend/CompilerInstance.h
+++ b/clang/include/clang/Frontend/CompilerInstance.h
@@ -35,7 +35,7 @@ namespace llvm {
 class raw_fd_ostream;
 class Timer;
 class TimerGroup;
-}
+} // namespace llvm
 
 namespace clang {
 class ASTContext;
@@ -58,6 +58,7 @@ class SourceManager;
 class TargetInfo;
 enum class DisableValidationForModuleKind;
 
+// Cratels: CompilerInstance是一个工具类来持有单例的 Clang compiler对象。
 /// CompilerInstance - Helper class for managing a single instance of the Clang
 /// compiler.
 ///
@@ -204,6 +205,7 @@ class CompilerInstance : public ModuleLoader {
 
   CompilerInstance(const CompilerInstance &) = delete;
   void operator=(const CompilerInstance &) = delete;
+
 public:
   explicit CompilerInstance(
       std::shared_ptr<PCHContainerOperations> PCHContainerOps =
@@ -270,9 +272,7 @@ class CompilerInstance : public ModuleLoader {
 
   /// Set the flag indicating whether we should (re)build the global
   /// module index.
-  void setBuildGlobalModuleIndex(bool Build) {
-    BuildGlobalModuleIndex = Build;
-  }
+  void setBuildGlobalModuleIndex(bool Build) { BuildGlobalModuleIndex = Build; }
 
   /// @}
   /// @name Forwarding Methods
@@ -280,9 +280,7 @@ class CompilerInstance : public ModuleLoader {
 
   AnalyzerOptions &getAnalyzerOpts() { return Invocation->getAnalyzerOpts(); }
 
-  CodeGenOptions &getCodeGenOpts() {
-    return Invocation->getCodeGenOpts();
-  }
+  CodeGenOptions &getCodeGenOpts() { return Invocation->getCodeGenOpts(); }
   const CodeGenOptions &getCodeGenOpts() const {
     return Invocation->getCodeGenOpts();
   }
@@ -308,9 +306,7 @@ class CompilerInstance : public ModuleLoader {
     return Invocation->getFileSystemOpts();
   }
 
-  FrontendOptions &getFrontendOpts() {
-    return Invocation->getFrontendOpts();
-  }
+  FrontendOptions &getFrontendOpts() { return Invocation->getFrontendOpts(); }
   const FrontendOptions &getFrontendOpts() const {
     return Invocation->getFrontendOpts();
   }
@@ -350,9 +346,7 @@ class CompilerInstance : public ModuleLoader {
     return Invocation->getPreprocessorOutputOpts();
   }
 
-  TargetOptions &getTargetOpts() {
-    return Invocation->getTargetOpts();
-  }
+  TargetOptions &getTargetOpts() { return Invocation->getTargetOpts(); }
   const TargetOptions &getTargetOpts() const {
     return Invocation->getTargetOpts();
   }
@@ -394,9 +388,7 @@ class CompilerInstance : public ModuleLoader {
   void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value);
 
   /// Get the current stream for verbose output.
-  raw_ostream &getVerboseOutputStream() {
-    return *VerboseOutputStream;
-  }
+  raw_ostream &getVerboseOutputStream() { return *VerboseOutputStream; }
 
   /// @}
   /// @name Target Info
@@ -574,8 +566,8 @@ class CompilerInstance : public ModuleLoader {
   void setASTReader(IntrusiveRefCntPtr<ASTReader> Reader);
 
   std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
-  void setModuleDepCollector(
-      std::shared_ptr<ModuleDependencyCollector> Collector);
+  void
+  setModuleDepCollector(std::shared_ptr<ModuleDependencyCollector> Collector);
 
   std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
     return ThePCHContainerOperations;
@@ -701,11 +693,9 @@ class CompilerInstance : public ModuleLoader {
   /// used by some diagnostics printers (for logging purposes only).
   ///
   /// \return The new object on success, or null on failure.
-  static IntrusiveRefCntPtr<DiagnosticsEngine>
-  createDiagnostics(DiagnosticOptions *Opts,
-                    DiagnosticConsumer *Client = nullptr,
-                    bool ShouldOwnClient = true,
-                    const CodeGenOptions *CodeGenOpts = nullptr);
+  static IntrusiveRefCntPtr<DiagnosticsEngine> createDiagnostics(
+      DiagnosticOptions *Opts, DiagnosticConsumer *Client = nullptr,
+      bool ShouldOwnClient = true, const CodeGenOptions *CodeGenOpts = nullptr);
 
   /// Create the file manager and replace any existing one with it.
   ///
diff --git a/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp b/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
index f85f0365616f9..134799a38a2c3 100644
--- a/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ b/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -43,24 +43,38 @@ CreateFrontendBaseAction(CompilerInstance &CI) {
   (void)Action;
 
   switch (CI.getFrontendOpts().ProgramAction) {
-  case ASTDeclList:            return std::make_unique<ASTDeclListAction>();
-  case ASTDump:                return std::make_unique<ASTDumpAction>();
-  case ASTPrint:               return std::make_unique<ASTPrintAction>();
-  case ASTView:                return std::make_unique<ASTViewAction>();
+  case ASTDeclList:
+    return std::make_unique<ASTDeclListAction>();
+  case ASTDump:
+    return std::make_unique<ASTDumpAction>();
+  case ASTPrint:
+    return std::make_unique<ASTPrintAction>();
+  case ASTView:
+    return std::make_unique<ASTViewAction>();
   case DumpCompilerOptions:
     return std::make_unique<DumpCompilerOptionsAction>();
-  case DumpRawTokens:          return std::make_unique<DumpRawTokensAction>();
-  case DumpTokens:             return std::make_unique<DumpTokensAction>();
-  case EmitAssembly:           return std::make_unique<EmitAssemblyAction>();
-  case EmitBC:                 return std::make_unique<EmitBCAction>();
-  case EmitHTML:               return std::make_unique<HTMLPrintAction>();
-  case EmitLLVM:               return std::make_unique<EmitLLVMAction>();
-  case EmitLLVMOnly:           return std::make_unique<EmitLLVMOnlyAction>();
-  case EmitCodeGenOnly:        return std::make_unique<EmitCodeGenOnlyAction>();
-  case EmitObj:                return std::make_unique<EmitObjAction>();
+  case DumpRawTokens:
+    return std::make_unique<DumpRawTokensAction>();
+  case DumpTokens:
+    return std::make_unique<DumpTokensAction>();
+  case EmitAssembly:
+    return std::make_unique<EmitAssemblyAction>();
+  case EmitBC:
+    return std::make_unique<EmitBCAction>();
+  case EmitHTML:
+    return std::make_unique<HTMLPrintAction>();
+  case EmitLLVM:
+    return std::make_unique<EmitLLVMAction>();
+  case EmitLLVMOnly:
+    return std::make_unique<EmitLLVMOnlyAction>();
+  case EmitCodeGenOnly:
+    return std::make_unique<EmitCodeGenOnlyAction>();
+  case EmitObj:
+    return std::make_unique<EmitObjAction>();
   case ExtractAPI:
     return std::make_unique<ExtractAPIAction>();
-  case FixIt:                  return std::make_unique<FixItAction>();
+  case FixIt:
+    return std::make_unique<FixItAction>();
   case GenerateModule:
     return std::make_unique<GenerateModuleFromModuleMapAction>();
   case GenerateModuleInterface:
@@ -69,14 +83,20 @@ CreateFrontendBaseAction(CompilerInstance &CI) {
     return std::make_unique<GenerateReducedModuleInterfaceAction>();
   case GenerateHeaderUnit:
     return std::make_unique<GenerateHeaderUnitAction>();
-  case GeneratePCH:            return std::make_unique<GeneratePCHAction>();
+  case GeneratePCH:
+    return std::make_unique<GeneratePCHAction>();
   case GenerateInterfaceStubs:
     return std::make_unique<GenerateInterfaceStubsAction>();
-  case InitOnly:               return std::make_unique<InitOnlyAction>();
-  case ParseSyntaxOnly:        return std::make_unique<SyntaxOnlyAction>();
-  case ModuleFileInfo:         return std::make_unique<DumpModuleInfoAction>();
-  case VerifyPCH:              return std::make_unique<VerifyPCHAction>();
-  case TemplightDump:          return std::make_unique<TemplightDumpAction>();
+  case InitOnly:
+    return std::make_unique<InitOnlyAction>();
+  case ParseSyntaxOnly:
+    return std::make_unique<SyntaxOnlyAction>();
+  case ModuleFileInfo:
+    return std::make_unique<DumpModuleInfoAction>();
+  case VerifyPCH:
+    return std::make_unique<VerifyPCHAction>();
+  case TemplightDump:
+    return std::make_unique<TemplightDumpAction>();
 
   case PluginAction: {
     for (const FrontendPluginRegistry::entry &Plugin :
@@ -94,11 +114,12 @@ CreateFrontendBaseAction(CompilerInstance &CI) {
     }
 
     CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
-      << CI.getFrontendOpts().ActionName;
+        << CI.getFrontendOpts().ActionName;
     return nullptr;
   }
 
-  case PrintPreamble:          return std::make_unique<PrintPreambleAction>();
+  case PrintPreamble:
+    return std::make_unique<PrintPreambleAction>();
   case PrintPreprocessedInput: {
     if (CI.getPreprocessorOutputOpts().RewriteIncludes ||
         CI.getPreprocessorOutputOpts().RewriteImports)
@@ -106,31 +127,42 @@ CreateFrontendBaseAction(CompilerInstance &CI) {
     return std::make_unique<PrintPreprocessedAction>();
   }
 
-  case RewriteMacros:          return std::make_unique<RewriteMacrosAction>();
-  case RewriteTest:            return std::make_unique<RewriteTestAction>();
+  case RewriteMacros:
+    return std::make_unique<RewriteMacrosAction>();
+  case RewriteTest:
+    return std::make_unique<RewriteTestAction>();
 #if CLANG_ENABLE_OBJC_REWRITER
-  case RewriteObjC:            return std::make_unique<RewriteObjCAction>();
+  case RewriteObjC:
+    return std::make_unique<RewriteObjCAction>();
 #else
-  case RewriteObjC:            Action = "RewriteObjC"; break;
+  case RewriteObjC:
+    Action = "RewriteObjC";
+    break;
 #endif
 #if CLANG_ENABLE_ARCMT
   case MigrateSource:
     return std::make_unique<arcmt::MigrateSourceAction>();
 #else
-  case MigrateSource:          Action = "MigrateSource"; break;
+  case MigrateSource:
+    Action = "MigrateSource";
+    break;
 #endif
 #if CLANG_ENABLE_STATIC_ANALYZER
-  case RunAnalysis:            return std::make_unique<ento::AnalysisAction>();
+  case RunAnalysis:
+    return std::make_unique<ento::AnalysisAction>();
 #else
-  case RunAnalysis:            Action = "RunAnalysis"; break;
+  case RunAnalysis:
+    Action = "RunAnalysis";
+    break;
 #endif
-  case RunPreprocessorOnly:    return std::make_unique<PreprocessOnlyAction>();
+  case RunPreprocessorOnly:
+    return std::make_unique<PreprocessOnlyAction>();
   case PrintDependencyDirectivesSourceMinimizerOutput:
     return std::make_unique<PrintDependencyDirectivesSourceMinimizerAction>();
   }
 
-#if !CLANG_ENABLE_ARCMT || !CLANG_ENABLE_STATIC_ANALYZER \
-  || !CLANG_ENABLE_OBJC_REWRITER
+#if !CLANG_ENABLE_ARCMT || !CLANG_ENABLE_STATIC_ANALYZER ||                    \
+    !CLANG_ENABLE_OBJC_REWRITER
   CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
   return 0;
 #else
@@ -138,8 +170,7 @@ CreateFrontendBaseAction(CompilerInstance &CI) {
 #endif
 }
 
-std::unique_ptr<FrontendAction>
-CreateFrontendAction(CompilerInstance &CI) {
+std::unique_ptr<FrontendAction> CreateFrontendAction(CompilerInstance &CI) {
   // Create the underlying action.
   std::unique_ptr<FrontendAction> Act = CreateFrontendBaseAction(CI);
   if (!Act)
@@ -165,17 +196,15 @@ CreateFrontendAction(CompilerInstance &CI) {
       Act = std::make_unique<arcmt::ModifyAction>(std::move(Act));
       break;
     case FrontendOptions::ARCMT_Migrate:
-      Act = std::make_unique<arcmt::MigrateAction>(std::move(Act),
-                                     FEOpts.MTMigrateDir,
-                                     FEOpts.ARCMTMigrateReportOut,
-                                     FEOpts.ARCMTMigrateEmitARCErrors);
+      Act = std::make_unique<arcmt::MigrateAction>(
+          std::move(Act), FEOpts.MTMigrateDir, FEOpts.ARCMTMigrateReportOut,
+          FEOpts.ARCMTMigrateEmitARCErrors);
       break;
     }
 
     if (FEOpts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
-      Act = std::make_unique<arcmt::ObjCMigrateAction>(std::move(Act),
-                                                        FEOpts.MTMigrateDir,
-                                                        FEOpts.ObjCMTAction);
+      Act = std::make_unique<arcmt::ObjCMigrateAction>(
+          std::move(Act), FEOpts.MTMigrateDir, FEOpts.ObjCMTAction);
     }
   }
 #endif
@@ -195,8 +224,8 @@ CreateFrontendAction(CompilerInstance &CI) {
   // If there are any AST files to merge, create a frontend action
   // adaptor to perform the merge.
   if (!FEOpts.ASTMergeFiles.empty())
-    Act = std::make_unique<ASTMergeAction>(std::move(Act),
-                                            FEOpts.ASTMergeFiles);
+    Act =
+        std::make_unique<ASTMergeAction>(std::move(Act), FEOpts.ASTMergeFiles);
 
   return Act;
 }
@@ -228,7 +257,7 @@ bool ExecuteCompilerInvocation(CompilerInstance *Clang) {
   // This should happen AFTER plugins have been loaded!
   if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
     unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
-    auto Args = std::make_unique<const char*[]>(NumArgs + 2);
+    auto Args = std::make_unique<const char *[]>(NumArgs + 2);
     Args[0] = "clang (LLVM option parsing)";
     for (unsigned i = 0; i != NumArgs; ++i)
       Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
@@ -268,6 +297,7 @@ bool ExecuteCompilerInvocation(CompilerInstance *Clang) {
   }
 #endif
 
+  // Cratels:
   // If there were errors in processing arguments, don't do anything else.
   if (Clang->getDiagnostics().hasErrorOccurred())
     return false;
diff --git a/clang/tools/driver/cc1_main.cpp b/clang/tools/driver/cc1_main.cpp
index b5c6be3c557bb..12bed1c607a6b 100644
--- a/clang/tools/driver/cc1_main.cpp
+++ b/clang/tools/driver/cc1_main.cpp
@@ -63,7 +63,7 @@ using namespace llvm::opt;
 
 static void LLVMErrorHandler(void *UserData, const char *Message,
                              bool GenCrashDiag) {
-  DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
+  DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine *>(UserData);
 
   Diags.Report(diag::err_fe_error_backend) << Message;
 
@@ -139,7 +139,7 @@ static int PrintSupportedExtensions(std::string TargetStr) {
   const llvm::Triple &MachineTriple = TheTargetMachine->getTargetTriple();
   const llvm::MCSubtargetInfo *MCInfo = TheTargetMachine->getMCSubtargetInfo();
   const llvm::ArrayRef<llvm::SubtargetFeatureKV> Features =
-    MCInfo->getAllProcessorFeatures();
+      MCInfo->getAllProcessorFeatures();
 
   llvm::StringMap<llvm::StringRef> DescMap;
   for (const llvm::SubtargetFeatureKV &feature : Features)
@@ -161,6 +161,7 @@ static int PrintSupportedExtensions(std::string TargetStr) {
   return 0;
 }
 
+// 通过指定-cc1 option 之后,LLVM 最终会执行到这个方法作为编译器前端来工作
 int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
   ensureSufficientStack();
 
@@ -208,7 +209,7 @@ int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
   if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
       Clang->getHeaderSearchOpts().ResourceDir.empty())
     Clang->getHeaderSearchOpts().ResourceDir =
-      CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
+        CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
 
   // Create the actual diagnostics engine.
   Clang->createDiagnostics();
@@ -217,8 +218,8 @@ int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
 
   // Set an error handler, so that any LLVM backend diagnostics go through our
   // error handler.
-  llvm::install_fatal_error_handler(LLVMErrorHandler,
-                                  static_cast<void*>(&Clang->getDiagnostics()));
+  llvm::install_fatal_error_handler(
+      LLVMErrorHandler, static_cast<void *>(&Clang->getDiagnostics()));
 
   DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
   if (!Success) {
diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index 940b88defe2cc..f22ccda01a9e1 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -240,6 +240,7 @@ static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV,
 
 int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
   noteBottomOfStack();
+
   llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
                         " and include the crash backtrace, preprocessed "
                         "source, and associated run script.\n");



More information about the cfe-commits mailing list