clang_invocation.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/base/clang_invocation.h"
  5. #include <filesystem>
  6. #include <string>
  7. #include "clang/Driver/CreateInvocationFromArgs.h"
  8. #include "clang/Frontend/CompilerInstance.h"
  9. #include "clang/Frontend/Utils.h"
  10. #include "common/string_helpers.h"
  11. #include "llvm/ADT/ArrayRef.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/Support/FormatVariadic.h"
  15. namespace Carbon {
  16. // The fake file name to use for the synthesized includes file.
  17. static constexpr const char IncludesFileName[] = "<carbon Cpp imports>";
  18. namespace {
  19. // Used to convert diagnostics from the Clang driver to Carbon diagnostics.
  20. class ClangDriverDiagnosticConsumer : public clang::DiagnosticConsumer {
  21. public:
  22. // Creates an instance with the location that triggers calling Clang.
  23. // `context` must not be null.
  24. explicit ClangDriverDiagnosticConsumer(Diagnostics::NoLocEmitter* emitter)
  25. : emitter_(emitter) {}
  26. // Generates a Carbon warning for each Clang warning and a Carbon error for
  27. // each Clang error or fatal.
  28. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  29. const clang::Diagnostic& info) -> void override {
  30. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  31. llvm::SmallString<256> message;
  32. info.FormatDiagnostic(message);
  33. switch (diag_level) {
  34. case clang::DiagnosticsEngine::Ignored:
  35. case clang::DiagnosticsEngine::Note:
  36. case clang::DiagnosticsEngine::Remark: {
  37. // TODO: Emit notes and remarks.
  38. break;
  39. }
  40. case clang::DiagnosticsEngine::Warning:
  41. case clang::DiagnosticsEngine::Error:
  42. case clang::DiagnosticsEngine::Fatal: {
  43. CARBON_DIAGNOSTIC(CppInteropDriverWarning, Warning, "{0}", std::string);
  44. CARBON_DIAGNOSTIC(CppInteropDriverError, Error, "{0}", std::string);
  45. emitter_->Emit(diag_level == clang::DiagnosticsEngine::Warning
  46. ? CppInteropDriverWarning
  47. : CppInteropDriverError,
  48. message.str().str());
  49. break;
  50. }
  51. }
  52. }
  53. private:
  54. // Diagnostic emitter. Note that driver diagnostics don't have meaningful
  55. // locations attached.
  56. Diagnostics::NoLocEmitter* emitter_;
  57. };
  58. } // namespace
  59. auto BuildClangInvocation(Diagnostics::Consumer& consumer,
  60. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  61. const InstallPaths& install_paths,
  62. llvm::StringRef target_str,
  63. llvm::ArrayRef<llvm::StringRef> extra_args)
  64. -> std::unique_ptr<clang::CompilerInvocation> {
  65. Diagnostics::ErrorTrackingConsumer error_tracker(consumer);
  66. Diagnostics::NoLocEmitter emitter(&error_tracker);
  67. ClangDriverDiagnosticConsumer diagnostics_consumer(&emitter);
  68. llvm::SmallVector<std::string> args;
  69. args.push_back("--start-no-unused-arguments");
  70. AppendDefaultClangArgs(install_paths, target_str, args);
  71. args.push_back("--end-no-unused-arguments");
  72. args.append({
  73. llvm::formatv("--target={0}", target_str).str(),
  74. // Add our include file name as the input file, and force it to be
  75. // interpreted as C++.
  76. "-x",
  77. "c++",
  78. IncludesFileName,
  79. });
  80. // The clang driver inconveniently wants an array of `const char*`, so convert
  81. // the arguments.
  82. llvm::BumpPtrAllocator alloc;
  83. llvm::SmallVector<const char*> cstr_args = BuildCStrArgs(
  84. install_paths.clang_path().native(), args, extra_args, alloc);
  85. // Build a diagnostics engine. Note that we don't have any diagnostic options
  86. // yet; they're produced by running the driver.
  87. clang::DiagnosticOptions driver_diag_opts;
  88. llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> driver_diags(
  89. clang::CompilerInstance::createDiagnostics(*fs, driver_diag_opts,
  90. &diagnostics_consumer,
  91. /*ShouldOwnClient=*/false));
  92. // Ask the driver to process the arguments and build a corresponding clang
  93. // frontend invocation.
  94. auto invocation =
  95. clang::createInvocation(cstr_args, {.Diags = driver_diags, .VFS = fs});
  96. // If Clang produced an error, throw away its invocation.
  97. if (error_tracker.seen_error()) {
  98. return nullptr;
  99. }
  100. if (invocation) {
  101. // Do not emit Clang's name and version as the creator of the output file.
  102. invocation->getCodeGenOpts().EmitVersionIdentMetadata = false;
  103. invocation->getCodeGenOpts().DiscardValueNames = false;
  104. }
  105. return invocation;
  106. }
  107. auto AppendDefaultClangArgs(const InstallPaths& install_paths,
  108. llvm::StringRef target_str,
  109. llvm::SmallVectorImpl<std::string>& args) -> void {
  110. args.append({
  111. // Enable PIE by default, but allow it to be overridden by Clang
  112. // arguments. Clang's default is configurable, but we'd like our
  113. // defaults to be more stable.
  114. // TODO: Decide if we want this.
  115. "-fPIE",
  116. // Override runtime library defaults.
  117. //
  118. // TODO: We should consider if there is a reasonable way to build Clang
  119. // with its configuration macros set to establish these defaults rather
  120. // than doing it with runtime flags.
  121. "-rtlib=compiler-rt",
  122. "-unwindlib=libunwind",
  123. "-stdlib=libc++",
  124. // Override the default linker to use.
  125. "-fuse-ld=lld",
  126. });
  127. // Add target-specific flags.
  128. llvm::Triple triple(target_str);
  129. switch (triple.getOS()) {
  130. case llvm::Triple::Darwin:
  131. case llvm::Triple::MacOSX:
  132. // On macOS we need to set the sysroot to a viable SDK. Currently, this
  133. // hard codes the path to be the unversioned symlink. The prefix is also
  134. // hard coded in Homebrew and so this seems likely to work reasonably
  135. // well. Homebrew and I suspect the Xcode Clang both have this hard coded
  136. // at build time, so this seems reasonably safe but we can revisit if/when
  137. // needed.
  138. args.push_back(
  139. "--sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk");
  140. // We also need to insist on a modern linker, otherwise the driver tries
  141. // too old and deprecated flags. The specific number here comes from an
  142. // inspection of the Clang driver source code to understand where features
  143. // were enabled, and this appears to be the latest version to control
  144. // driver behavior.
  145. //
  146. // TODO: We should replace this with use of `lld` eventually.
  147. args.push_back("-mlinker-version=705");
  148. break;
  149. default:
  150. break;
  151. }
  152. // Append our exact header search paths for the various parts of the C++
  153. // standard library headers as we don't build a single unified tree.
  154. for (const std::filesystem::path& runtime_path :
  155. {install_paths.libunwind_path(), install_paths.libcxx_path(),
  156. install_paths.libcxxabi_path()}) {
  157. args.push_back(
  158. llvm::formatv("-stdlib++-isystem{0}", runtime_path / "include").str());
  159. }
  160. }
  161. } // namespace Carbon