Loading...
Searching...
No Matches
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/DiagnosticSema.h>
16#undef CALLBACK
17#include "clang/Basic/FileManager.h"
18#include "clang/Basic/Stack.h"
19#include "clang/Basic/TargetOptions.h"
20#if __has_include("clang/CodeGen/ObjectFilePCHContainerOperations.h")
21#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
22#endif
23#include "clang/Config/config.h"
24#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/CompilerInvocation.h"
26#include "clang/Frontend/FrontendDiagnostic.h"
27#include "clang/Frontend/TextDiagnosticBuffer.h"
28#include "clang/Frontend/TextDiagnosticPrinter.h"
29#include "clang/FrontendTool/Utils.h"
30#include "llvm/Config/llvm-config.h"
31#include "llvm/LinkAllPasses.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/FileSystem.h"
39#include "llvm/Support/ManagedStatic.h"
40#include "llvm/Support/Process.h"
41#include "llvm/Support/Signals.h"
42//#include "llvm/Support/TargetRegistry.h"
43#include "llvm/Support/TargetSelect.h"
44#include "llvm/Support/TimeProfiler.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
47#include "llvm/Target/TargetMachine.h"
48
49#include <iostream>
50#include <sstream>
51
52#ifdef CLANG_HAVE_RLIMITS
53#include <sys/resource.h>
54#endif
55
56using namespace clang;
57using namespace llvm::opt;
58
59class QtDiagnosticConsumer final : public DiagnosticConsumer
60{
61
62 // DiagnosticConsumer interface
63public:
64 void finish() override { std::cerr << " == finish == \n"; }
65 void
66 HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic& Info) override
67 {
68 SmallVector<char, 1024> vec;
69 Info.FormatDiagnostic(vec);
70 std::cerr << " == diagnostic == " << vec.data() << "\n";
71 }
72};
73
74//===----------------------------------------------------------------------===//
75// Main driver
76//===----------------------------------------------------------------------===//
77#if LLVM_VERSION_MAJOR < 14
78static void
79LLVMErrorHandler(void* UserData, const std::string& Message, bool GenCrashDiag)
80#else
81static void LLVMErrorHandler(void* UserData, const char* Message, bool GenCrashDiag)
82#endif
83{
84 DiagnosticsEngine& Diags = *static_cast<DiagnosticsEngine*>(UserData);
85
86 Diags.Report(diag::err_fe_error_backend) << Message;
87
88 // Run the interrupt handlers to make sure any special cleanups get done, in
89 // particular that we remove files registered with RemoveFileOnSignal.
90 llvm::sys::RunInterruptHandlers();
91
92 // We cannot recover from llvm errors. When reporting a fatal error, exit
93 // with status 70 to generate crash diagnostics. For BSD systems this is
94 // defined as an internal software error. Otherwise, exit with status 1.
95 llvm::sys::Process::Exit(GenCrashDiag ? 70 : 1);
96}
97
98#ifdef CLANG_HAVE_RLIMITS
99#if defined(__linux__) && defined(__PIE__)
100static size_t getCurrentStackAllocation()
101{
102 // If we can't compute the current stack usage, allow for 512K of command
103 // line arguments and environment.
104 size_t Usage = 512 * 1024;
105 if(FILE* StatFile = fopen("/proc/self/stat", "r"))
106 {
107 // We assume that the stack extends from its current address to the end of
108 // the environment space. In reality, there is another string literal (the
109 // program name) after the environment, but this is close enough (we only
110 // need to be within 100K or so).
111 unsigned long StackPtr, EnvEnd;
112 // Disable silly GCC -Wformat warning that complains about length
113 // modifiers on ignored format specifiers. We want to retain these
114 // for documentation purposes even though they have no effect.
115#if defined(__GNUC__) && !defined(__clang__)
116#pragma GCC diagnostic push
117#pragma GCC diagnostic ignored "-Wformat"
118#endif
119 if(fscanf(
120 StatFile,
121 "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu "
122 "%*lu %*ld %*ld %*ld %*ld %*ld %*ld %*llu %*lu %*ld %*lu %*lu "
123 "%*lu %*lu %lu %*lu %*lu %*lu %*lu %*lu %*llu %*lu %*lu %*d %*d "
124 "%*u %*u %*llu %*lu %*ld %*lu %*lu %*lu %*lu %*lu %*lu %lu %*d",
125 &StackPtr, &EnvEnd)
126 == 2)
127 {
128#if defined(__GNUC__) && !defined(__clang__)
129#pragma GCC diagnostic pop
130#endif
131 Usage = StackPtr < EnvEnd ? EnvEnd - StackPtr : StackPtr - EnvEnd;
132 }
133 fclose(StatFile);
134 }
135 return Usage;
136}
137
138#include <alloca.h>
139
140LLVM_ATTRIBUTE_NOINLINE
141static void ensureStackAddressSpace()
142{
143 // Linux kernels prior to 4.1 will sometimes locate the heap of a PIE binary
144 // relatively close to the stack (they are only guaranteed to be 128MiB
145 // apart). This results in crashes if we happen to heap-allocate more than
146 // 128MiB before we reach our stack high-water mark.
147 //
148 // To avoid these crashes, ensure that we have sufficient virtual memory
149 // pages allocated before we start running.
150 size_t Curr = getCurrentStackAllocation();
151 const int kTargetStack = DesiredStackSize - 256 * 1024;
152 if(Curr < kTargetStack)
153 {
154 volatile char* volatile Alloc
155 = static_cast<volatile char*>(alloca(kTargetStack - Curr));
156 Alloc[0] = 0;
157 Alloc[kTargetStack - Curr - 1] = 0;
158 }
159}
160#else
161static void ensureStackAddressSpace() { }
162#endif
163
165static void ensureSufficientStack()
166{
167 struct rlimit rlim;
168 if(getrlimit(RLIMIT_STACK, &rlim) != 0)
169 return;
170
171 // Increase the soft stack limit to our desired level, if necessary and
172 // possible.
173 if(rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur < rlim_t(DesiredStackSize))
174 {
175 // Try to allocate sufficient stack.
176 if(rlim.rlim_max == RLIM_INFINITY || rlim.rlim_max >= rlim_t(DesiredStackSize))
177 rlim.rlim_cur = DesiredStackSize;
178 else if(rlim.rlim_cur == rlim.rlim_max)
179 return;
180 else
181 rlim.rlim_cur = rlim.rlim_max;
182
183 if(setrlimit(RLIMIT_STACK, &rlim) != 0 || rlim.rlim_cur != DesiredStackSize)
184 return;
185 }
186
187 // We should now have a stack of size at least DesiredStackSize. Ensure
188 // that we can actually use that much, if necessary.
189 ensureStackAddressSpace();
190}
191#else
192static void ensureSufficientStack() { }
193#endif
194
195auto printErrors(TextDiagnosticBuffer& buf, const SourceManager& mgr)
196{
197 std::stringstream ss;
198 for(auto it = buf.err_begin(); it != buf.err_end(); ++it)
199 {
200 auto& loc = it->first;
201 ss << loc.printToString(mgr) << ":\n" << it->second << "\n\n";
202 }
203
204 std::cerr << ss.str();
205 return ss.str();
206}
207llvm::Error cc1_main(ArrayRef<const char*> Argv, const char* Argv0, void* MainAddr)
208{
209 ensureSufficientStack();
210
211 // Initialize targets first, so that --version shows registered targets.
212 llvm::InitializeAllTargets();
213 llvm::InitializeAllTargetMCs();
214 llvm::InitializeAllAsmPrinters();
215 llvm::InitializeAllAsmParsers();
216
217 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
218#ifdef LINK_POLLY_INTO_TOOLS
219 llvm::PassRegistry& Registry = *llvm::PassRegistry::getPassRegistry();
220 polly::initializePollyPasses(Registry);
221#endif
222
223 // Buffer diagnostics from argument parsing so that we can output them using a
224 // well formed diagnostic object.
225 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
226 TextDiagnosticBuffer* DiagsBuffer = new TextDiagnosticBuffer;
227 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
228 new DiagnosticsEngine(DiagID, &*DiagOpts, DiagsBuffer));
229
230#if LLVM_VERSION_MAJOR >= 13
231 llvm::IntrusiveRefCntPtr<FileManager> Files(
232 new FileManager(FileSystemOptions(), llvm::vfs::getRealFileSystem()));
233 llvm::IntrusiveRefCntPtr<SourceManager> SrcMgr(new SourceManager(*Diags, *Files));
234#endif
235
236 // Create a Clang instance
237 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
238
239#if __has_include("clang/CodeGen/ObjectFilePCHContainerOperations.h")
240 // Register the support for object-file-wrapped Clang modules.
241 auto PCHOps = Clang->getPCHContainerOperations();
242 PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
243 PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
244#endif
245
246 bool Success
247 = CompilerInvocation::CreateFromArgs(Clang->getInvocation(), Argv, *Diags);
248
249#if LLVM_VERSION_MAJOR >= 13
250 if(!Clang->hasSourceManager())
251 {
252 Diags->setSourceManager(SrcMgr.get());
253
254 Clang->setFileManager(Files.get());
255 Clang->setSourceManager(SrcMgr.get());
256 }
257#endif
258 // Infer the builtin include path if unspecified.
259 if(Clang->getHeaderSearchOpts().UseBuiltinIncludes
260 && Clang->getHeaderSearchOpts().ResourceDir.empty())
261 Clang->getHeaderSearchOpts().ResourceDir
262 = CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
263
264 Clang->setDiagnostics(Diags.get());
265 if(!Clang->hasDiagnostics())
266 {
267 return llvm::make_error<llvm::StringError>(
268 "No diagnostics", std::error_code(1, std::system_category()));
269 }
270
271 // Set an error handler, so that any LLVM backend diagnostics go through our
272 // error handler.
273 llvm::install_fatal_error_handler(
274 LLVMErrorHandler, static_cast<void*>(&Clang->getDiagnostics()));
275
276 //if(Clang && DiagsBuffer)
277 // DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
278 Clang->getDiagnostics().setSeverity(clang::diag::ext_constexpr_function_never_constant_expr, diag::Severity::Ignored, {});
279 if(!Success)
280 {
281 return llvm::make_error<llvm::StringError>(
282 printErrors(*DiagsBuffer, Clang->getSourceManager()),
283 std::error_code(1, std::system_category()));
284 }
285
286 // Execute the frontend actions.
287 {
288 llvm::TimeTraceScope TimeScope("ExecuteCompiler");
289 Success = ExecuteCompilerInvocation(Clang.get());
290 }
291
292 // If any timers were active but haven't been destroyed yet, print their
293 // results now. This happens in -disable-free mode.
294 llvm::TimerGroup::printAll(llvm::errs());
295 llvm::TimerGroup::clearAll();
296
297 auto res = Success ? llvm::Error::success()
298 : llvm::make_error<llvm::StringError>(
299 printErrors(*DiagsBuffer, Clang->getSourceManager()),
300 std::error_code(1, std::system_category()));
301
302 // Our error handler depends on the Diagnostics object, which we're
303 // potentially about to delete. Uninstall the handler now so that any
304 // later errors use the default handling behavior instead.
305 llvm::remove_fatal_error_handler();
306
307 // When running with -disable-free, don't do any destruction or shutdown.
308 if(Clang->getFrontendOpts().DisableFree)
309 {
310 llvm::BuryPointer(std::move(Clang));
311 return res;
312 }
313 return res;
314}
Definition cc1_main.cpp:60
STL namespace.