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/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/Signals.h"
40 #include "llvm/Support/TargetRegistry.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 
48 #ifdef CLANG_HAVE_RLIMITS
49 #include <sys/resource.h>
50 #endif
51 
52 using namespace clang;
53 using namespace llvm::opt;
54 
55 //===----------------------------------------------------------------------===//
56 // Main driver
57 //===----------------------------------------------------------------------===//
58 
59 static void LLVMErrorHandler(void *UserData, const std::string &Message,
60                              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   exit(GenCrashDiag ? 70 : 1);
73 }
74 
75 #ifdef LINK_POLLY_INTO_TOOLS
76 namespace polly {
77 void initializePollyPasses(llvm::PassRegistry &Registry);
78 }
79 #endif
80 
81 #ifdef CLANG_HAVE_RLIMITS
82 #if defined(__linux__) && defined(__PIE__)
83 static size_t getCurrentStackAllocation() {
84   // If we can't compute the current stack usage, allow for 512K of command
85   // line arguments and environment.
86   size_t Usage = 512 * 1024;
87   if (FILE *StatFile = fopen("/proc/self/stat", "r")) {
88     // We assume that the stack extends from its current address to the end of
89     // the environment space. In reality, there is another string literal (the
90     // program name) after the environment, but this is close enough (we only
91     // need to be within 100K or so).
92     unsigned long StackPtr, EnvEnd;
93     // Disable silly GCC -Wformat warning that complains about length
94     // modifiers on ignored format specifiers. We want to retain these
95     // for documentation purposes even though they have no effect.
96 #if defined(__GNUC__) && !defined(__clang__)
97 #pragma GCC diagnostic push
98 #pragma GCC diagnostic ignored "-Wformat"
99 #endif
100     if (fscanf(StatFile,
101                "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu "
102                "%*lu %*ld %*ld %*ld %*ld %*ld %*ld %*llu %*lu %*ld %*lu %*lu "
103                "%*lu %*lu %lu %*lu %*lu %*lu %*lu %*lu %*llu %*lu %*lu %*d %*d "
104                "%*u %*u %*llu %*lu %*ld %*lu %*lu %*lu %*lu %*lu %*lu %lu %*d",
105                &StackPtr, &EnvEnd) == 2) {
106 #if defined(__GNUC__) && !defined(__clang__)
107 #pragma GCC diagnostic pop
108 #endif
109       Usage = StackPtr < EnvEnd ? EnvEnd - StackPtr : StackPtr - EnvEnd;
110     }
111     fclose(StatFile);
112   }
113   return Usage;
114 }
115 
116 #include <alloca.h>
117 
118 LLVM_ATTRIBUTE_NOINLINE
119 static void ensureStackAddressSpace() {
120   // Linux kernels prior to 4.1 will sometimes locate the heap of a PIE binary
121   // relatively close to the stack (they are only guaranteed to be 128MiB
122   // apart). This results in crashes if we happen to heap-allocate more than
123   // 128MiB before we reach our stack high-water mark.
124   //
125   // To avoid these crashes, ensure that we have sufficient virtual memory
126   // pages allocated before we start running.
127   size_t Curr = getCurrentStackAllocation();
128   const int kTargetStack = DesiredStackSize - 256 * 1024;
129   if (Curr < kTargetStack) {
130     volatile char *volatile Alloc =
131         static_cast<volatile char *>(alloca(kTargetStack - Curr));
132     Alloc[0] = 0;
133     Alloc[kTargetStack - Curr - 1] = 0;
134   }
135 }
136 #else
137 static void ensureStackAddressSpace() {}
138 #endif
139 
140 /// Attempt to ensure that we have at least 8MiB of usable stack space.
141 static void ensureSufficientStack() {
142   struct rlimit rlim;
143   if (getrlimit(RLIMIT_STACK, &rlim) != 0)
144     return;
145 
146   // Increase the soft stack limit to our desired level, if necessary and
147   // possible.
148   if (rlim.rlim_cur != RLIM_INFINITY &&
149       rlim.rlim_cur < rlim_t(DesiredStackSize)) {
150     // Try to allocate sufficient stack.
151     if (rlim.rlim_max == RLIM_INFINITY ||
152         rlim.rlim_max >= rlim_t(DesiredStackSize))
153       rlim.rlim_cur = DesiredStackSize;
154     else if (rlim.rlim_cur == rlim.rlim_max)
155       return;
156     else
157       rlim.rlim_cur = rlim.rlim_max;
158 
159     if (setrlimit(RLIMIT_STACK, &rlim) != 0 ||
160         rlim.rlim_cur != DesiredStackSize)
161       return;
162   }
163 
164   // We should now have a stack of size at least DesiredStackSize. Ensure
165   // that we can actually use that much, if necessary.
166   ensureStackAddressSpace();
167 }
168 #else
169 static void ensureSufficientStack() {}
170 #endif
171 
172 /// Print supported cpus of the given target.
173 static int PrintSupportedCPUs(std::string TargetStr) {
174   std::string Error;
175   const llvm::Target *TheTarget =
176       llvm::TargetRegistry::lookupTarget(TargetStr, Error);
177   if (!TheTarget) {
178     llvm::errs() << Error;
179     return 1;
180   }
181 
182   // the target machine will handle the mcpu printing
183   llvm::TargetOptions Options;
184   std::unique_ptr<llvm::TargetMachine> TheTargetMachine(
185       TheTarget->createTargetMachine(TargetStr, "", "+cpuHelp", Options, None));
186   return 0;
187 }
188 
189 int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
190   ensureSufficientStack();
191 
192   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
193   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
194 
195   // Register the support for object-file-wrapped Clang modules.
196   auto PCHOps = Clang->getPCHContainerOperations();
197   PCHOps->registerWriter(llvm::make_unique<ObjectFilePCHContainerWriter>());
198   PCHOps->registerReader(llvm::make_unique<ObjectFilePCHContainerReader>());
199 
200   // Initialize targets first, so that --version shows registered targets.
201   llvm::InitializeAllTargets();
202   llvm::InitializeAllTargetMCs();
203   llvm::InitializeAllAsmPrinters();
204   llvm::InitializeAllAsmParsers();
205 
206 #ifdef LINK_POLLY_INTO_TOOLS
207   llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
208   polly::initializePollyPasses(Registry);
209 #endif
210 
211   // Buffer diagnostics from argument parsing so that we can output them using a
212   // well formed diagnostic object.
213   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
214   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
215   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
216   bool Success = CompilerInvocation::CreateFromArgs(
217       Clang->getInvocation(), Argv.begin(), Argv.end(), Diags);
218 
219   if (Clang->getFrontendOpts().TimeTrace)
220     llvm::timeTraceProfilerInitialize();
221 
222   // --print-supported-cpus takes priority over the actual compilation.
223   if (Clang->getFrontendOpts().PrintSupportedCPUs)
224     return PrintSupportedCPUs(Clang->getTargetOpts().Triple);
225 
226   // Infer the builtin include path if unspecified.
227   if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
228       Clang->getHeaderSearchOpts().ResourceDir.empty())
229     Clang->getHeaderSearchOpts().ResourceDir =
230       CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
231 
232   // Create the actual diagnostics engine.
233   Clang->createDiagnostics();
234   if (!Clang->hasDiagnostics())
235     return 1;
236 
237   // Set an error handler, so that any LLVM backend diagnostics go through our
238   // error handler.
239   llvm::install_fatal_error_handler(LLVMErrorHandler,
240                                   static_cast<void*>(&Clang->getDiagnostics()));
241 
242   DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
243   if (!Success)
244     return 1;
245 
246   // Execute the frontend actions.
247   {
248     llvm::TimeTraceScope TimeScope("ExecuteCompiler", StringRef(""));
249     Success = ExecuteCompilerInvocation(Clang.get());
250   }
251 
252   // If any timers were active but haven't been destroyed yet, print their
253   // results now.  This happens in -disable-free mode.
254   llvm::TimerGroup::printAll(llvm::errs());
255 
256   if (llvm::timeTraceProfilerEnabled()) {
257     SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
258     llvm::sys::path::replace_extension(Path, "json");
259     auto profilerOutput =
260         Clang->createOutputFile(Path.str(),
261                                 /*Binary=*/false,
262                                 /*RemoveFileOnSignal=*/false, "",
263                                 /*Extension=*/"json",
264                                 /*useTemporary=*/false);
265 
266     llvm::timeTraceProfilerWrite(*profilerOutput);
267     // FIXME(ibiryukov): make profilerOutput flush in destructor instead.
268     profilerOutput->flush();
269     llvm::timeTraceProfilerCleanup();
270 
271     llvm::errs() << "Time trace json-file dumped to " << Path.str() << "\n";
272     llvm::errs()
273         << "Use chrome://tracing or Speedscope App "
274            "(https://www.speedscope.app) for flamegraph visualization\n";
275   }
276 
277   // Our error handler depends on the Diagnostics object, which we're
278   // potentially about to delete. Uninstall the handler now so that any
279   // later errors use the default handling behavior instead.
280   llvm::remove_fatal_error_handler();
281 
282   // When running with -disable-free, don't do any destruction or shutdown.
283   if (Clang->getFrontendOpts().DisableFree) {
284     llvm::BuryPointer(std::move(Clang));
285     return !Success;
286   }
287 
288   return !Success;
289 }
290