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