[clang] [llvm] add comment (PR #103046)

via cfe-commits cfe-commits at lists.llvm.org
Tue Aug 13 08:28:44 PDT 2024


https://github.com/cratelschen updated https://github.com/llvm/llvm-project/pull/103046

>From b547df47fd2e85c08e3d0c0e86a124abc162a8d7 Mon Sep 17 00:00:00 2001
From: chenshuang <chenshuang at softsafe-tech.com>
Date: Tue, 13 Aug 2024 19:04:18 +0800
Subject: [PATCH 1/2] add comment: driver.cpp

---
 clang/tools/driver/driver.cpp            |  22 +--
 llvm/include/llvm/Support/TargetSelect.h | 198 ++++++++++++-----------
 test.cpp                                 |   1 +
 3 files changed, 116 insertions(+), 105 deletions(-)
 create mode 100644 test.cpp

diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index 83b5bbb71f5212..62e64b2b282f39 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,7 @@ static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV,
   return 1;
 }
 
+// Cratels:clang driver的真正入口.main方法在build目录,是有cmake自动生成的.
 int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
   noteBottomOfStack();
   llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
@@ -235,6 +236,9 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
   if (llvm::sys::Process::FixupStandardFileDescriptors())
     return 1;
 
+  // clang-format off
+  // Cratels:初始化所有的target.如果在cmake configure的时候指定了target,这只会初始化对应的target,否则就初始化默认的targets.
+  // clang-format on
   llvm::InitializeAllTargets();
 
   llvm::BumpPtrAllocator A;
@@ -316,8 +320,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 +427,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();
diff --git a/llvm/include/llvm/Support/TargetSelect.h b/llvm/include/llvm/Support/TargetSelect.h
index e57614cea758bb..0da7fbd180fb80 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,133 @@ 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() {
 #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetInfo();
 #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();
+/// 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();
 
 #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##Target();
+  // clang-format off
+  // Cratels:这个def文件是在cmake configure的时候自动生成的,其内容就是需要生成的targets
+  // clang-format on
 #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
diff --git a/test.cpp b/test.cpp
new file mode 100644
index 00000000000000..3d706294134f32
--- /dev/null
+++ b/test.cpp
@@ -0,0 +1 @@
+int f() { return 1; }

>From dbb149610e5b24dbed5a33d6359eb1318ca6e90d Mon Sep 17 00:00:00 2001
From: Cratels Chen <cratels at 126.com>
Date: Tue, 13 Aug 2024 23:28:28 +0800
Subject: [PATCH 2/2] =?UTF-8?q?add=20comments:=20=E7=A0=94=E7=A9=B6=20resp?=
 =?UTF-8?q?onse=20file=20=E7=9A=84=E9=97=AE=E9=A2=98=E4=BB=A5=E5=8F=8A?=
 =?UTF-8?q?=E5=85=B6=E7=94=A8=E6=B3=95=20time=3D2024-08-13=2023:28:28?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 clang/lib/Driver/Driver.cpp         | 149 ++++++++++++++--------------
 clang/tools/driver/driver.cpp       |  18 +++-
 clang/tools/driver/response_file.md |  22 ++++
 3 files changed, 112 insertions(+), 77 deletions(-)
 create mode 100644 clang/tools/driver/response_file.md

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index e12416e51f8d24..2ca7f1017722a0 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -348,8 +348,7 @@ phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
   if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
       (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
-      (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P)) ||
-      CCGenDiagnostics) {
+      (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P)) || CCGenDiagnostics) {
     FinalPhase = phases::Preprocess;
 
     // --precompile only runs up to precompilation.
@@ -363,7 +362,8 @@ phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
     // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
              (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
-             (PhaseArg = DAL.getLastArg(options::OPT_print_enabled_extensions)) ||
+             (PhaseArg =
+                  DAL.getLastArg(options::OPT_print_enabled_extensions)) ||
              (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
              (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
@@ -374,18 +374,18 @@ phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
     FinalPhase = phases::Compile;
 
-  // -S only runs up to the backend.
+    // -S only runs up to the backend.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
     FinalPhase = phases::Backend;
 
-  // -c compilation only runs up to the assembler.
+    // -c compilation only runs up to the assembler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
     FinalPhase = phases::Assemble;
 
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_emit_interface_stubs))) {
     FinalPhase = phases::IfsMerge;
 
-  // Otherwise do everything.
+    // Otherwise do everything.
   } else
     FinalPhase = phases::Link;
 
@@ -517,8 +517,7 @@ DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
 ///
 /// This routine provides the logic to compute a target triple from various
 /// args passed to the driver and the default triple string.
-static llvm::Triple computeTargetTriple(const Driver &D,
-                                        StringRef TargetTriple,
+static llvm::Triple computeTargetTriple(const Driver &D, StringRef TargetTriple,
                                         const ArgList &Args,
                                         StringRef DarwinArchName = "") {
   // FIXME: Already done in Compilation *Driver::BuildCompilation
@@ -636,8 +635,8 @@ static llvm::Triple computeTargetTriple(const Driver &D,
   // Handle -miamcu flag.
   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
     if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
-      D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
-                                                       << Target.str();
+      D.Diag(diag::err_drv_unsupported_opt_for_target)
+          << "-miamcu" << Target.str();
 
     if (A && !A->getOption().matches(options::OPT_m32))
       D.Diag(diag::err_drv_argument_not_allowed_with)
@@ -1227,8 +1226,8 @@ Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
   bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
 
   // All arguments, from both config file and command line.
-  InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
-                                              : std::move(*CLOptions));
+  InputArgList Args =
+      std::move(HasConfigFile ? std::move(*CfgOptions) : std::move(*CLOptions));
 
   if (HasConfigFile)
     for (auto *Opt : *CLOptions) {
@@ -1406,14 +1405,13 @@ Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
   if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
     StringRef Name = A->getValue();
     unsigned Model = llvm::StringSwitch<unsigned>(Name)
-        .Case("off", EmbedNone)
-        .Case("all", EmbedBitcode)
-        .Case("bitcode", EmbedBitcode)
-        .Case("marker", EmbedMarker)
-        .Default(~0U);
+                         .Case("off", EmbedNone)
+                         .Case("all", EmbedBitcode)
+                         .Case("bitcode", EmbedBitcode)
+                         .Case("marker", EmbedMarker)
+                         .Default(~0U);
     if (Model == ~0U) {
-      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
-                                                << Name;
+      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
     } else
       BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
   }
@@ -1462,8 +1460,8 @@ Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
   DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
 
   // Owned by the host.
-  const ToolChain &TC = getToolChain(
-      *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
+  const ToolChain &TC =
+      getToolChain(*UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
 
   // Check if the environment version is valid except wasm case.
   llvm::Triple Triple = TC.getTriple();
@@ -1615,7 +1613,7 @@ bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
     size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
     if (LineEnd == StringRef::npos)
       continue;
-    StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
+    StringRef ParentProcess = Data.slice(ParentProcPos + 15, LineEnd).trim();
     int OpenBracket = -1, CloseBracket = -1;
     for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
       if (ParentProcess[i] == '[')
@@ -1628,7 +1626,8 @@ bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
     int CrashPID;
     if (OpenBracket < 0 || CloseBracket < 0 ||
         ParentProcess.slice(OpenBracket + 1, CloseBracket)
-            .getAsInteger(10, CrashPID) || CrashPID != PID) {
+            .getAsInteger(10, CrashPID) ||
+        CrashPID != PID) {
       continue;
     }
 
@@ -1884,8 +1883,7 @@ void Driver::generateCompilationDiagnostics(
       CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
       Diag(clang::diag::note_drv_command_failed_diag_msg)
           << "Crash backtrace is located in";
-      Diag(clang::diag::note_drv_command_failed_diag_msg)
-          << CrashDiagDir.str();
+      Diag(clang::diag::note_drv_command_failed_diag_msg) << CrashDiagDir.str();
       Diag(clang::diag::note_drv_command_failed_diag_msg)
           << "(choose the .crash file that corresponds to your crash)";
     }
@@ -1997,8 +1995,7 @@ void Driver::PrintHelp(bool ShowHidden) const {
 
   std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
   getOpts().printHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
-                      ShowHidden, /*ShowAllAliases=*/false,
-                      VisibilityMask);
+                      ShowHidden, /*ShowAllAliases=*/false, VisibilityMask);
 }
 
 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
@@ -2175,11 +2172,11 @@ bool Driver::HandleImmediateArgs(Compilation &C) {
 
   if (C.getArgs().hasArg(options::OPT_v)) {
     if (!SystemConfigDir.empty())
-      llvm::errs() << "System configuration file directory: "
-                   << SystemConfigDir << "\n";
+      llvm::errs() << "System configuration file directory: " << SystemConfigDir
+                   << "\n";
     if (!UserConfigDir.empty())
-      llvm::errs() << "User configuration file directory: "
-                   << UserConfigDir << "\n";
+      llvm::errs() << "User configuration file directory: " << UserConfigDir
+                   << "\n";
   }
 
   const ToolChain &TC = C.getDefaultToolChain();
@@ -2258,7 +2255,7 @@ bool Driver::HandleImmediateArgs(Compilation &C) {
     StringRef ProgName = A->getValue();
 
     // Null program name cannot have a path.
-    if (! ProgName.empty())
+    if (!ProgName.empty())
       llvm::outs() << GetProgramPath(ProgName, TC);
 
     llvm::outs() << "\n";
@@ -2491,7 +2488,7 @@ void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
 
   // Add in arch bindings for every top level action, as well as lipo and
   // dsymutil steps if needed.
-  for (Action* Act : SingleActions) {
+  for (Action *Act : SingleActions) {
     // Make sure we can lipo this kind of output. If not (and it is an actual
     // output) then we disallow, since we can't create an output file with the
     // right name without overwriting it. We could remove this oddity by just
@@ -2534,7 +2531,7 @@ void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
 
       // Verify the debug info output.
       if (Args.hasArg(options::OPT_verify_debug_info)) {
-        Action* LastAction = Actions.back();
+        Action *LastAction = Actions.back();
         Actions.pop_back();
         Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
             LastAction, types::TY_Nothing));
@@ -2715,7 +2712,8 @@ void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
             Ty = TC.LookupTypeForExtension(Ext + 1);
 
           if (Ty == types::TY_INVALID) {
-            if (IsCLMode() && (Args.hasArgNoClaim(options::OPT_E) || CCGenDiagnostics))
+            if (IsCLMode() &&
+                (Args.hasArgNoClaim(options::OPT_E) || CCGenDiagnostics))
               Ty = types::TY_CXX;
             else if (CCCIsCPP() || CCGenDiagnostics)
               Ty = types::TY_C;
@@ -2919,7 +2917,7 @@ class OffloadingActionBuilder final {
     virtual void appendLinkDeviceActions(ActionList &AL) {}
 
     /// Append linker host action generated by the builder.
-    virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
+    virtual Action *appendLinkHostActions(ActionList &AL) { return nullptr; }
 
     /// Append linker actions generated by the builder.
     virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
@@ -3624,15 +3622,15 @@ class OffloadingActionBuilder final {
       for (auto &LI : DeviceLinkerInputs) {
 
         types::ID Output = Args.hasArg(options::OPT_emit_llvm)
-                                   ? types::TY_LLVM_BC
-                                   : types::TY_Image;
+                               ? types::TY_LLVM_BC
+                               : types::TY_Image;
 
         auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(LI, Output);
         // Linking all inputs for the current GPU arch.
         // LI contains all the inputs for the linker.
         OffloadAction::DeviceDependences DeviceLinkDeps;
-        DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
-            GpuArchList[I], AssociatedOffloadKind);
+        DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0], GpuArchList[I],
+                           AssociatedOffloadKind);
         Actions.push_back(C.MakeAction<OffloadAction>(
             DeviceLinkDeps, DeviceLinkAction->getType()));
         ++I;
@@ -3641,8 +3639,8 @@ class OffloadingActionBuilder final {
 
       // If emitting LLVM, do not generate final host/device compilation action
       if (Args.hasArg(options::OPT_emit_llvm)) {
-          AL.append(Actions);
-          return;
+        AL.append(Actions);
+        return;
       }
 
       // Create a host object from all the device images by embedding them
@@ -3663,7 +3661,7 @@ class OffloadingActionBuilder final {
       }
     }
 
-    Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
+    Action *appendLinkHostActions(ActionList &AL) override { return AL.back(); }
 
     void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
   };
@@ -3906,7 +3904,7 @@ class OffloadingActionBuilder final {
       return nullptr;
 
     // Let builders add host linking actions.
-    Action* HA = nullptr;
+    Action *HA = nullptr;
     for (DeviceActionBuilder *SB : SpecializedBuilders) {
       if (!SB->isValid())
         continue;
@@ -4001,7 +3999,8 @@ void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
                       getOpts().getOption(options::OPT_frtlib_add_rpath));
     }
     // Emitting LLVM while linking disabled except in HIPAMD Toolchain
-    if (Args.hasArg(options::OPT_emit_llvm) && !Args.hasArg(options::OPT_hip_link))
+    if (Args.hasArg(options::OPT_emit_llvm) &&
+        !Args.hasArg(options::OPT_hip_link))
       Diag(clang::diag::err_drv_emit_llvm_link);
     if (IsCLMode() && LTOMode != LTOK_None &&
         !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
@@ -5340,8 +5339,8 @@ class ToolSelector final {
         continue;
       }
 
-      // This is legal to combine. Append any offload action we found and add the
-      // current input to preprocessor inputs.
+      // This is legal to combine. Append any offload action we found and add
+      // the current input to preprocessor inputs.
       CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
                                     PreprocessJobOffloadActions.end());
       NewInputs.append(PJ->input_begin(), PJ->input_end());
@@ -5364,8 +5363,7 @@ class ToolSelector final {
   /// connected to collapsed actions are updated accordingly. The latter enables
   /// the caller of the selector to process them afterwards instead of just
   /// dropping them. If no suitable tool is found, null will be returned.
-  const Tool *getTool(ActionList &Inputs,
-                      ActionList &CollapsedOffloadAction) {
+  const Tool *getTool(ActionList &Inputs, ActionList &CollapsedOffloadAction) {
     //
     // Get the largest chain of actions that we could combine.
     //
@@ -5408,7 +5406,7 @@ class ToolSelector final {
     return T;
   }
 };
-}
+} // namespace
 
 /// Return a string that uniquely identifies the result of a job. The bound arch
 /// is not necessarily represented in the toolchain's triple -- for example,
@@ -5578,9 +5576,9 @@ InputInfoList Driver::BuildJobsForActionNoCache(
     StringRef ArchName = BAA->getArchName();
 
     if (!ArchName.empty())
-      TC = &getToolChain(C.getArgs(),
-                         computeTargetTriple(*this, TargetTriple,
-                                             C.getArgs(), ArchName));
+      TC = &getToolChain(
+          C.getArgs(),
+          computeTargetTriple(*this, TargetTriple, C.getArgs(), ArchName));
     else
       TC = &C.getDefaultToolChain();
 
@@ -5589,7 +5587,6 @@ InputInfoList Driver::BuildJobsForActionNoCache(
                               TargetDeviceOffloadKind);
   }
 
-
   ActionList Inputs = A->getInputs();
 
   const JobAction *JA = cast<JobAction>(A);
@@ -5723,10 +5720,11 @@ InputInfoList Driver::BuildJobsForActionNoCache(
         /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(A) ||
             !(A->getOffloadingHostActiveKinds() == Action::OFK_None ||
               AtTopLevel));
-    Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
-                                             AtTopLevel, MultipleArchs,
-                                             OffloadingPrefix),
-                       BaseInput);
+    Result =
+        InputInfo(A,
+                  GetNamedOutputPath(C, *JA, BaseInput, BoundArch, AtTopLevel,
+                                     MultipleArchs, OffloadingPrefix),
+                  BaseInput);
     if (T->canEmitIR() && OffloadingPrefix.empty())
       handleTimeTrace(C, Args, JA, BaseInput, Result);
   }
@@ -6059,12 +6057,10 @@ const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
     }
   } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
     NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
-  } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) &&
+  } else if ((JA.getType() == types::TY_Plist ||
+              JA.getType() == types::TY_AST) &&
              C.getArgs().hasArg(options::OPT__SLASH_o)) {
-    StringRef Val =
-        C.getArgs()
-            .getLastArg(options::OPT__SLASH_o)
-            ->getValue();
+    StringRef Val = C.getArgs().getLastArg(options::OPT__SLASH_o)->getValue();
     NamedOutput =
         MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
   } else {
@@ -6380,15 +6376,15 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
     case llvm::Triple::Linux:
     case llvm::Triple::ELFIAMCU:
       if (Target.getArch() == llvm::Triple::hexagon)
-        TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
-                                                             Args);
+        TC =
+            std::make_unique<toolchains::HexagonToolChain>(*this, Target, Args);
       else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
                !Target.hasEnvironment())
         TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
-                                                              Args);
+                                                             Args);
       else if (Target.isPPC())
         TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
-                                                              Args);
+                                                             Args);
       else if (Target.getArch() == llvm::Triple::ve)
         TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
       else if (Target.isOHOSFamily())
@@ -6430,7 +6426,7 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
         break;
       case llvm::Triple::Itanium:
         TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
-                                                                  Args);
+                                                                 Args);
         break;
       case llvm::Triple::MSVC:
       case llvm::Triple::UnknownEnvironment:
@@ -6439,8 +6435,7 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
           TC = std::make_unique<toolchains::CrossWindowsToolChain>(
               *this, Target, Args);
         else
-          TC =
-              std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
+          TC = std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
         break;
       }
       break;
@@ -6473,8 +6468,8 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
         TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
         break;
       case llvm::Triple::hexagon:
-        TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
-                                                             Args);
+        TC =
+            std::make_unique<toolchains::HexagonToolChain>(*this, Target, Args);
         break;
       case llvm::Triple::lanai:
         TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
@@ -6490,8 +6485,7 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
         TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
         break;
       case llvm::Triple::msp430:
-        TC =
-            std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
+        TC = std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
         break;
       case llvm::Triple::riscv32:
       case llvm::Triple::riscv64:
@@ -6667,7 +6661,7 @@ Driver::getOptionVisibilityMask(bool UseDriverMode) const {
     return llvm::opt::Visibility(options::CLOption);
   if (IsDXCMode())
     return llvm::opt::Visibility(options::DXCOption);
-  if (IsFlangMode())  {
+  if (IsFlangMode()) {
     return llvm::opt::Visibility(options::FlangOption);
   }
   return llvm::opt::Visibility(options::ClangOption);
@@ -6747,6 +6741,11 @@ llvm::Error driver::expandResponseFiles(SmallVectorImpl<const char *> &Args,
   // have to manually search for a --driver-mode=cl argument the hard way.
   // Finally, our -cc1 tools don't care which tokenization mode we use because
   // response files written by clang will tokenize the same way in either mode.
+  // clang-format off
+  // Cratels:使用GNU语法解析响应文件,除非我们处于CL模式。有两种方法可以将clang置于CL兼容模式:ProgName是clang-cl或cl,或者--driver-mode=cl在命令行上。
+  // Cratels:正常的命令行解析要到响应文件解析后才能发生,因此我们必须以艰难的方式手动搜索--driver-mode=cl参数
+  // Cratels:最后,我们的-cc1工具不在乎我们使用哪种令牌化模式,因为由clang编写的响应文件将在两种模式下以相同的方式进行令牌化。
+  // clang-format on
   enum { Default, POSIX, Windows } RSPQuoting = Default;
   for (const char *F : Args) {
     if (strcmp(F, "--rsp-quoting=posix") == 0)
diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index 62e64b2b282f39..62c4c85f0c5456 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -225,7 +225,7 @@ static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV,
   return 1;
 }
 
-// Cratels:clang driver的真正入口.main方法在build目录,是有cmake自动生成的.
+// Cratels:clang driver的真正入口.main方法在build目录,是有cmake自动生成的
 int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
   noteBottomOfStack();
   llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
@@ -237,7 +237,7 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
     return 1;
 
   // clang-format off
-  // Cratels:初始化所有的target.如果在cmake configure的时候指定了target,这只会初始化对应的target,否则就初始化默认的targets.
+  // Cratels:初始化所有的target.如果在cmake configure的时候指定了target,这只会初始化对应的target,否则就初始化默认的targets
   // clang-format on
   llvm::InitializeAllTargets();
 
@@ -247,9 +247,23 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
   const char *ProgName =
       ToolContext.NeedsPrependArg ? ToolContext.PrependArg : ToolContext.Path;
 
+  // clang-format off
+  // Cratels:clang-cl 是一个Clang驱动器的另一个命令行接口的选择,被设计用来兼容Visual C++ 的编译器cl.exe
+  // Cratels:clang --driver-mode可以用来指定 clang driver 的工作模式
+  // Cratels:There are two ways to put clang in CL compatibility mode: ProgName is either clang-cl or cl, or --driver-mode=cl is on the command line
+  // clang-format on
   bool ClangCLMode =
       IsClangCL(getDriverMode(ProgName, llvm::ArrayRef(Args).slice(1)));
 
+  // clang-format off
+  // Cratels:On some systems (such as older UNIX systems and certain Windows variants) command-lines have relatively limited lengths.
+  // Cratels: Windows compilers therefore support "response files". These files are mentioned on the command-line (using the "@file") syntax.
+  // Cratels: The compiler reads these files and inserts the contents into argv, thereby working around the command-line length limits.
+  // Cratels:一些编译环境(比如 windows)对命令行的长度有限制,不能超过 127字符,但是现实环境中确实存在很长命令行的需求,此时可以使用 response file 来绕过这个限制
+  // Cratels:详细信息请看:https://learn.microsoft.com/en-us/cpp/build/reference/at-specify-a-compiler-response-file?view=msvc-170
+  // Cratels:见本目录的 response_file.md文档
+  // Cratels:这里的操作就是展开 response file 并将其内容写入 Args 里面
+  // clang-format on
   if (llvm::Error Err = expandResponseFiles(Args, ClangCLMode, A)) {
     llvm::errs() << toString(std::move(Err)) << '\n';
     return 1;
diff --git a/clang/tools/driver/response_file.md b/clang/tools/driver/response_file.md
new file mode 100644
index 00000000000000..5bb3436591e6cc
--- /dev/null
+++ b/clang/tools/driver/response_file.md
@@ -0,0 +1,22 @@
+A response file in the context of the Clang compiler (which is part of the LLVM project) is a plain text file that contains command-line options for the compiler. Response files are useful in situations where the number of command-line arguments is too large to be handled directly by the shell or when you want to separate the build commands from the build system for better organization or to work around command line length limitations.
+Here's how you can use a response file with Clang:
+1. **Create the Response File**: Create a text file with the desired filename, for example, `clang.opts`. Inside this file, you will list all the command-line options that you would normally pass to Clang, each on a new line. For example:
+    ```
+    -I/usr/local/include
+    -DDEBUG
+    -O2
+    -o myprogram
+    source1.c
+    source2.c
+    ```
+2. **Call Clang with the Response File**: To use the response file, you pass its name to Clang with the `@` symbol prefix. For example:
+    ```
+    clang @clang.opts
+    ```
+When Clang encounters the `@` symbol, it treats the following argument as the name of the response file and reads the command-line options from there.
+Here are some things to keep in mind when using response files:
+- The response file can contain any command-line option that you would normally use with Clang.
+- If you need to pass an option that starts with the `@` symbol, you can escape it by using `@@` in the response file.
+- If a line in the response file starts with `#`, it is treated as a comment and ignored.
+- Response files can be particularly useful in build systems like CMake, where you might have complex build configurations that generate long command lines.
+Using response files can greatly simplify complex build setups and make them more maintainable.



More information about the cfe-commits mailing list