blob: ae60fefdcf59b5cf83f2517102e313eff7dcf9e8 [file] [log] [blame]
Daniel Dunbar2fcaa542010-05-20 17:49:16 +00001//===-- cc1_main.cpp - Clang CC1 Compiler Frontend ------------------------===//
Daniel Dunbar51cd8f02009-11-19 07:37:51 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Daniel Dunbar51cd8f02009-11-19 07:37:51 +00006//
7//===----------------------------------------------------------------------===//
8//
Daniel Dunbarf72bdf72009-12-11 22:20:12 +00009// 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.
Daniel Dunbar51cd8f02009-11-19 07:37:51 +000012//
13//===----------------------------------------------------------------------===//
14
David Blaikie9941da42018-11-17 18:04:13 +000015#include "clang/Basic/Stack.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000016#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
Chris Bienemana6b39ab2016-08-23 20:07:07 +000017#include "clang/Config/config.h"
Daniel Dunbarf72bdf72009-12-11 22:20:12 +000018#include "clang/Driver/DriverDiagnostic.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000019#include "clang/Driver/Options.h"
Daniel Dunbarf72bdf72009-12-11 22:20:12 +000020#include "clang/Frontend/CompilerInstance.h"
21#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbarf72bdf72009-12-11 22:20:12 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbarf72bdf72009-12-11 22:20:12 +000023#include "clang/Frontend/TextDiagnosticBuffer.h"
24#include "clang/Frontend/TextDiagnosticPrinter.h"
Kostya Serebryanyce2c7262013-12-27 08:11:08 +000025#include "clang/Frontend/Utils.h"
Peter Collingbourne85dd0bd2010-08-24 00:31:22 +000026#include "clang/FrontendTool/Utils.h"
Douglas Gregor171b7802010-03-30 17:33:59 +000027#include "llvm/ADT/Statistic.h"
Nico Weberd637c052018-04-30 13:52:15 +000028#include "llvm/Config/llvm-config.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000029#include "llvm/LinkAllPasses.h"
David Blaikie9941da42018-11-17 18:04:13 +000030#include "llvm/Option/Arg.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000031#include "llvm/Option/ArgList.h"
32#include "llvm/Option/OptTable.h"
David Blaikie9941da42018-11-17 18:04:13 +000033#include "llvm/Support/BuryPointer.h"
Richard Smith194b6a32016-08-17 01:05:07 +000034#include "llvm/Support/Compiler.h"
Daniel Dunbarf72bdf72009-12-11 22:20:12 +000035#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/ManagedStatic.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000037#include "llvm/Support/Path.h"
Chad Rosier7ea73972012-11-12 19:39:37 +000038#include "llvm/Support/Signals.h"
Evan Cheng494eb062011-08-24 18:09:14 +000039#include "llvm/Support/TargetSelect.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000040#include "llvm/Support/TimeProfiler.h"
Chris Lattner09f8cc82010-03-30 05:39:52 +000041#include "llvm/Support/Timer.h"
Daniel Dunbar51cd8f02009-11-19 07:37:51 +000042#include "llvm/Support/raw_ostream.h"
Daniel Dunbarf72bdf72009-12-11 22:20:12 +000043#include <cstdio>
Richard Smithc33b8372016-08-18 18:22:22 +000044
Chris Bienemana6b39ab2016-08-23 20:07:07 +000045#ifdef CLANG_HAVE_RLIMITS
Richard Smith194b6a32016-08-17 01:05:07 +000046#include <sys/resource.h>
47#endif
Richard Smithc33b8372016-08-18 18:22:22 +000048
Daniel Dunbarf72bdf72009-12-11 22:20:12 +000049using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000050using namespace llvm::opt;
Daniel Dunbar51cd8f02009-11-19 07:37:51 +000051
Daniel Dunbarf72bdf72009-12-11 22:20:12 +000052//===----------------------------------------------------------------------===//
53// Main driver
54//===----------------------------------------------------------------------===//
55
Chad Rosier05c71aa2013-03-27 18:28:23 +000056static void LLVMErrorHandler(void *UserData, const std::string &Message,
57 bool GenCrashDiag) {
David Blaikie9c902b52011-09-25 23:23:43 +000058 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
Daniel Dunbarf72bdf72009-12-11 22:20:12 +000059
60 Diags.Report(diag::err_fe_error_backend) << Message;
61
Chad Rosier7ea73972012-11-12 19:39:37 +000062 // Run the interrupt handlers to make sure any special cleanups get done, in
63 // particular that we remove files registered with RemoveFileOnSignal.
64 llvm::sys::RunInterruptHandlers();
65
Chad Rosierad6e96d2012-11-12 21:32:24 +000066 // We cannot recover from llvm errors. When reporting a fatal error, exit
Chad Rosier05c71aa2013-03-27 18:28:23 +000067 // with status 70 to generate crash diagnostics. For BSD systems this is
68 // defined as an internal software error. Otherwise, exit with status 1.
69 exit(GenCrashDiag ? 70 : 1);
Daniel Dunbarf72bdf72009-12-11 22:20:12 +000070}
71
Sebastian Pop17fac042014-03-14 04:04:27 +000072#ifdef LINK_POLLY_INTO_TOOLS
73namespace polly {
74void initializePollyPasses(llvm::PassRegistry &Registry);
75}
76#endif
77
Chris Bienemana6b39ab2016-08-23 20:07:07 +000078#ifdef CLANG_HAVE_RLIMITS
Richard Smith194b6a32016-08-17 01:05:07 +000079#if defined(__linux__) && defined(__PIE__)
Richard Smithf80a27e2016-10-14 19:51:36 +000080static size_t getCurrentStackAllocation() {
81 // If we can't compute the current stack usage, allow for 512K of command
82 // line arguments and environment.
83 size_t Usage = 512 * 1024;
84 if (FILE *StatFile = fopen("/proc/self/stat", "r")) {
85 // We assume that the stack extends from its current address to the end of
86 // the environment space. In reality, there is another string literal (the
87 // program name) after the environment, but this is close enough (we only
88 // need to be within 100K or so).
89 unsigned long StackPtr, EnvEnd;
Richard Smith49db68d2016-10-15 01:59:52 +000090 // Disable silly GCC -Wformat warning that complains about length
91 // modifiers on ignored format specifiers. We want to retain these
92 // for documentation purposes even though they have no effect.
93#if defined(__GNUC__) && !defined(__clang__)
94#pragma GCC diagnostic push
95#pragma GCC diagnostic ignored "-Wformat"
96#endif
Richard Smithf80a27e2016-10-14 19:51:36 +000097 if (fscanf(StatFile,
98 "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu "
99 "%*lu %*ld %*ld %*ld %*ld %*ld %*ld %*llu %*lu %*ld %*lu %*lu "
100 "%*lu %*lu %lu %*lu %*lu %*lu %*lu %*lu %*llu %*lu %*lu %*d %*d "
101 "%*u %*u %*llu %*lu %*ld %*lu %*lu %*lu %*lu %*lu %*lu %lu %*d",
102 &StackPtr, &EnvEnd) == 2) {
Richard Smith49db68d2016-10-15 01:59:52 +0000103#if defined(__GNUC__) && !defined(__clang__)
104#pragma GCC diagnostic pop
105#endif
Richard Smithf80a27e2016-10-14 19:51:36 +0000106 Usage = StackPtr < EnvEnd ? EnvEnd - StackPtr : StackPtr - EnvEnd;
107 }
108 fclose(StatFile);
109 }
110 return Usage;
111}
112
113#include <alloca.h>
114
Richard Smith194b6a32016-08-17 01:05:07 +0000115LLVM_ATTRIBUTE_NOINLINE
Richard Smith0a7b2972018-07-03 21:34:13 +0000116static void ensureStackAddressSpace() {
Richard Smith194b6a32016-08-17 01:05:07 +0000117 // Linux kernels prior to 4.1 will sometimes locate the heap of a PIE binary
118 // relatively close to the stack (they are only guaranteed to be 128MiB
119 // apart). This results in crashes if we happen to heap-allocate more than
120 // 128MiB before we reach our stack high-water mark.
121 //
122 // To avoid these crashes, ensure that we have sufficient virtual memory
Richard Smithf80a27e2016-10-14 19:51:36 +0000123 // pages allocated before we start running.
124 size_t Curr = getCurrentStackAllocation();
Richard Smith0a7b2972018-07-03 21:34:13 +0000125 const int kTargetStack = DesiredStackSize - 256 * 1024;
Richard Smithf80a27e2016-10-14 19:51:36 +0000126 if (Curr < kTargetStack) {
127 volatile char *volatile Alloc =
128 static_cast<volatile char *>(alloca(kTargetStack - Curr));
129 Alloc[0] = 0;
130 Alloc[kTargetStack - Curr - 1] = 0;
131 }
Richard Smith194b6a32016-08-17 01:05:07 +0000132}
133#else
134static void ensureStackAddressSpace() {}
135#endif
136
137/// Attempt to ensure that we have at least 8MiB of usable stack space.
138static void ensureSufficientStack() {
139 struct rlimit rlim;
140 if (getrlimit(RLIMIT_STACK, &rlim) != 0)
141 return;
142
143 // Increase the soft stack limit to our desired level, if necessary and
144 // possible.
Fangrui Song4eab1ba2018-07-25 06:57:31 +0000145 if (rlim.rlim_cur != RLIM_INFINITY &&
146 rlim.rlim_cur < rlim_t(DesiredStackSize)) {
Richard Smith194b6a32016-08-17 01:05:07 +0000147 // Try to allocate sufficient stack.
Fangrui Song4eab1ba2018-07-25 06:57:31 +0000148 if (rlim.rlim_max == RLIM_INFINITY ||
149 rlim.rlim_max >= rlim_t(DesiredStackSize))
Richard Smith0a7b2972018-07-03 21:34:13 +0000150 rlim.rlim_cur = DesiredStackSize;
Richard Smith194b6a32016-08-17 01:05:07 +0000151 else if (rlim.rlim_cur == rlim.rlim_max)
152 return;
153 else
154 rlim.rlim_cur = rlim.rlim_max;
155
156 if (setrlimit(RLIMIT_STACK, &rlim) != 0 ||
Richard Smith0a7b2972018-07-03 21:34:13 +0000157 rlim.rlim_cur != DesiredStackSize)
Richard Smith194b6a32016-08-17 01:05:07 +0000158 return;
159 }
160
Richard Smith0a7b2972018-07-03 21:34:13 +0000161 // We should now have a stack of size at least DesiredStackSize. Ensure
Richard Smith194b6a32016-08-17 01:05:07 +0000162 // that we can actually use that much, if necessary.
163 ensureStackAddressSpace();
164}
165#else
Richard Smith525ce252016-08-17 02:22:39 +0000166static void ensureSufficientStack() {}
Richard Smith194b6a32016-08-17 01:05:07 +0000167#endif
168
Sean Silva070cd2d2014-08-15 21:38:36 +0000169int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
Richard Smith194b6a32016-08-17 01:05:07 +0000170 ensureSufficientStack();
171
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000172 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000173 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Daniel Dunbare922d9b2010-02-16 01:54:47 +0000174
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000175 // Register the support for object-file-wrapped Clang modules.
176 auto PCHOps = Clang->getPCHContainerOperations();
177 PCHOps->registerWriter(llvm::make_unique<ObjectFilePCHContainerWriter>());
178 PCHOps->registerReader(llvm::make_unique<ObjectFilePCHContainerReader>());
179
Daniel Dunbarf72bdf72009-12-11 22:20:12 +0000180 // Initialize targets first, so that --version shows registered targets.
181 llvm::InitializeAllTargets();
Evan Chengc391a582011-07-22 21:59:11 +0000182 llvm::InitializeAllTargetMCs();
Daniel Dunbarf72bdf72009-12-11 22:20:12 +0000183 llvm::InitializeAllAsmPrinters();
Chris Lattner61955ab2010-04-05 23:33:20 +0000184 llvm::InitializeAllAsmParsers();
Daniel Dunbarf72bdf72009-12-11 22:20:12 +0000185
Sebastian Pop17fac042014-03-14 04:04:27 +0000186#ifdef LINK_POLLY_INTO_TOOLS
187 llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
188 polly::initializePollyPasses(Registry);
189#endif
190
Daniel Dunbarf72bdf72009-12-11 22:20:12 +0000191 // Buffer diagnostics from argument parsing so that we can output them using a
192 // well formed diagnostic object.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000193 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000194 TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
Douglas Gregor811db4e2012-10-23 22:26:28 +0000195 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
Sean Silva070cd2d2014-08-15 21:38:36 +0000196 bool Success = CompilerInvocation::CreateFromArgs(
197 Clang->getInvocation(), Argv.begin(), Argv.end(), Diags);
Daniel Dunbard6136772009-12-13 03:45:58 +0000198
Anton Afanasyevd880de22019-03-30 08:42:48 +0000199 if (Clang->getFrontendOpts().TimeTrace)
200 llvm::timeTraceProfilerInitialize();
201
Daniel Dunbard6136772009-12-13 03:45:58 +0000202 // Infer the builtin include path if unspecified.
Daniel Dunbar30b24e92010-03-23 05:09:16 +0000203 if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
204 Clang->getHeaderSearchOpts().ResourceDir.empty())
205 Clang->getHeaderSearchOpts().ResourceDir =
Daniel Dunbara5a166d2009-12-15 00:06:45 +0000206 CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
Daniel Dunbarf72bdf72009-12-11 22:20:12 +0000207
Daniel Dunbar1cdf04c2010-08-12 02:53:07 +0000208 // Create the actual diagnostics engine.
Sean Silvaf1b49e22013-01-20 01:58:28 +0000209 Clang->createDiagnostics();
Daniel Dunbar1cdf04c2010-08-12 02:53:07 +0000210 if (!Clang->hasDiagnostics())
211 return 1;
212
213 // Set an error handler, so that any LLVM backend diagnostics go through our
214 // error handler.
215 llvm::install_fatal_error_handler(LLVMErrorHandler,
216 static_cast<void*>(&Clang->getDiagnostics()));
217
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000218 DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
Argyrios Kyrtzidisbe6d89d2012-01-25 20:00:43 +0000219 if (!Success)
220 return 1;
Daniel Dunbar1cdf04c2010-08-12 02:53:07 +0000221
Daniel Dunbare9e91b02010-08-12 02:53:12 +0000222 // Execute the frontend actions.
Anton Afanasyevd880de22019-03-30 08:42:48 +0000223 {
224 llvm::TimeTraceScope TimeScope("ExecuteCompiler", StringRef(""));
225 Success = ExecuteCompilerInvocation(Clang.get());
226 }
Daniel Dunbar30b24e92010-03-23 05:09:16 +0000227
Chris Lattner09f8cc82010-03-30 05:39:52 +0000228 // If any timers were active but haven't been destroyed yet, print their
229 // results now. This happens in -disable-free mode.
230 llvm::TimerGroup::printAll(llvm::errs());
Daniel Dunbar2be96742010-08-02 15:31:28 +0000231
Anton Afanasyevd880de22019-03-30 08:42:48 +0000232 if (llvm::timeTraceProfilerEnabled()) {
233 SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
234 llvm::sys::path::replace_extension(Path, "json");
235 auto profilerOutput =
236 Clang->createOutputFile(Path.str(),
237 /*Binary=*/false,
238 /*RemoveFileOnSignal=*/false, "",
239 /*Extension=*/"json",
240 /*useTemporary=*/false);
241
Anton Afanasyev26536722019-04-15 21:02:47 +0000242 llvm::timeTraceProfilerWrite(*profilerOutput);
Anton Afanasyevd880de22019-03-30 08:42:48 +0000243 llvm::timeTraceProfilerCleanup();
244 }
245
Dan Gohmanb37af7d2010-08-18 21:23:17 +0000246 // 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
Daniel Dunbar30b24e92010-03-23 05:09:16 +0000251 // When running with -disable-free, don't do any destruction or shutdown.
252 if (Clang->getFrontendOpts().DisableFree) {
David Blaikie9941da42018-11-17 18:04:13 +0000253 llvm::BuryPointer(std::move(Clang));
Daniel Dunbar30b24e92010-03-23 05:09:16 +0000254 return !Success;
Daniel Dunbarf72bdf72009-12-11 22:20:12 +0000255 }
256
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000257 return !Success;
Daniel Dunbarf72bdf72009-12-11 22:20:12 +0000258}