xref: /freebsd/contrib/llvm-project/clang/tools/driver/cc1_main.cpp (revision 0b37c1590418417c894529d371800dfac71ef887)
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 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, &EnvEnd) == 2) {
100 #if defined(__GNUC__) && !defined(__clang__)
101 #pragma GCC diagnostic pop
102 #endif
103       Usage = StackPtr < EnvEnd ? EnvEnd - StackPtr : StackPtr - EnvEnd;
104     }
105     fclose(StatFile);
106   }
107   return Usage;
108 }
109 
110 #include <alloca.h>
111 
112 LLVM_ATTRIBUTE_NOINLINE
113 static void ensureStackAddressSpace() {
114   // Linux kernels prior to 4.1 will sometimes locate the heap of a PIE binary
115   // relatively close to the stack (they are only guaranteed to be 128MiB
116   // apart). This results in crashes if we happen to heap-allocate more than
117   // 128MiB before we reach our stack high-water mark.
118   //
119   // To avoid these crashes, ensure that we have sufficient virtual memory
120   // pages allocated before we start running.
121   size_t Curr = getCurrentStackAllocation();
122   const int kTargetStack = DesiredStackSize - 256 * 1024;
123   if (Curr < kTargetStack) {
124     volatile char *volatile Alloc =
125         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 &&
143       rlim.rlim_cur < rlim_t(DesiredStackSize)) {
144     // Try to allocate sufficient stack.
145     if (rlim.rlim_max == RLIM_INFINITY ||
146         rlim.rlim_max >= rlim_t(DesiredStackSize))
147       rlim.rlim_cur = DesiredStackSize;
148     else if (rlim.rlim_cur == rlim.rlim_max)
149       return;
150     else
151       rlim.rlim_cur = rlim.rlim_max;
152 
153     if (setrlimit(RLIMIT_STACK, &rlim) != 0 ||
154         rlim.rlim_cur != DesiredStackSize)
155       return;
156   }
157 
158   // We should now have a stack of size at least DesiredStackSize. Ensure
159   // that we can actually use that much, if necessary.
160   ensureStackAddressSpace();
161 }
162 #else
163 static void ensureSufficientStack() {}
164 #endif
165 
166 /// Print supported cpus of the given target.
167 static int PrintSupportedCPUs(std::string TargetStr) {
168   std::string Error;
169   const llvm::Target *TheTarget =
170       llvm::TargetRegistry::lookupTarget(TargetStr, Error);
171   if (!TheTarget) {
172     llvm::errs() << Error;
173     return 1;
174   }
175 
176   // the target machine will handle the mcpu printing
177   llvm::TargetOptions Options;
178   std::unique_ptr<llvm::TargetMachine> TheTargetMachine(
179       TheTarget->createTargetMachine(TargetStr, "", "+cpuHelp", Options, None));
180   return 0;
181 }
182 
183 int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
184   ensureSufficientStack();
185 
186   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
187   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
188 
189   // Register the support for object-file-wrapped Clang modules.
190   auto PCHOps = Clang->getPCHContainerOperations();
191   PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
192   PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
193 
194   // Initialize targets first, so that --version shows registered targets.
195   llvm::InitializeAllTargets();
196   llvm::InitializeAllTargetMCs();
197   llvm::InitializeAllAsmPrinters();
198   llvm::InitializeAllAsmParsers();
199 
200   // Buffer diagnostics from argument parsing so that we can output them using a
201   // well formed diagnostic object.
202   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
203   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
204   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
205   bool Success =
206       CompilerInvocation::CreateFromArgs(Clang->getInvocation(), Argv, Diags);
207 
208   if (Clang->getFrontendOpts().TimeTrace) {
209     llvm::timeTraceProfilerInitialize(
210         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 &&
218       Clang->getHeaderSearchOpts().ResourceDir.empty())
219     Clang->getHeaderSearchOpts().ResourceDir =
220       CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
221 
222   // Create the actual diagnostics engine.
223   Clang->createDiagnostics();
224   if (!Clang->hasDiagnostics())
225     return 1;
226 
227   // Set an error handler, so that any LLVM backend diagnostics go through our
228   // error handler.
229   llvm::install_fatal_error_handler(LLVMErrorHandler,
230                                   static_cast<void*>(&Clang->getDiagnostics()));
231 
232   DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
233   if (!Success)
234     return 1;
235 
236   // Execute the frontend actions.
237   {
238     llvm::TimeTraceScope TimeScope("ExecuteCompiler");
239     Success = ExecuteCompilerInvocation(Clang.get());
240   }
241 
242   // If any timers were active but haven't been destroyed yet, print their
243   // results now.  This happens in -disable-free mode.
244   llvm::TimerGroup::printAll(llvm::errs());
245   llvm::TimerGroup::clearAll();
246 
247   if (llvm::timeTraceProfilerEnabled()) {
248     SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
249     llvm::sys::path::replace_extension(Path, "json");
250     if (auto profilerOutput =
251             Clang->createOutputFile(Path.str(),
252                                     /*Binary=*/false,
253                                     /*RemoveFileOnSignal=*/false, "",
254                                     /*Extension=*/"json",
255                                     /*useTemporary=*/false)) {
256 
257       llvm::timeTraceProfilerWrite(*profilerOutput);
258       // FIXME(ibiryukov): make profilerOutput flush in destructor instead.
259       profilerOutput->flush();
260       llvm::timeTraceProfilerCleanup();
261     }
262   }
263 
264   // Our error handler depends on the Diagnostics object, which we're
265   // potentially about to delete. Uninstall the handler now so that any
266   // later errors use the default handling behavior instead.
267   llvm::remove_fatal_error_handler();
268 
269   // When running with -disable-free, don't do any destruction or shutdown.
270   if (Clang->getFrontendOpts().DisableFree) {
271     llvm::BuryPointer(std::move(Clang));
272     return !Success;
273   }
274 
275   return !Success;
276 }
277