cc1_main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. //===-- cc1_main.cpp - Clang CC1 Compiler Frontend ------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This is the entry point to the clang -cc1 functionality, which implements the
  10. // core compiler functionality along with a number of additional tools for
  11. // demonstration and testing purposes.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Basic/Stack.h"
  15. #include "clang/Basic/TargetOptions.h"
  16. #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
  17. #include "clang/Config/config.h"
  18. #include "clang/Driver/DriverDiagnostic.h"
  19. #include "clang/Driver/Options.h"
  20. #include "clang/Frontend/CompilerInstance.h"
  21. #include "clang/Frontend/CompilerInvocation.h"
  22. #include "clang/Frontend/FrontendDiagnostic.h"
  23. #include "clang/Frontend/TextDiagnosticBuffer.h"
  24. #include "clang/Frontend/TextDiagnosticPrinter.h"
  25. #include "clang/Frontend/Utils.h"
  26. #include "clang/FrontendTool/Utils.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/Config/llvm-config.h"
  29. #include "llvm/LinkAllPasses.h"
  30. #include "llvm/MC/TargetRegistry.h"
  31. #include "llvm/Option/Arg.h"
  32. #include "llvm/Option/ArgList.h"
  33. #include "llvm/Option/OptTable.h"
  34. #include "llvm/Support/BuryPointer.h"
  35. #include "llvm/Support/Compiler.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/ManagedStatic.h"
  38. #include "llvm/Support/Path.h"
  39. #include "llvm/Support/Process.h"
  40. #include "llvm/Support/Signals.h"
  41. #include "llvm/Support/TargetSelect.h"
  42. #include "llvm/Support/TimeProfiler.h"
  43. #include "llvm/Support/Timer.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include "llvm/Target/TargetMachine.h"
  46. #include <cstdio>
  47. #ifdef CLANG_HAVE_RLIMITS
  48. #include <sys/resource.h>
  49. #endif
  50. using namespace clang;
  51. using namespace llvm::opt;
  52. //===----------------------------------------------------------------------===//
  53. // Main driver
  54. //===----------------------------------------------------------------------===//
  55. static void LLVMErrorHandler(void *UserData, const char *Message,
  56. bool GenCrashDiag) {
  57. DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
  58. Diags.Report(diag::err_fe_error_backend) << Message;
  59. // Run the interrupt handlers to make sure any special cleanups get done, in
  60. // particular that we remove files registered with RemoveFileOnSignal.
  61. llvm::sys::RunInterruptHandlers();
  62. // We cannot recover from llvm errors. When reporting a fatal error, exit
  63. // with status 70 to generate crash diagnostics. For BSD systems this is
  64. // defined as an internal software error. Otherwise, exit with status 1.
  65. llvm::sys::Process::Exit(GenCrashDiag ? 70 : 1);
  66. }
  67. #ifdef CLANG_HAVE_RLIMITS
  68. #if defined(__linux__) && defined(__PIE__)
  69. static size_t getCurrentStackAllocation() {
  70. // If we can't compute the current stack usage, allow for 512K of command
  71. // line arguments and environment.
  72. size_t Usage = 512 * 1024;
  73. if (FILE *StatFile = fopen("/proc/self/stat", "r")) {
  74. // We assume that the stack extends from its current address to the end of
  75. // the environment space. In reality, there is another string literal (the
  76. // program name) after the environment, but this is close enough (we only
  77. // need to be within 100K or so).
  78. unsigned long StackPtr, EnvEnd;
  79. // Disable silly GCC -Wformat warning that complains about length
  80. // modifiers on ignored format specifiers. We want to retain these
  81. // for documentation purposes even though they have no effect.
  82. #if defined(__GNUC__) && !defined(__clang__)
  83. #pragma GCC diagnostic push
  84. #pragma GCC diagnostic ignored "-Wformat"
  85. #endif
  86. if (fscanf(StatFile,
  87. "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu "
  88. "%*lu %*ld %*ld %*ld %*ld %*ld %*ld %*llu %*lu %*ld %*lu %*lu "
  89. "%*lu %*lu %lu %*lu %*lu %*lu %*lu %*lu %*llu %*lu %*lu %*d %*d "
  90. "%*u %*u %*llu %*lu %*ld %*lu %*lu %*lu %*lu %*lu %*lu %lu %*d",
  91. &StackPtr, &EnvEnd) == 2) {
  92. #if defined(__GNUC__) && !defined(__clang__)
  93. #pragma GCC diagnostic pop
  94. #endif
  95. Usage = StackPtr < EnvEnd ? EnvEnd - StackPtr : StackPtr - EnvEnd;
  96. }
  97. fclose(StatFile);
  98. }
  99. return Usage;
  100. }
  101. #include <alloca.h>
  102. LLVM_ATTRIBUTE_NOINLINE
  103. static void ensureStackAddressSpace() {
  104. // Linux kernels prior to 4.1 will sometimes locate the heap of a PIE binary
  105. // relatively close to the stack (they are only guaranteed to be 128MiB
  106. // apart). This results in crashes if we happen to heap-allocate more than
  107. // 128MiB before we reach our stack high-water mark.
  108. //
  109. // To avoid these crashes, ensure that we have sufficient virtual memory
  110. // pages allocated before we start running.
  111. size_t Curr = getCurrentStackAllocation();
  112. const int kTargetStack = DesiredStackSize - 256 * 1024;
  113. if (Curr < kTargetStack) {
  114. volatile char *volatile Alloc =
  115. static_cast<volatile char *>(alloca(kTargetStack - Curr));
  116. Alloc[0] = 0;
  117. Alloc[kTargetStack - Curr - 1] = 0;
  118. }
  119. }
  120. #else
  121. static void ensureStackAddressSpace() {}
  122. #endif
  123. /// Attempt to ensure that we have at least 8MiB of usable stack space.
  124. static void ensureSufficientStack() {
  125. struct rlimit rlim;
  126. if (getrlimit(RLIMIT_STACK, &rlim) != 0)
  127. return;
  128. // Increase the soft stack limit to our desired level, if necessary and
  129. // possible.
  130. if (rlim.rlim_cur != RLIM_INFINITY &&
  131. rlim.rlim_cur < rlim_t(DesiredStackSize)) {
  132. // Try to allocate sufficient stack.
  133. if (rlim.rlim_max == RLIM_INFINITY ||
  134. rlim.rlim_max >= rlim_t(DesiredStackSize))
  135. rlim.rlim_cur = DesiredStackSize;
  136. else if (rlim.rlim_cur == rlim.rlim_max)
  137. return;
  138. else
  139. rlim.rlim_cur = rlim.rlim_max;
  140. if (setrlimit(RLIMIT_STACK, &rlim) != 0 ||
  141. rlim.rlim_cur != DesiredStackSize)
  142. return;
  143. }
  144. // We should now have a stack of size at least DesiredStackSize. Ensure
  145. // that we can actually use that much, if necessary.
  146. ensureStackAddressSpace();
  147. }
  148. #else
  149. static void ensureSufficientStack() {}
  150. #endif
  151. /// Print supported cpus of the given target.
  152. static int PrintSupportedCPUs(std::string TargetStr) {
  153. std::string Error;
  154. const llvm::Target *TheTarget =
  155. llvm::TargetRegistry::lookupTarget(TargetStr, Error);
  156. if (!TheTarget) {
  157. llvm::errs() << Error;
  158. return 1;
  159. }
  160. // the target machine will handle the mcpu printing
  161. llvm::TargetOptions Options;
  162. std::unique_ptr<llvm::TargetMachine> TheTargetMachine(
  163. TheTarget->createTargetMachine(TargetStr, "", "+cpuhelp", Options,
  164. std::nullopt));
  165. return 0;
  166. }
  167. int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
  168. ensureSufficientStack();
  169. std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
  170. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  171. // Register the support for object-file-wrapped Clang modules.
  172. auto PCHOps = Clang->getPCHContainerOperations();
  173. PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
  174. PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
  175. // Initialize targets first, so that --version shows registered targets.
  176. llvm::InitializeAllTargets();
  177. llvm::InitializeAllTargetMCs();
  178. llvm::InitializeAllAsmPrinters();
  179. llvm::InitializeAllAsmParsers();
  180. // Buffer diagnostics from argument parsing so that we can output them using a
  181. // well formed diagnostic object.
  182. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  183. TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
  184. DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
  185. // Setup round-trip remarks for the DiagnosticsEngine used in CreateFromArgs.
  186. if (find(Argv, StringRef("-Rround-trip-cc1-args")) != Argv.end())
  187. Diags.setSeverity(diag::remark_cc1_round_trip_generated,
  188. diag::Severity::Remark, {});
  189. bool Success = CompilerInvocation::CreateFromArgs(Clang->getInvocation(),
  190. Argv, Diags, Argv0);
  191. if (Clang->getFrontendOpts().TimeTrace ||
  192. !Clang->getFrontendOpts().TimeTracePath.empty()) {
  193. Clang->getFrontendOpts().TimeTrace = 1;
  194. llvm::timeTraceProfilerInitialize(
  195. Clang->getFrontendOpts().TimeTraceGranularity, Argv0);
  196. }
  197. // --print-supported-cpus takes priority over the actual compilation.
  198. if (Clang->getFrontendOpts().PrintSupportedCPUs)
  199. return PrintSupportedCPUs(Clang->getTargetOpts().Triple);
  200. // Infer the builtin include path if unspecified.
  201. if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
  202. Clang->getHeaderSearchOpts().ResourceDir.empty())
  203. Clang->getHeaderSearchOpts().ResourceDir =
  204. CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
  205. // Create the actual diagnostics engine.
  206. Clang->createDiagnostics();
  207. if (!Clang->hasDiagnostics())
  208. return 1;
  209. // Set an error handler, so that any LLVM backend diagnostics go through our
  210. // error handler.
  211. llvm::install_fatal_error_handler(LLVMErrorHandler,
  212. static_cast<void*>(&Clang->getDiagnostics()));
  213. DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
  214. if (!Success) {
  215. Clang->getDiagnosticClient().finish();
  216. return 1;
  217. }
  218. // Execute the frontend actions.
  219. {
  220. llvm::TimeTraceScope TimeScope("ExecuteCompiler");
  221. Success = ExecuteCompilerInvocation(Clang.get());
  222. }
  223. // If any timers were active but haven't been destroyed yet, print their
  224. // results now. This happens in -disable-free mode.
  225. llvm::TimerGroup::printAll(llvm::errs());
  226. llvm::TimerGroup::clearAll();
  227. if (llvm::timeTraceProfilerEnabled()) {
  228. SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
  229. llvm::sys::path::replace_extension(Path, "json");
  230. if (!Clang->getFrontendOpts().TimeTracePath.empty()) {
  231. // replace the suffix to '.json' directly
  232. SmallString<128> TracePath(Clang->getFrontendOpts().TimeTracePath);
  233. if (llvm::sys::fs::is_directory(TracePath))
  234. llvm::sys::path::append(TracePath, llvm::sys::path::filename(Path));
  235. Path.assign(TracePath);
  236. }
  237. if (auto profilerOutput = Clang->createOutputFile(
  238. Path.str(), /*Binary=*/false, /*RemoveFileOnSignal=*/false,
  239. /*useTemporary=*/false)) {
  240. llvm::timeTraceProfilerWrite(*profilerOutput);
  241. profilerOutput.reset();
  242. llvm::timeTraceProfilerCleanup();
  243. Clang->clearOutputFiles(false);
  244. }
  245. }
  246. // Our error handler depends on the Diagnostics object, which we're
  247. // potentially about to delete. Uninstall the handler now so that any
  248. // later errors use the default handling behavior instead.
  249. llvm::remove_fatal_error_handler();
  250. // When running with -disable-free, don't do any destruction or shutdown.
  251. if (Clang->getFrontendOpts().DisableFree) {
  252. llvm::BuryPointer(std::move(Clang));
  253. return !Success;
  254. }
  255. return !Success;
  256. }