blob: 58eef022c7b4d0f60bb483f2557a4b8f6872416d [file] [log] [blame]
Daniel Dunbar217acbf2009-11-19 07:37:51 +00001//===-- cc1_main.cpp - Clang CC1 Driver -----------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Daniel Dunbar21085772009-12-11 22:20:12 +000010// This is the entry point to the clang -cc1 functionality, which implements the
11// core compiler functionality along with a number of additional tools for
12// demonstration and testing purposes.
Daniel Dunbar217acbf2009-11-19 07:37:51 +000013//
14//===----------------------------------------------------------------------===//
15
Daniel Dunbar21085772009-12-11 22:20:12 +000016#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/TargetInfo.h"
20#include "clang/Basic/Version.h"
21#include "clang/Driver/Arg.h"
22#include "clang/Driver/ArgList.h"
23#include "clang/Driver/CC1Options.h"
24#include "clang/Driver/DriverDiagnostic.h"
25#include "clang/Driver/OptTable.h"
26#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/CompilerInvocation.h"
28#include "clang/Frontend/FrontendActions.h"
29#include "clang/Frontend/FrontendDiagnostic.h"
30#include "clang/Frontend/FrontendPluginRegistry.h"
31#include "clang/Frontend/TextDiagnosticBuffer.h"
32#include "clang/Frontend/TextDiagnosticPrinter.h"
33#include "clang/Frontend/VerifyDiagnosticsClient.h"
34#include "llvm/LLVMContext.h"
35#include "llvm/ADT/OwningPtr.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/ManagedStatic.h"
38#include "llvm/Support/PrettyStackTrace.h"
Daniel Dunbar217acbf2009-11-19 07:37:51 +000039#include "llvm/Support/raw_ostream.h"
Daniel Dunbar21085772009-12-11 22:20:12 +000040#include "llvm/System/DynamicLibrary.h"
41#include "llvm/System/Host.h"
42#include "llvm/System/Path.h"
43#include "llvm/System/Signals.h"
44#include "llvm/Target/TargetSelect.h"
45#include <cstdio>
46using namespace clang;
Daniel Dunbar217acbf2009-11-19 07:37:51 +000047
Daniel Dunbar21085772009-12-11 22:20:12 +000048//===----------------------------------------------------------------------===//
49// Main driver
50//===----------------------------------------------------------------------===//
51
52void LLVMErrorHandler(void *UserData, const std::string &Message) {
53 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
54
55 Diags.Report(diag::err_fe_error_backend) << Message;
56
57 // We cannot recover from llvm errors.
58 exit(1);
59}
60
61static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
62 using namespace clang::frontend;
63
64 switch (CI.getFrontendOpts().ProgramAction) {
65 default:
66 llvm::llvm_unreachable("Invalid program action!");
67
68 case ASTDump: return new ASTDumpAction();
69 case ASTPrint: return new ASTPrintAction();
70 case ASTPrintXML: return new ASTPrintXMLAction();
71 case ASTView: return new ASTViewAction();
72 case DumpRawTokens: return new DumpRawTokensAction();
73 case DumpRecordLayouts: return new DumpRecordAction();
74 case DumpTokens: return new DumpTokensAction();
75 case EmitAssembly: return new EmitAssemblyAction();
76 case EmitBC: return new EmitBCAction();
77 case EmitHTML: return new HTMLPrintAction();
78 case EmitLLVM: return new EmitLLVMAction();
79 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
80 case FixIt: return new FixItAction();
81 case GeneratePCH: return new GeneratePCHAction();
82 case GeneratePTH: return new GeneratePTHAction();
83 case InheritanceView: return new InheritanceViewAction();
84 case ParseNoop: return new ParseOnlyAction();
85 case ParsePrintCallbacks: return new PrintParseAction();
86 case ParseSyntaxOnly: return new SyntaxOnlyAction();
87
88 case PluginAction: {
89 if (CI.getFrontendOpts().ActionName == "help") {
90 llvm::errs() << "clang -cc1 plugins:\n";
91 for (FrontendPluginRegistry::iterator it =
92 FrontendPluginRegistry::begin(),
93 ie = FrontendPluginRegistry::end();
94 it != ie; ++it)
95 llvm::errs() << " " << it->getName() << " - " << it->getDesc() << "\n";
96 return 0;
97 }
98
99 for (FrontendPluginRegistry::iterator it =
100 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
101 it != ie; ++it) {
102 if (it->getName() == CI.getFrontendOpts().ActionName)
103 return it->instantiate();
104 }
105
106 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
107 << CI.getFrontendOpts().ActionName;
108 return 0;
109 }
110
111 case PrintDeclContext: return new DeclContextPrintAction();
112 case PrintPreprocessedInput: return new PrintPreprocessedAction();
113 case RewriteBlocks: return new RewriteBlocksAction();
114 case RewriteMacros: return new RewriteMacrosAction();
115 case RewriteObjC: return new RewriteObjCAction();
116 case RewriteTest: return new RewriteTestAction();
117 case RunAnalysis: return new AnalysisAction();
118 case RunPreprocessorOnly: return new PreprocessOnlyAction();
119 }
120}
121
122// FIXME: Define the need for this testing away.
123static int cc1_test(Diagnostic &Diags,
124 const char **ArgBegin, const char **ArgEnd,
125 const char *Argv0, void *MainAddr) {
126 using namespace clang::driver;
127
Daniel Dunbar217acbf2009-11-19 07:37:51 +0000128 llvm::errs() << "cc1 argv:";
129 for (const char **i = ArgBegin; i != ArgEnd; ++i)
130 llvm::errs() << " \"" << *i << '"';
131 llvm::errs() << "\n";
132
Daniel Dunbar21085772009-12-11 22:20:12 +0000133 // Parse the arguments.
134 OptTable *Opts = createCC1OptTable();
135 unsigned MissingArgIndex, MissingArgCount;
136 InputArgList *Args = Opts->ParseArgs(ArgBegin, ArgEnd,
137 MissingArgIndex, MissingArgCount);
138
139 // Check for missing argument error.
140 if (MissingArgCount)
141 Diags.Report(clang::diag::err_drv_missing_argument)
142 << Args->getArgString(MissingArgIndex) << MissingArgCount;
143
144 // Dump the parsed arguments.
145 llvm::errs() << "cc1 parsed options:\n";
146 for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
147 it != ie; ++it)
148 (*it)->dump();
149
150 // Create a compiler invocation.
151 llvm::errs() << "cc1 creating invocation.\n";
152 CompilerInvocation Invocation;
153 CompilerInvocation::CreateFromArgs(Invocation, ArgBegin, ArgEnd,
154 Argv0, MainAddr, Diags);
155
156 // Convert the invocation back to argument strings.
157 std::vector<std::string> InvocationArgs;
158 Invocation.toArgs(InvocationArgs);
159
160 // Dump the converted arguments.
161 llvm::SmallVector<const char*, 32> Invocation2Args;
162 llvm::errs() << "invocation argv :";
163 for (unsigned i = 0, e = InvocationArgs.size(); i != e; ++i) {
164 Invocation2Args.push_back(InvocationArgs[i].c_str());
165 llvm::errs() << " \"" << InvocationArgs[i] << '"';
166 }
167 llvm::errs() << "\n";
168
169 // Convert those arguments to another invocation, and check that we got the
170 // same thing.
171 CompilerInvocation Invocation2;
172 CompilerInvocation::CreateFromArgs(Invocation2, Invocation2Args.begin(),
173 Invocation2Args.end(), Argv0, MainAddr,
174 Diags);
175
176 // FIXME: Implement CompilerInvocation comparison.
177 if (true) {
178 //llvm::errs() << "warning: Invocations differ!\n";
179
180 std::vector<std::string> Invocation2Args;
181 Invocation2.toArgs(Invocation2Args);
182 llvm::errs() << "invocation2 argv:";
183 for (unsigned i = 0, e = Invocation2Args.size(); i != e; ++i)
184 llvm::errs() << " \"" << Invocation2Args[i] << '"';
185 llvm::errs() << "\n";
186 }
187
Daniel Dunbar217acbf2009-11-19 07:37:51 +0000188 return 0;
189}
Daniel Dunbar21085772009-12-11 22:20:12 +0000190
191int cc1_main(const char **ArgBegin, const char **ArgEnd,
192 const char *Argv0, void *MainAddr) {
193 llvm::sys::PrintStackTraceOnErrorSignal();
194 llvm::PrettyStackTraceProgram X(ArgBegin - ArgEnd, ArgBegin);
195 CompilerInstance Clang(&llvm::getGlobalContext(), false);
196
197 // Run clang -cc1 test.
198 if (ArgBegin != ArgEnd && llvm::StringRef(ArgBegin[0]) == "-cc1test") {
199 TextDiagnosticPrinter DiagClient(llvm::errs(), DiagnosticOptions());
200 Diagnostic Diags(&DiagClient);
201 return cc1_test(Diags, ArgBegin + 1, ArgEnd, Argv0, MainAddr);
202 }
203
204 // Initialize targets first, so that --version shows registered targets.
205 llvm::InitializeAllTargets();
206 llvm::InitializeAllAsmPrinters();
207
208 // Buffer diagnostics from argument parsing so that we can output them using a
209 // well formed diagnostic object.
210 TextDiagnosticBuffer DiagsBuffer;
211 Diagnostic Diags(&DiagsBuffer);
212 CompilerInvocation::CreateFromArgs(Clang.getInvocation(), ArgBegin, ArgEnd,
213 Argv0, MainAddr, Diags);
214
215 // Honor -help.
216 if (Clang.getInvocation().getFrontendOpts().ShowHelp) {
217 llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1OptTable());
218 Opts->PrintHelp(llvm::outs(), "clang -cc1",
219 "LLVM 'Clang' Compiler: http://clang.llvm.org");
220 return 0;
221 }
222
223 // Honor -version.
224 //
225 // FIXME: Use a better -version message?
226 if (Clang.getInvocation().getFrontendOpts().ShowVersion) {
227 llvm::cl::PrintVersionMessage();
228 return 0;
229 }
230
231 // Create the actual diagnostics engine.
232 Clang.createDiagnostics(ArgEnd - ArgBegin, const_cast<char**>(ArgBegin));
233 if (!Clang.hasDiagnostics())
234 return 1;
235
236 // Set an error handler, so that any LLVM backend diagnostics go through our
237 // error handler.
238 llvm::llvm_install_error_handler(LLVMErrorHandler,
239 static_cast<void*>(&Clang.getDiagnostics()));
240
241 DiagsBuffer.FlushDiagnostics(Clang.getDiagnostics());
242
243 // Load any requested plugins.
244 for (unsigned i = 0,
245 e = Clang.getFrontendOpts().Plugins.size(); i != e; ++i) {
246 const std::string &Path = Clang.getFrontendOpts().Plugins[i];
247 std::string Error;
248 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
249 Diags.Report(diag::err_fe_unable_to_load_plugin) << Path << Error;
250 }
251
252 // If there were any errors in processing arguments, exit now.
253 if (Clang.getDiagnostics().getNumErrors())
254 return 1;
255
256 // Create the target instance.
257 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
258 Clang.getTargetOpts()));
259 if (!Clang.hasTarget())
260 return 1;
261
262 // Inform the target of the language options
263 //
264 // FIXME: We shouldn't need to do this, the target should be immutable once
265 // created. This complexity should be lifted elsewhere.
266 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
267
268 // Validate/process some options
269 if (Clang.getHeaderSearchOpts().Verbose)
270 llvm::errs() << "clang -cc1 version " CLANG_VERSION_STRING
271 << " based upon " << PACKAGE_STRING
272 << " hosted on " << llvm::sys::getHostTriple() << "\n";
273
274 if (Clang.getFrontendOpts().ShowTimers)
275 Clang.createFrontendTimer();
276
277 for (unsigned i = 0, e = Clang.getFrontendOpts().Inputs.size(); i != e; ++i) {
278 const std::string &InFile = Clang.getFrontendOpts().Inputs[i].second;
279
280 // If we aren't using an AST file, setup the file and source managers and
281 // the preprocessor.
282 bool IsAST =
283 Clang.getFrontendOpts().Inputs[i].first == FrontendOptions::IK_AST;
284 if (!IsAST) {
285 if (!i) {
286 // Create a file manager object to provide access to and cache the
287 // filesystem.
288 Clang.createFileManager();
289
290 // Create the source manager.
291 Clang.createSourceManager();
292 } else {
293 // Reset the ID tables if we are reusing the SourceManager.
294 Clang.getSourceManager().clearIDTables();
295 }
296
297 // Create the preprocessor.
298 Clang.createPreprocessor();
299 }
300
301 llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(Clang));
302 if (!Act)
303 break;
304
305 if (Act->BeginSourceFile(Clang, InFile, IsAST)) {
306 Act->Execute();
307 Act->EndSourceFile();
308 }
309 }
310
311 if (Clang.getDiagnosticOpts().ShowCarets)
312 if (unsigned NumDiagnostics = Clang.getDiagnostics().getNumDiagnostics())
313 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
314 (NumDiagnostics == 1 ? "" : "s"));
315
316 if (Clang.getFrontendOpts().ShowStats) {
317 Clang.getFileManager().PrintStats();
318 fprintf(stderr, "\n");
319 }
320
321 // Return the appropriate status when verifying diagnostics.
322 //
323 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
324 // this.
325 if (Clang.getDiagnosticOpts().VerifyDiagnostics)
326 return static_cast<VerifyDiagnosticsClient&>(
327 Clang.getDiagnosticClient()).HadErrors();
328
329 // Managed static deconstruction. Useful for making things like
330 // -time-passes usable.
331 llvm::llvm_shutdown();
332
333 return (Clang.getDiagnostics().getNumErrors() != 0);
334}