xref: /freebsd/contrib/llvm-project/clang/tools/driver/cc1_main.cpp (revision 2e3507c25e42292b45a5482e116d278f5515d04d)
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,
61                              bool GenCrashDiag) {
62   DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
63 
64   Diags.Report(diag::err_fe_error_backend) << Message;
65 
66   // Run the interrupt handlers to make sure any special cleanups get done, in
67   // particular that we remove files registered with RemoveFileOnSignal.
68   llvm::sys::RunInterruptHandlers();
69 
70   // We cannot recover from llvm errors.  When reporting a fatal error, exit
71   // with status 70 to generate crash diagnostics.  For BSD systems this is
72   // defined as an internal software error.  Otherwise, exit with status 1.
73   llvm::sys::Process::Exit(GenCrashDiag ? 70 : 1);
74 }
75 
76 #ifdef CLANG_HAVE_RLIMITS
77 #if defined(__linux__) && defined(__PIE__)
78 static size_t getCurrentStackAllocation() {
79   // If we can't compute the current stack usage, allow for 512K of command
80   // line arguments and environment.
81   size_t Usage = 512 * 1024;
82   if (FILE *StatFile = fopen("/proc/self/stat", "r")) {
83     // We assume that the stack extends from its current address to the end of
84     // the environment space. In reality, there is another string literal (the
85     // program name) after the environment, but this is close enough (we only
86     // need to be within 100K or so).
87     unsigned long StackPtr, EnvEnd;
88     // Disable silly GCC -Wformat warning that complains about length
89     // modifiers on ignored format specifiers. We want to retain these
90     // for documentation purposes even though they have no effect.
91 #if defined(__GNUC__) && !defined(__clang__)
92 #pragma GCC diagnostic push
93 #pragma GCC diagnostic ignored "-Wformat"
94 #endif
95     if (fscanf(StatFile,
96                "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu "
97                "%*lu %*ld %*ld %*ld %*ld %*ld %*ld %*llu %*lu %*ld %*lu %*lu "
98                "%*lu %*lu %lu %*lu %*lu %*lu %*lu %*lu %*llu %*lu %*lu %*d %*d "
99                "%*u %*u %*llu %*lu %*ld %*lu %*lu %*lu %*lu %*lu %*lu %lu %*d",
100                &StackPtr, &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 =
126         static_cast<volatile char *>(alloca(kTargetStack - Curr));
127     Alloc[0] = 0;
128     Alloc[kTargetStack - Curr - 1] = 0;
129   }
130 }
131 #else
132 static void ensureStackAddressSpace() {}
133 #endif
134 
135 /// Attempt to ensure that we have at least 8MiB of usable stack space.
136 static void ensureSufficientStack() {
137   struct rlimit rlim;
138   if (getrlimit(RLIMIT_STACK, &rlim) != 0)
139     return;
140 
141   // Increase the soft stack limit to our desired level, if necessary and
142   // possible.
143   if (rlim.rlim_cur != RLIM_INFINITY &&
144       rlim.rlim_cur < rlim_t(DesiredStackSize)) {
145     // Try to allocate sufficient stack.
146     if (rlim.rlim_max == RLIM_INFINITY ||
147         rlim.rlim_max >= rlim_t(DesiredStackSize))
148       rlim.rlim_cur = DesiredStackSize;
149     else if (rlim.rlim_cur == rlim.rlim_max)
150       return;
151     else
152       rlim.rlim_cur = rlim.rlim_max;
153 
154     if (setrlimit(RLIMIT_STACK, &rlim) != 0 ||
155         rlim.rlim_cur != DesiredStackSize)
156       return;
157   }
158 
159   // We should now have a stack of size at least DesiredStackSize. Ensure
160   // that we can actually use that much, if necessary.
161   ensureStackAddressSpace();
162 }
163 #else
164 static void ensureSufficientStack() {}
165 #endif
166 
167 /// Print supported cpus of the given target.
168 static int PrintSupportedCPUs(std::string TargetStr) {
169   std::string Error;
170   const llvm::Target *TheTarget =
171       llvm::TargetRegistry::lookupTarget(TargetStr, Error);
172   if (!TheTarget) {
173     llvm::errs() << Error;
174     return 1;
175   }
176 
177   // the target machine will handle the mcpu printing
178   llvm::TargetOptions Options;
179   std::unique_ptr<llvm::TargetMachine> TheTargetMachine(
180       TheTarget->createTargetMachine(TargetStr, "", "+cpuhelp", Options,
181                                      std::nullopt));
182   return 0;
183 }
184 
185 int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
186   ensureSufficientStack();
187 
188   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
189   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
190 
191   // Register the support for object-file-wrapped Clang modules.
192   auto PCHOps = Clang->getPCHContainerOperations();
193   PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
194   PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
195 
196   // Initialize targets first, so that --version shows registered targets.
197   llvm::InitializeAllTargets();
198   llvm::InitializeAllTargetMCs();
199   llvm::InitializeAllAsmPrinters();
200   llvm::InitializeAllAsmParsers();
201 
202   // Buffer diagnostics from argument parsing so that we can output them using a
203   // well formed diagnostic object.
204   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
205   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
206   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
207 
208   // Setup round-trip remarks for the DiagnosticsEngine used in CreateFromArgs.
209   if (find(Argv, StringRef("-Rround-trip-cc1-args")) != Argv.end())
210     Diags.setSeverity(diag::remark_cc1_round_trip_generated,
211                       diag::Severity::Remark, {});
212 
213   bool Success = CompilerInvocation::CreateFromArgs(Clang->getInvocation(),
214                                                     Argv, Diags, Argv0);
215 
216   if (!Clang->getFrontendOpts().TimeTracePath.empty()) {
217     llvm::timeTraceProfilerInitialize(
218         Clang->getFrontendOpts().TimeTraceGranularity, Argv0);
219   }
220   // --print-supported-cpus takes priority over the actual compilation.
221   if (Clang->getFrontendOpts().PrintSupportedCPUs)
222     return PrintSupportedCPUs(Clang->getTargetOpts().Triple);
223 
224   // Infer the builtin include path if unspecified.
225   if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
226       Clang->getHeaderSearchOpts().ResourceDir.empty())
227     Clang->getHeaderSearchOpts().ResourceDir =
228       CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
229 
230   // Create the actual diagnostics engine.
231   Clang->createDiagnostics();
232   if (!Clang->hasDiagnostics())
233     return 1;
234 
235   // Set an error handler, so that any LLVM backend diagnostics go through our
236   // error handler.
237   llvm::install_fatal_error_handler(LLVMErrorHandler,
238                                   static_cast<void*>(&Clang->getDiagnostics()));
239 
240   DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
241   if (!Success) {
242     Clang->getDiagnosticClient().finish();
243     return 1;
244   }
245 
246   // Execute the frontend actions.
247   {
248     llvm::TimeTraceScope TimeScope("ExecuteCompiler");
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   llvm::TimerGroup::clearAll();
256 
257   if (llvm::timeTraceProfilerEnabled()) {
258     // It is possible that the compiler instance doesn't own a file manager here
259     // if we're compiling a module unit. Since the file manager are owned by AST
260     // when we're compiling a module unit. So the file manager may be invalid
261     // here.
262     //
263     // It should be fine to create file manager here since the file system
264     // options are stored in the compiler invocation and we can recreate the VFS
265     // from the compiler invocation.
266     if (!Clang->hasFileManager())
267       Clang->createFileManager(createVFSFromCompilerInvocation(
268           Clang->getInvocation(), Clang->getDiagnostics()));
269 
270     if (auto profilerOutput = Clang->createOutputFile(
271             Clang->getFrontendOpts().TimeTracePath, /*Binary=*/false,
272             /*RemoveFileOnSignal=*/false,
273             /*useTemporary=*/false)) {
274       llvm::timeTraceProfilerWrite(*profilerOutput);
275       profilerOutput.reset();
276       llvm::timeTraceProfilerCleanup();
277       Clang->clearOutputFiles(false);
278     }
279   }
280 
281   // Our error handler depends on the Diagnostics object, which we're
282   // potentially about to delete. Uninstall the handler now so that any
283   // later errors use the default handling behavior instead.
284   llvm::remove_fatal_error_handler();
285 
286   // When running with -disable-free, don't do any destruction or shutdown.
287   if (Clang->getFrontendOpts().DisableFree) {
288     llvm::BuryPointer(std::move(Clang));
289     return !Success;
290   }
291 
292   return !Success;
293 }
294