blob: 8c08d7cadc3aa561c5491482985f5142060f873c [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenek20e97482007-12-12 23:41:08 +000029#include "TranslationUnit.h"
Chris Lattner556beb72007-09-15 22:56:56 +000030#include "clang/Sema/ASTStreamer.h"
31#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "clang/Parse/Parser.h"
33#include "clang/Lex/HeaderSearch.h"
34#include "clang/Basic/FileManager.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/TargetInfo.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/MemoryBuffer.h"
39#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000040#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041#include <memory>
42using namespace clang;
43
44//===----------------------------------------------------------------------===//
45// Global options.
46//===----------------------------------------------------------------------===//
47
48static llvm::cl::opt<bool>
49Verbose("v", llvm::cl::desc("Enable verbose output"));
50static llvm::cl::opt<bool>
51Stats("stats", llvm::cl::desc("Print performance metrics and statistics"));
52
53enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000054 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000055 EmitLLVM, // Emit a .ll file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000056 SerializeAST, // Emit a .ast file.
Chris Lattner3b427b32007-10-11 00:18:28 +000057 ASTPrint, // Parse ASTs and print them.
58 ASTDump, // Parse ASTs and dump them.
59 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000060 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000061 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000062 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek055c2752007-09-06 23:00:42 +000063 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000064 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000065 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000066 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000067 ParsePrintCallbacks, // Parse and print each callback.
68 ParseSyntaxOnly, // Parse and perform semantic analysis.
69 ParseNoop, // Parse with noop callbacks.
70 RunPreprocessorOnly, // Just lex, no output.
71 PrintPreprocessedInput, // -E mode.
72 DumpTokens // Token dump mode.
73};
74
75static llvm::cl::opt<ProgActions>
76ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
77 llvm::cl::init(ParseSyntaxOnly),
78 llvm::cl::values(
79 clEnumValN(RunPreprocessorOnly, "Eonly",
80 "Just run preprocessor, no output (for timings)"),
81 clEnumValN(PrintPreprocessedInput, "E",
82 "Run preprocessor, emit preprocessed file"),
83 clEnumValN(DumpTokens, "dumptokens",
84 "Run preprocessor, dump internal rep of tokens"),
85 clEnumValN(ParseNoop, "parse-noop",
86 "Run parser with noop callbacks (for timings)"),
87 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
88 "Run parser and perform semantic analysis"),
89 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
90 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +000091 clEnumValN(ASTPrint, "ast-print",
92 "Build ASTs and then pretty-print them"),
93 clEnumValN(ASTDump, "ast-dump",
94 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +000095 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +000096 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +000097 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +000098 "Run parser, then build and print CFGs."),
99 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000100 "Run parser, then build and view CFGs with Graphviz."),
101 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000102 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000103 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000104 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000105 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000106 "Flag warnings of uses of unitialized variables."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000107 clEnumValN(TestSerialization, "test-pickling",
108 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000110 "Build ASTs then convert to LLVM, emit .ll file"),
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000111 clEnumValN(SerializeAST, "serialize-ast",
112 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000113 clEnumValN(RewriteTest, "rewrite-test",
114 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 clEnumValEnd));
116
Ted Kremenek41193e42007-09-26 19:42:19 +0000117static llvm::cl::opt<bool>
118VerifyDiagnostics("verify",
119 llvm::cl::desc("Verify emitted diagnostics and warnings."));
120
Reid Spencer5f016e22007-07-11 17:01:13 +0000121//===----------------------------------------------------------------------===//
122// Language Options
123//===----------------------------------------------------------------------===//
124
125enum LangKind {
126 langkind_unspecified,
127 langkind_c,
128 langkind_c_cpp,
129 langkind_cxx,
130 langkind_cxx_cpp,
131 langkind_objc,
132 langkind_objc_cpp,
133 langkind_objcxx,
134 langkind_objcxx_cpp
135};
136
137/* TODO: GCC also accepts:
138 c-header c++-header objective-c-header objective-c++-header
139 assembler assembler-with-cpp
140 ada, f77*, ratfor (!), f95, java, treelang
141 */
142static llvm::cl::opt<LangKind>
143BaseLang("x", llvm::cl::desc("Base language to compile"),
144 llvm::cl::init(langkind_unspecified),
145 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
146 clEnumValN(langkind_cxx, "c++", "C++"),
147 clEnumValN(langkind_objc, "objective-c", "Objective C"),
148 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
149 clEnumValN(langkind_c_cpp, "c-cpp-output",
150 "Preprocessed C"),
151 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
152 "Preprocessed C++"),
153 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
154 "Preprocessed Objective C"),
155 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
156 "Preprocessed Objective C++"),
157 clEnumValEnd));
158
159static llvm::cl::opt<bool>
160LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
161 llvm::cl::Hidden);
162static llvm::cl::opt<bool>
163LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
164 llvm::cl::Hidden);
165
Ted Kremenek8904f152007-12-05 23:49:08 +0000166/// InitializeBaseLanguage - Handle the -x foo options.
167static void InitializeBaseLanguage() {
168 if (LangObjC)
169 BaseLang = langkind_objc;
170 else if (LangObjCXX)
171 BaseLang = langkind_objcxx;
172}
173
174static LangKind GetLanguage(const std::string &Filename) {
175 if (BaseLang != langkind_unspecified)
176 return BaseLang;
177
178 std::string::size_type DotPos = Filename.rfind('.');
179
180 if (DotPos == std::string::npos) {
181 BaseLang = langkind_c; // Default to C if no extension.
Reid Spencer5f016e22007-07-11 17:01:13 +0000182 }
183
Ted Kremenek8904f152007-12-05 23:49:08 +0000184 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
185 // C header: .h
186 // C++ header: .hh or .H;
187 // assembler no preprocessing: .s
188 // assembler: .S
189 if (Ext == "c")
190 return langkind_c;
191 else if (Ext == "i")
192 return langkind_c_cpp;
193 else if (Ext == "ii")
194 return langkind_cxx_cpp;
195 else if (Ext == "m")
196 return langkind_objc;
197 else if (Ext == "mi")
198 return langkind_objc_cpp;
199 else if (Ext == "mm" || Ext == "M")
200 return langkind_objcxx;
201 else if (Ext == "mii")
202 return langkind_objcxx_cpp;
203 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
204 Ext == "c++" || Ext == "cp" || Ext == "cxx")
205 return langkind_cxx;
206 else
207 return langkind_c;
208}
209
210
211static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 // FIXME: implement -fpreprocessed mode.
213 bool NoPreprocess = false;
214
Ted Kremenek8904f152007-12-05 23:49:08 +0000215 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000216 default: assert(0 && "Unknown language kind!");
217 case langkind_c_cpp:
218 NoPreprocess = true;
219 // FALLTHROUGH
220 case langkind_c:
221 break;
222 case langkind_cxx_cpp:
223 NoPreprocess = true;
224 // FALLTHROUGH
225 case langkind_cxx:
226 Options.CPlusPlus = 1;
227 break;
228 case langkind_objc_cpp:
229 NoPreprocess = true;
230 // FALLTHROUGH
231 case langkind_objc:
232 Options.ObjC1 = Options.ObjC2 = 1;
233 break;
234 case langkind_objcxx_cpp:
235 NoPreprocess = true;
236 // FALLTHROUGH
237 case langkind_objcxx:
238 Options.ObjC1 = Options.ObjC2 = 1;
239 Options.CPlusPlus = 1;
240 break;
241 }
242}
243
244/// LangStds - Language standards we support.
245enum LangStds {
246 lang_unspecified,
247 lang_c89, lang_c94, lang_c99,
248 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000249 lang_cxx98, lang_gnucxx98,
250 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000251};
252
253static llvm::cl::opt<LangStds>
254LangStd("std", llvm::cl::desc("Language standard to compile for"),
255 llvm::cl::init(lang_unspecified),
256 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
257 clEnumValN(lang_c89, "c90", "ISO C 1990"),
258 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
259 clEnumValN(lang_c94, "iso9899:199409",
260 "ISO C 1990 with amendment 1"),
261 clEnumValN(lang_c99, "c99", "ISO C 1999"),
262// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
263 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
264// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
265 clEnumValN(lang_gnu89, "gnu89",
266 "ISO C 1990 with GNU extensions (default for C)"),
267 clEnumValN(lang_gnu99, "gnu99",
268 "ISO C 1999 with GNU extensions"),
269 clEnumValN(lang_gnu99, "gnu9x",
270 "ISO C 1999 with GNU extensions"),
271 clEnumValN(lang_cxx98, "c++98",
272 "ISO C++ 1998 with amendments"),
273 clEnumValN(lang_gnucxx98, "gnu++98",
274 "ISO C++ 1998 with amendments and GNU "
275 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000276 clEnumValN(lang_cxx0x, "c++0x",
277 "Upcoming ISO C++ 200x with amendments"),
278 clEnumValN(lang_gnucxx0x, "gnu++0x",
279 "Upcoming ISO C++ 200x with amendments and GNU "
280 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 clEnumValEnd));
282
283static llvm::cl::opt<bool>
284NoOperatorNames("fno-operator-names",
285 llvm::cl::desc("Do not treat C++ operator name keywords as "
286 "synonyms for operators"));
287
Anders Carlssonee98ac52007-10-15 02:50:23 +0000288static llvm::cl::opt<bool>
289PascalStrings("fpascal-strings",
290 llvm::cl::desc("Recognize and construct Pascal-style "
291 "string literals"));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000292
293static llvm::cl::opt<bool>
294WritableStrings("fwritable-strings",
295 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000296
297static llvm::cl::opt<bool>
298LaxVectorConversions("flax-vector-conversions",
299 llvm::cl::desc("Allow implicit conversions between vectors"
300 " with a different number of elements or "
301 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000302// FIXME: add:
303// -ansi
304// -trigraphs
305// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000306// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000307static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 if (LangStd == lang_unspecified) {
309 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000310 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 default: assert(0 && "Unknown base language");
312 case langkind_c:
313 case langkind_c_cpp:
314 case langkind_objc:
315 case langkind_objc_cpp:
316 LangStd = lang_gnu99;
317 break;
318 case langkind_cxx:
319 case langkind_cxx_cpp:
320 case langkind_objcxx:
321 case langkind_objcxx_cpp:
322 LangStd = lang_gnucxx98;
323 break;
324 }
325 }
326
327 switch (LangStd) {
328 default: assert(0 && "Unknown language standard!");
329
330 // Fall through from newer standards to older ones. This isn't really right.
331 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000332 case lang_gnucxx0x:
333 case lang_cxx0x:
334 Options.CPlusPlus0x = 1;
335 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 case lang_gnucxx98:
337 case lang_cxx98:
338 Options.CPlusPlus = 1;
339 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000340 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 // FALL THROUGH.
342 case lang_gnu99:
343 case lang_c99:
344 Options.Digraphs = 1;
345 Options.C99 = 1;
346 Options.HexFloats = 1;
347 // FALL THROUGH.
348 case lang_gnu89:
349 Options.BCPLComment = 1; // Only for C99/C++.
350 // FALL THROUGH.
351 case lang_c94:
352 case lang_c89:
353 break;
354 }
355
356 Options.Trigraphs = 1; // -trigraphs or -ansi
357 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000358 Options.PascalStrings = PascalStrings;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000359 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000360 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000361}
362
363//===----------------------------------------------------------------------===//
364// Our DiagnosticClient implementation
365//===----------------------------------------------------------------------===//
366
367// FIXME: Werror should take a list of things, -Werror=foo,bar
368static llvm::cl::opt<bool>
369WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
370
371static llvm::cl::opt<bool>
372WarnOnExtensions("pedantic", llvm::cl::init(false),
373 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
374
375static llvm::cl::opt<bool>
376ErrorOnExtensions("pedantic-errors",
377 llvm::cl::desc("Issue an error on uses of GCC extensions"));
378
379static llvm::cl::opt<bool>
380WarnUnusedMacros("Wunused_macros",
381 llvm::cl::desc("Warn for unused macros in the main translation unit"));
382
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000383static llvm::cl::opt<bool>
384WarnFloatEqual("Wfloat-equal",
385 llvm::cl::desc("Warn about equality comparisons of floating point values."));
386
Reid Spencer5f016e22007-07-11 17:01:13 +0000387/// InitializeDiagnostics - Initialize the diagnostic object, based on the
388/// current command line option settings.
389static void InitializeDiagnostics(Diagnostic &Diags) {
390 Diags.setWarningsAsErrors(WarningsAsErrors);
391 Diags.setWarnOnExtensions(WarnOnExtensions);
392 Diags.setErrorOnExtensions(ErrorOnExtensions);
393
394 // Silence the "macro is not used" warning unless requested.
395 if (!WarnUnusedMacros)
396 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000397
398 // Silence "floating point comparison" warnings unless requested.
399 if (!WarnFloatEqual)
400 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000401}
402
403//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000404// Target Triple Processing.
405//===----------------------------------------------------------------------===//
406
407static llvm::cl::opt<std::string>
408TargetTriple("triple",
409 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
410
411static llvm::cl::list<std::string>
412Archs("arch",
413 llvm::cl::desc("Specify target architecture (e.g. i686)."));
414
415namespace {
416 class TripleProcessor {
417 llvm::StringMap<char> TriplesProcessed;
418 std::vector<std::string>& triples;
419 public:
420 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
421
422 void addTriple(const std::string& t) {
423 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
424 TriplesProcessed.end()) {
425 triples.push_back(t);
426 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
427 }
428 }
429 };
430}
431
432static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000433 // Initialize base triple. If a -triple option has been specified, use
434 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000435 std::string Triple = TargetTriple;
436 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000437
438 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000439 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000440
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000441 if (firstDash == std::string::npos) {
442 fprintf(stderr,
443 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000444 Triple.c_str());
445 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000446 }
Ted Kremenekae360762007-12-03 22:06:55 +0000447
Chris Lattner6590d212007-12-12 05:01:48 +0000448 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000449
450 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000451 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
452 Triple.c_str());
453 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000454 }
Ted Kremenekae360762007-12-03 22:06:55 +0000455
456 // Create triple cacher.
457 TripleProcessor tp(triples);
458
459 // Add the primary triple to our set of triples if we are using the
460 // host-triple with no archs or using a specified target triple.
461 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000462 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000463
464 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
465 tp.addTriple(Archs[i] + "-" + suffix);
466}
467
468//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000469// Preprocessor Initialization
470//===----------------------------------------------------------------------===//
471
472// FIXME: Preprocessor builtins to support.
473// -A... - Play with #assertions
474// -undef - Undefine all predefined macros
475
476static llvm::cl::list<std::string>
477D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
478 llvm::cl::desc("Predefine the specified macro"));
479static llvm::cl::list<std::string>
480U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
481 llvm::cl::desc("Undefine the specified macro"));
482
483// Append a #define line to Buf for Macro. Macro should be of the form XXX,
484// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
485// "#define XXX Y z W". To get a #define with no value, use "XXX=".
486static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
487 const char *Command = "#define ") {
488 Buf.insert(Buf.end(), Command, Command+strlen(Command));
489 if (const char *Equal = strchr(Macro, '=')) {
490 // Turn the = into ' '.
491 Buf.insert(Buf.end(), Macro, Equal);
492 Buf.push_back(' ');
493 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
494 } else {
495 // Push "macroname 1".
496 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
497 Buf.push_back(' ');
498 Buf.push_back('1');
499 }
500 Buf.push_back('\n');
501}
502
Reid Spencer5f016e22007-07-11 17:01:13 +0000503
Chris Lattner53b0dab2007-10-09 22:10:18 +0000504/// InitializePreprocessor - Initialize the preprocessor getting it and the
505/// environment ready to process a single file. This returns the file ID for the
506/// input file. If a failure happens, it returns 0.
507///
508static unsigned InitializePreprocessor(Preprocessor &PP,
509 const std::string &InFile,
510 SourceManager &SourceMgr,
511 HeaderSearch &HeaderInfo,
512 const LangOptions &LangInfo,
513 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000514
Chris Lattner53b0dab2007-10-09 22:10:18 +0000515 FileManager &FileMgr = HeaderInfo.getFileMgr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000516
Chris Lattner53b0dab2007-10-09 22:10:18 +0000517 // Figure out where to get and map in the main file.
518 unsigned MainFileID = 0;
519 if (InFile != "-") {
520 const FileEntry *File = FileMgr.getFile(InFile);
521 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
522 if (MainFileID == 0) {
523 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
524 return 0;
525 }
526 } else {
527 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
528 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
529 if (MainFileID == 0) {
530 fprintf(stderr, "Error reading standard input! Empty?\n");
531 return 0;
532 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000533 }
534
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 // Add macros from the command line.
536 // FIXME: Should traverse the #define/#undef lists in parallel.
537 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000538 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000540 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
541
542 // FIXME: Read any files specified by -imacros or -include.
543
544 // Null terminate PredefinedBuffer and add it.
545 PredefineBuffer.push_back(0);
546 PP.setPredefines(&PredefineBuffer[0]);
547
548 // Once we've read this, we're done.
549 return MainFileID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000550}
Chris Lattner53b0dab2007-10-09 22:10:18 +0000551
552
Reid Spencer5f016e22007-07-11 17:01:13 +0000553
554//===----------------------------------------------------------------------===//
555// Preprocessor include path information.
556//===----------------------------------------------------------------------===//
557
558// This tool exports a large number of command line options to control how the
559// preprocessor searches for header files. At root, however, the Preprocessor
560// object takes a very simple interface: a list of directories to search for
561//
562// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000563// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000564//
565// FIXME: -include,-imacros
566
567static llvm::cl::opt<bool>
568nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
569
570// Various command line options. These four add directories to each chain.
571static llvm::cl::list<std::string>
572F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
573 llvm::cl::desc("Add directory to framework include search path"));
574static llvm::cl::list<std::string>
575I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
576 llvm::cl::desc("Add directory to include search path"));
577static llvm::cl::list<std::string>
578idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
579 llvm::cl::desc("Add directory to AFTER include search path"));
580static llvm::cl::list<std::string>
581iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
582 llvm::cl::desc("Add directory to QUOTE include search path"));
583static llvm::cl::list<std::string>
584isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
585 llvm::cl::desc("Add directory to SYSTEM include search path"));
586
587// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
588static llvm::cl::list<std::string>
589iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
590 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
591static llvm::cl::list<std::string>
592iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
593 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
594static llvm::cl::list<std::string>
595iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
596 llvm::cl::Prefix,
597 llvm::cl::desc("Set directory to include search path with prefix"));
598
Chris Lattner0c946412007-08-26 17:47:35 +0000599static llvm::cl::opt<std::string>
600isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
601 llvm::cl::desc("Set the system root directory (usually /)"));
602
Reid Spencer5f016e22007-07-11 17:01:13 +0000603// Finally, implement the code that groks the options above.
604enum IncludeDirGroup {
605 Quoted = 0,
606 Angled,
607 System,
608 After
609};
610
611static std::vector<DirectoryLookup> IncludeGroup[4];
612
613/// AddPath - Add the specified path to the specified group list.
614///
615static void AddPath(const std::string &Path, IncludeDirGroup Group,
616 bool isCXXAware, bool isUserSupplied,
617 bool isFramework, FileManager &FM) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000618 assert(!Path.empty() && "can't handle empty path here");
619
Chris Lattner0c946412007-08-26 17:47:35 +0000620 const DirectoryEntry *DE;
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000621 if (Group == System) {
622 if (isysroot != "/")
623 DE = FM.getDirectory(isysroot + "/" + Path);
624 else if (Path[0] == '/')
625 DE = FM.getDirectory(Path);
626 else
627 DE = FM.getDirectory("/" + Path);
628 } else
Chris Lattner0c946412007-08-26 17:47:35 +0000629 DE = FM.getDirectory(Path);
630
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 if (DE == 0) {
632 if (Verbose)
633 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
634 Path.c_str());
635 return;
636 }
637
638 DirectoryLookup::DirType Type;
639 if (Group == Quoted || Group == Angled)
640 Type = DirectoryLookup::NormalHeaderDir;
641 else if (isCXXAware)
642 Type = DirectoryLookup::SystemHeaderDir;
643 else
644 Type = DirectoryLookup::ExternCSystemHeaderDir;
645
646 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
647 isFramework));
648}
649
650/// RemoveDuplicates - If there are duplicate directory entries in the specified
651/// search list, remove the later (dead) ones.
652static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
653 std::set<const DirectoryEntry *> SeenDirs;
654 for (unsigned i = 0; i != SearchList.size(); ++i) {
655 // If this isn't the first time we've seen this dir, remove it.
656 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
657 if (Verbose)
658 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
659 SearchList[i].getDir()->getName());
660 SearchList.erase(SearchList.begin()+i);
661 --i;
662 }
663 }
664}
665
666/// InitializeIncludePaths - Process the -I options and set them in the
667/// HeaderSearch object.
668static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000669 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 // Handle -F... options.
671 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
672 AddPath(F_dirs[i], Angled, false, true, true, FM);
673
674 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000675 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
676 AddPath(I_dirs[i], Angled, false, true, false, FM);
Reid Spencer5f016e22007-07-11 17:01:13 +0000677
678 // Handle -idirafter... options.
679 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
680 AddPath(idirafter_dirs[i], After, false, true, false, FM);
681
682 // Handle -iquote... options.
683 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
684 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
685
686 // Handle -isystem... options.
687 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
688 AddPath(isystem_dirs[i], System, false, true, false, FM);
689
690 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
691 // parallel, processing the values in order of occurance to get the right
692 // prefixes.
693 {
694 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
695 unsigned iprefix_idx = 0;
696 unsigned iwithprefix_idx = 0;
697 unsigned iwithprefixbefore_idx = 0;
698 bool iprefix_done = iprefix_vals.empty();
699 bool iwithprefix_done = iwithprefix_vals.empty();
700 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
701 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
702 if (!iprefix_done &&
703 (iwithprefix_done ||
704 iprefix_vals.getPosition(iprefix_idx) <
705 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
706 (iwithprefixbefore_done ||
707 iprefix_vals.getPosition(iprefix_idx) <
708 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
709 Prefix = iprefix_vals[iprefix_idx];
710 ++iprefix_idx;
711 iprefix_done = iprefix_idx == iprefix_vals.size();
712 } else if (!iwithprefix_done &&
713 (iwithprefixbefore_done ||
714 iwithprefix_vals.getPosition(iwithprefix_idx) <
715 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
716 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
717 System, false, false, false, FM);
718 ++iwithprefix_idx;
719 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
720 } else {
721 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
722 Angled, false, false, false, FM);
723 ++iwithprefixbefore_idx;
724 iwithprefixbefore_done =
725 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
726 }
727 }
728 }
729
730 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
731 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
732
733 // FIXME: temporary hack: hard-coded paths.
734 // FIXME: get these from the target?
735 if (!nostdinc) {
736 if (Lang.CPlusPlus) {
737 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
738 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
739 false, FM);
740 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
741 }
742
743 AddPath("/usr/local/include", System, false, false, false, FM);
744 // leopard
745 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
746 false, false, false, FM);
747 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
748 System, false, false, false, FM);
749 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
750 "4.0.1/../../../../powerpc-apple-darwin0/include",
751 System, false, false, false, FM);
752
753 // tiger
754 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
755 false, false, false, FM);
756 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
757 System, false, false, false, FM);
758 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
759 "4.0.1/../../../../powerpc-apple-darwin8/include",
760 System, false, false, false, FM);
761
762 AddPath("/usr/include", System, false, false, false, FM);
763 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
764 AddPath("/Library/Frameworks", System, true, false, true, FM);
765 }
766
767 // Now that we have collected all of the include paths, merge them all
768 // together and tell the preprocessor about them.
769
770 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
771 std::vector<DirectoryLookup> SearchList;
772 SearchList = IncludeGroup[Angled];
773 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
774 IncludeGroup[System].end());
775 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
776 IncludeGroup[After].end());
777 RemoveDuplicates(SearchList);
778 RemoveDuplicates(IncludeGroup[Quoted]);
779
780 // Prepend QUOTED list on the search list.
781 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
782 IncludeGroup[Quoted].end());
783
784
785 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
786 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
787 DontSearchCurDir);
788
789 // If verbose, print the list of directories that will be searched.
790 if (Verbose) {
791 fprintf(stderr, "#include \"...\" search starts here:\n");
792 unsigned QuotedIdx = IncludeGroup[Quoted].size();
793 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
794 if (i == QuotedIdx)
795 fprintf(stderr, "#include <...> search starts here:\n");
796 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
797 }
798 }
799}
800
801
Reid Spencer5f016e22007-07-11 17:01:13 +0000802//===----------------------------------------------------------------------===//
803// Basic Parser driver
804//===----------------------------------------------------------------------===//
805
806static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
807 Parser P(PP, *PA);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000808 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000809
810 // Parsing the specified input file.
811 P.ParseTranslationUnit();
812 delete PA;
813}
814
815//===----------------------------------------------------------------------===//
816// Main driver
817//===----------------------------------------------------------------------===//
818
Ted Kremenekdb094a22007-12-05 18:27:04 +0000819/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
820/// action. These consumers can operate on both ASTs that are freshly
821/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000822static ASTConsumer* CreateASTConsumer(const std::string& InFile,
823 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremenekdb094a22007-12-05 18:27:04 +0000824 const LangOptions& LangOpts) {
825 switch (ProgAction) {
826 default:
827 return NULL;
828
829 case ASTPrint:
830 return CreateASTPrinter();
831
832 case ASTDump:
833 return CreateASTDumper();
834
835 case ASTView:
836 return CreateASTViewer();
837
838 case ParseCFGDump:
839 case ParseCFGView:
840 return CreateCFGDumper(ProgAction == ParseCFGView);
841
842 case AnalysisLiveVariables:
843 return CreateLiveVarAnalyzer();
844
845 case WarnDeadStores:
846 return CreateDeadStoreChecker(Diag);
847
848 case WarnUninitVals:
849 return CreateUnitValsChecker(Diag);
850
851 case TestSerialization:
Ted Kremenekacc9f332007-12-05 21:34:36 +0000852 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000853
854 case EmitLLVM:
855 return CreateLLVMEmitter(Diag, LangOpts);
856
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000857 case SerializeAST: {
858 // FIXME: Allow user to tailor where the file is written.
859 llvm::sys::Path FName = llvm::sys::Path::GetTemporaryDirectory(NULL);
860 FName.appendComponent((InFile + ".ast").c_str());
861
862 if (FName.makeUnique(true,NULL)) {
863 fprintf (stderr, "error: cannot create serialized file: '%s'\n",
864 FName.c_str());
865
866 return NULL;
867 }
868
869 return CreateASTSerializer(FName, Diag, LangOpts);
870 }
871
Ted Kremenekdb094a22007-12-05 18:27:04 +0000872 case RewriteTest:
873 return CreateCodeRewriterTest(Diag);
874 }
875}
876
Reid Spencer5f016e22007-07-11 17:01:13 +0000877/// ProcessInputFile - Process a single input file with the specified state.
878///
879static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
880 const std::string &InFile,
881 SourceManager &SourceMgr,
882 TextDiagnostics &OurDiagnosticClient,
883 HeaderSearch &HeaderInfo,
884 const LangOptions &LangInfo) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000885
886 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000887 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000888
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 switch (ProgAction) {
890 default:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000891 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
892 HeaderInfo.getFileMgr(),
Ted Kremenekdb094a22007-12-05 18:27:04 +0000893 PP.getLangOptions());
894
895 if (!Consumer) {
896 fprintf(stderr, "Unexpected program action!\n");
897 return;
898 }
899 break;
900
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000902 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000903 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000904 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 do {
906 PP.Lex(Tok);
907 PP.DumpToken(Tok, true);
908 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000909 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000910 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 break;
912 }
913 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000914 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000915 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000916 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 do {
918 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000919 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000920 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 break;
922 }
923
924 case PrintPreprocessedInput: // -E mode.
925 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
Chris Lattnerbd247762007-07-22 06:05:44 +0000926 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000927 break;
928
929 case ParseNoop: // -parse-noop
Steve Naroffb4292f22007-10-31 20:55:39 +0000930 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000931 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000932 break;
933
934 case ParsePrintCallbacks:
Steve Naroffb4292f22007-10-31 20:55:39 +0000935 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
936 MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000937 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000938 break;
Ted Kremenek44579782007-09-25 18:37:20 +0000939
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000940 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000941 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +0000942 break;
Chris Lattner580980b2007-09-16 19:46:59 +0000943 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000944
945 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000946 if (VerifyDiagnostics)
Chris Lattner31e6c7d2007-11-03 06:24:16 +0000947 exit(CheckASTConsumer(PP, MainFileID, Consumer));
948
949 // This deletes Consumer.
950 ParseAST(PP, MainFileID, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 }
952
953 if (Stats) {
954 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
955 PP.PrintStats();
956 PP.getIdentifierTable().PrintStats();
957 HeaderInfo.PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +0000958 if (ClearSourceMgr)
959 SourceMgr.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000960 fprintf(stderr, "\n");
961 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000962
963 // For a multi-file compilation, some things are ok with nuking the source
964 // manager tables, other require stable fileid/macroid's across multiple
965 // files.
966 if (ClearSourceMgr) {
967 SourceMgr.clearIDTables();
968 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000969}
970
Ted Kremenek20e97482007-12-12 23:41:08 +0000971static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
972 FileManager& FileMgr) {
973
974 if (VerifyDiagnostics) {
975 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
976 exit (1);
977 }
978
979 llvm::sys::Path Filename(InFile);
980
981 if (!Filename.isValid()) {
982 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
983 exit (1);
984 }
985
986 TranslationUnit* TU = TranslationUnit::ReadBitcodeFile(Filename,FileMgr);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000987 ASTConsumer* Consumer = CreateASTConsumer(InFile,Diag,
988 FileMgr,TU->getLangOpts());
Ted Kremenek20e97482007-12-12 23:41:08 +0000989
990 if (!Consumer) {
991 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
992 exit (1);
993 }
994
995 // FIXME: only work on consumers that do not require MainFileID.
996 Consumer->Initialize(*TU->getContext(),0);
997
998 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
999 Consumer->HandleTopLevelDecl(*I);
1000
1001 delete Consumer;
1002}
1003
1004
Reid Spencer5f016e22007-07-11 17:01:13 +00001005static llvm::cl::list<std::string>
1006InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1007
Ted Kremenek20e97482007-12-12 23:41:08 +00001008static bool isSerializedFile(const std::string& InFile) {
1009 if (InFile.size() < 4)
1010 return false;
1011
1012 const char* s = InFile.c_str()+InFile.size()-4;
1013
1014 return s[0] == '.' &&
1015 s[1] == 'a' &&
1016 s[2] == 's' &&
1017 s[3] == 't';
1018}
1019
Reid Spencer5f016e22007-07-11 17:01:13 +00001020
1021int main(int argc, char **argv) {
1022 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1023 llvm::sys::PrintStackTraceOnErrorSignal();
1024
1025 // If no input was specified, read from stdin.
1026 if (InputFilenames.empty())
1027 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001028
Reid Spencer5f016e22007-07-11 17:01:13 +00001029 // Create a file manager object to provide access to and cache the filesystem.
1030 FileManager FileMgr;
1031
Ted Kremenek31e703b2007-12-11 23:28:38 +00001032 // Create the diagnostic client for reporting errors or for
1033 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001035 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001036 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001037 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 } else {
1039 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001040 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001041
1042 if (InputFilenames.size() != 1) {
1043 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001044 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 return 1;
1046 }
1047 }
1048
1049 // Configure our handling of diagnostics.
1050 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001051 InitializeDiagnostics(Diags);
1052
Chris Lattner4f037832007-12-05 23:24:17 +00001053 // -I- is a deprecated GCC feature, scan for it and reject it.
1054 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1055 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001056 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001057 I_dirs.erase(I_dirs.begin()+i);
1058 --i;
1059 }
1060 }
1061
Reid Spencer5f016e22007-07-11 17:01:13 +00001062 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001063 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001064
Ted Kremenek20e97482007-12-12 23:41:08 +00001065 if (isSerializedFile(InFile))
1066 ProcessSerializedFile(InFile,Diags,FileMgr);
1067 else {
1068 /// Create a SourceManager object. This tracks and owns all the file
1069 /// buffers allocated to a translation unit.
1070 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001071
Ted Kremenek20e97482007-12-12 23:41:08 +00001072 // Initialize language options, inferring file types from input filenames.
1073 LangOptions LangInfo;
1074 InitializeBaseLanguage();
1075 LangKind LK = GetLanguage(InFile);
1076 InitializeLangOptions(LangInfo, LK);
1077 InitializeLanguageStandard(LangInfo, LK);
1078
1079 // Process the -I options and set them in the HeaderInfo.
1080 HeaderSearch HeaderInfo(FileMgr);
1081 DiagClient->setHeaderSearch(HeaderInfo);
1082 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1083
1084 // Get information about the targets being compiled for. Note that this
1085 // pointer and the TargetInfoImpl objects are never deleted by this toy
1086 // driver.
1087 TargetInfo *Target;
1088
1089 // Create triples, and create the TargetInfo.
1090 std::vector<std::string> triples;
1091 CreateTargetTriples(triples);
1092 Target = TargetInfo::CreateTargetInfo(&triples[0],
1093 &triples[0]+triples.size(),
1094 &Diags);
1095
1096 if (Target == 0) {
1097 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1098 triples[0].c_str());
1099 fprintf(stderr, "Please use -triple or -arch.\n");
1100 exit(1);
1101 }
1102
1103 // Set up the preprocessor with these options.
1104 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1105
1106 std::vector<char> PredefineBuffer;
1107 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
1108 HeaderInfo, LangInfo,
1109 PredefineBuffer);
1110
1111 if (!MainFileID) continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00001112
Ted Kremenek20e97482007-12-12 23:41:08 +00001113 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
1114 *DiagClient, HeaderInfo, LangInfo);
1115
1116 HeaderInfo.ClearFileInfo();
1117
1118 if (Stats)
1119 SourceMgr.PrintStats();
1120 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001121 }
1122
1123 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1124
1125 if (NumDiagnostics)
1126 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1127 (NumDiagnostics == 1 ? "" : "s"));
1128
1129 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 FileMgr.PrintStats();
1131 fprintf(stderr, "\n");
1132 }
1133
Chris Lattner96f1a642007-07-21 05:40:53 +00001134 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001135}