blob: b3e5c336c356b0dfa35c6ba7b42b20e94fb7dbb5 [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,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000510 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000511
Chris Lattnerdee73592007-12-15 20:48:40 +0000512 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000513
Chris Lattner53b0dab2007-10-09 22:10:18 +0000514 // Figure out where to get and map in the main file.
515 unsigned MainFileID = 0;
Chris Lattnerdee73592007-12-15 20:48:40 +0000516 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000517 if (InFile != "-") {
518 const FileEntry *File = FileMgr.getFile(InFile);
519 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
520 if (MainFileID == 0) {
521 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
522 return 0;
523 }
524 } else {
525 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
526 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
527 if (MainFileID == 0) {
528 fprintf(stderr, "Error reading standard input! Empty?\n");
529 return 0;
530 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000531 }
532
Reid Spencer5f016e22007-07-11 17:01:13 +0000533 // Add macros from the command line.
534 // FIXME: Should traverse the #define/#undef lists in parallel.
535 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000536 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000538 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
539
540 // FIXME: Read any files specified by -imacros or -include.
541
542 // Null terminate PredefinedBuffer and add it.
543 PredefineBuffer.push_back(0);
544 PP.setPredefines(&PredefineBuffer[0]);
545
546 // Once we've read this, we're done.
547 return MainFileID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000548}
Chris Lattner53b0dab2007-10-09 22:10:18 +0000549
550
Reid Spencer5f016e22007-07-11 17:01:13 +0000551
552//===----------------------------------------------------------------------===//
553// Preprocessor include path information.
554//===----------------------------------------------------------------------===//
555
556// This tool exports a large number of command line options to control how the
557// preprocessor searches for header files. At root, however, the Preprocessor
558// object takes a very simple interface: a list of directories to search for
559//
560// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000561// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000562//
563// FIXME: -include,-imacros
564
565static llvm::cl::opt<bool>
566nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
567
568// Various command line options. These four add directories to each chain.
569static llvm::cl::list<std::string>
570F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
571 llvm::cl::desc("Add directory to framework include search path"));
572static llvm::cl::list<std::string>
573I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
574 llvm::cl::desc("Add directory to include search path"));
575static llvm::cl::list<std::string>
576idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
577 llvm::cl::desc("Add directory to AFTER include search path"));
578static llvm::cl::list<std::string>
579iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
580 llvm::cl::desc("Add directory to QUOTE include search path"));
581static llvm::cl::list<std::string>
582isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
583 llvm::cl::desc("Add directory to SYSTEM include search path"));
584
585// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
586static llvm::cl::list<std::string>
587iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
588 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
589static llvm::cl::list<std::string>
590iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
591 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
592static llvm::cl::list<std::string>
593iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
594 llvm::cl::Prefix,
595 llvm::cl::desc("Set directory to include search path with prefix"));
596
Chris Lattner0c946412007-08-26 17:47:35 +0000597static llvm::cl::opt<std::string>
598isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
599 llvm::cl::desc("Set the system root directory (usually /)"));
600
Reid Spencer5f016e22007-07-11 17:01:13 +0000601// Finally, implement the code that groks the options above.
602enum IncludeDirGroup {
603 Quoted = 0,
604 Angled,
605 System,
606 After
607};
608
609static std::vector<DirectoryLookup> IncludeGroup[4];
610
611/// AddPath - Add the specified path to the specified group list.
612///
613static void AddPath(const std::string &Path, IncludeDirGroup Group,
614 bool isCXXAware, bool isUserSupplied,
615 bool isFramework, FileManager &FM) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000616 assert(!Path.empty() && "can't handle empty path here");
617
Chris Lattner0c946412007-08-26 17:47:35 +0000618 const DirectoryEntry *DE;
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000619 if (Group == System) {
620 if (isysroot != "/")
621 DE = FM.getDirectory(isysroot + "/" + Path);
622 else if (Path[0] == '/')
623 DE = FM.getDirectory(Path);
624 else
625 DE = FM.getDirectory("/" + Path);
626 } else
Chris Lattner0c946412007-08-26 17:47:35 +0000627 DE = FM.getDirectory(Path);
628
Reid Spencer5f016e22007-07-11 17:01:13 +0000629 if (DE == 0) {
630 if (Verbose)
631 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
632 Path.c_str());
633 return;
634 }
635
636 DirectoryLookup::DirType Type;
637 if (Group == Quoted || Group == Angled)
638 Type = DirectoryLookup::NormalHeaderDir;
639 else if (isCXXAware)
640 Type = DirectoryLookup::SystemHeaderDir;
641 else
642 Type = DirectoryLookup::ExternCSystemHeaderDir;
643
644 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
645 isFramework));
646}
647
648/// RemoveDuplicates - If there are duplicate directory entries in the specified
649/// search list, remove the later (dead) ones.
650static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
651 std::set<const DirectoryEntry *> SeenDirs;
652 for (unsigned i = 0; i != SearchList.size(); ++i) {
653 // If this isn't the first time we've seen this dir, remove it.
654 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
655 if (Verbose)
656 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
657 SearchList[i].getDir()->getName());
658 SearchList.erase(SearchList.begin()+i);
659 --i;
660 }
661 }
662}
663
664/// InitializeIncludePaths - Process the -I options and set them in the
665/// HeaderSearch object.
666static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000667 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 // Handle -F... options.
669 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
670 AddPath(F_dirs[i], Angled, false, true, true, FM);
671
672 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000673 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
674 AddPath(I_dirs[i], Angled, false, true, false, FM);
Reid Spencer5f016e22007-07-11 17:01:13 +0000675
676 // Handle -idirafter... options.
677 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
678 AddPath(idirafter_dirs[i], After, false, true, false, FM);
679
680 // Handle -iquote... options.
681 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
682 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
683
684 // Handle -isystem... options.
685 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
686 AddPath(isystem_dirs[i], System, false, true, false, FM);
687
688 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
689 // parallel, processing the values in order of occurance to get the right
690 // prefixes.
691 {
692 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
693 unsigned iprefix_idx = 0;
694 unsigned iwithprefix_idx = 0;
695 unsigned iwithprefixbefore_idx = 0;
696 bool iprefix_done = iprefix_vals.empty();
697 bool iwithprefix_done = iwithprefix_vals.empty();
698 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
699 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
700 if (!iprefix_done &&
701 (iwithprefix_done ||
702 iprefix_vals.getPosition(iprefix_idx) <
703 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
704 (iwithprefixbefore_done ||
705 iprefix_vals.getPosition(iprefix_idx) <
706 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
707 Prefix = iprefix_vals[iprefix_idx];
708 ++iprefix_idx;
709 iprefix_done = iprefix_idx == iprefix_vals.size();
710 } else if (!iwithprefix_done &&
711 (iwithprefixbefore_done ||
712 iwithprefix_vals.getPosition(iwithprefix_idx) <
713 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
714 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
715 System, false, false, false, FM);
716 ++iwithprefix_idx;
717 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
718 } else {
719 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
720 Angled, false, false, false, FM);
721 ++iwithprefixbefore_idx;
722 iwithprefixbefore_done =
723 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
724 }
725 }
726 }
727
728 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
729 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
730
731 // FIXME: temporary hack: hard-coded paths.
732 // FIXME: get these from the target?
733 if (!nostdinc) {
734 if (Lang.CPlusPlus) {
735 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
736 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
737 false, FM);
738 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
739 }
740
741 AddPath("/usr/local/include", System, false, false, false, FM);
742 // leopard
743 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
744 false, false, false, FM);
745 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
746 System, false, false, false, FM);
747 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
748 "4.0.1/../../../../powerpc-apple-darwin0/include",
749 System, false, false, false, FM);
750
751 // tiger
752 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
753 false, false, false, FM);
754 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
755 System, false, false, false, FM);
756 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
757 "4.0.1/../../../../powerpc-apple-darwin8/include",
758 System, false, false, false, FM);
759
760 AddPath("/usr/include", System, false, false, false, FM);
761 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
762 AddPath("/Library/Frameworks", System, true, false, true, FM);
763 }
764
765 // Now that we have collected all of the include paths, merge them all
766 // together and tell the preprocessor about them.
767
768 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
769 std::vector<DirectoryLookup> SearchList;
770 SearchList = IncludeGroup[Angled];
771 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
772 IncludeGroup[System].end());
773 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
774 IncludeGroup[After].end());
775 RemoveDuplicates(SearchList);
776 RemoveDuplicates(IncludeGroup[Quoted]);
777
778 // Prepend QUOTED list on the search list.
779 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
780 IncludeGroup[Quoted].end());
781
782
783 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
784 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
785 DontSearchCurDir);
786
787 // If verbose, print the list of directories that will be searched.
788 if (Verbose) {
789 fprintf(stderr, "#include \"...\" search starts here:\n");
790 unsigned QuotedIdx = IncludeGroup[Quoted].size();
791 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
792 if (i == QuotedIdx)
793 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner80e17152007-12-15 23:11:06 +0000794 fprintf(stderr, " %s", SearchList[i].getDir()->getName());
795 if (SearchList[i].isFramework())
796 fprintf(stderr, " (framework directory)");
797 fprintf(stderr, "\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 }
Chris Lattner80e17152007-12-15 23:11:06 +0000799 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000800 }
801}
802
803
Reid Spencer5f016e22007-07-11 17:01:13 +0000804//===----------------------------------------------------------------------===//
805// Basic Parser driver
806//===----------------------------------------------------------------------===//
807
808static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
809 Parser P(PP, *PA);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000810 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000811
812 // Parsing the specified input file.
813 P.ParseTranslationUnit();
814 delete PA;
815}
816
817//===----------------------------------------------------------------------===//
818// Main driver
819//===----------------------------------------------------------------------===//
820
Ted Kremenekdb094a22007-12-05 18:27:04 +0000821/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
822/// action. These consumers can operate on both ASTs that are freshly
823/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000824static ASTConsumer* CreateASTConsumer(const std::string& InFile,
825 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremenekdb094a22007-12-05 18:27:04 +0000826 const LangOptions& LangOpts) {
827 switch (ProgAction) {
828 default:
829 return NULL;
830
831 case ASTPrint:
832 return CreateASTPrinter();
833
834 case ASTDump:
835 return CreateASTDumper();
836
837 case ASTView:
838 return CreateASTViewer();
839
840 case ParseCFGDump:
841 case ParseCFGView:
842 return CreateCFGDumper(ProgAction == ParseCFGView);
843
844 case AnalysisLiveVariables:
845 return CreateLiveVarAnalyzer();
846
847 case WarnDeadStores:
848 return CreateDeadStoreChecker(Diag);
849
850 case WarnUninitVals:
851 return CreateUnitValsChecker(Diag);
852
853 case TestSerialization:
Ted Kremenekacc9f332007-12-05 21:34:36 +0000854 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000855
856 case EmitLLVM:
857 return CreateLLVMEmitter(Diag, LangOpts);
858
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000859 case SerializeAST: {
860 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek3821d402007-12-13 17:50:11 +0000861 // FIXME: This is a hack: "/" separator not portable.
862 std::string::size_type idx = InFile.rfind("/");
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000863
Ted Kremenek3821d402007-12-13 17:50:11 +0000864 if (idx != std::string::npos && idx == InFile.size()-1)
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000865 return NULL;
Ted Kremenek3821d402007-12-13 17:50:11 +0000866
867 std::string TargetPrefix( idx == std::string::npos ?
868 InFile : InFile.substr(idx+1));
869
870 llvm::sys::Path FName = llvm::sys::Path((TargetPrefix + ".ast").c_str());
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000871
872 return CreateASTSerializer(FName, Diag, LangOpts);
873 }
874
Ted Kremenekdb094a22007-12-05 18:27:04 +0000875 case RewriteTest:
876 return CreateCodeRewriterTest(Diag);
877 }
878}
879
Reid Spencer5f016e22007-07-11 17:01:13 +0000880/// ProcessInputFile - Process a single input file with the specified state.
881///
882static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
883 const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +0000884 TextDiagnostics &OurDiagnosticClient) {
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(),
Chris Lattnerdee73592007-12-15 20:48:40 +0000892 PP.getFileManager(),
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.
Chris Lattnerdee73592007-12-15 20:48:40 +0000925 DoPrintPreprocessedInput(MainFileID, PP);
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();
Chris Lattnerdee73592007-12-15 20:48:40 +0000957 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +0000958 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +0000959 PP.getSourceManager().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.
Chris Lattnerdee73592007-12-15 20:48:40 +0000966 if (ClearSourceMgr)
967 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +0000968}
969
Ted Kremenek20e97482007-12-12 23:41:08 +0000970static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
971 FileManager& FileMgr) {
972
973 if (VerifyDiagnostics) {
974 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
975 exit (1);
976 }
977
978 llvm::sys::Path Filename(InFile);
979
980 if (!Filename.isValid()) {
981 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
982 exit (1);
983 }
984
Ted Kremenekfe4e0152007-12-13 18:11:11 +0000985 TranslationUnit* TU = TranslationUnit::ReadBitcodeFile(Filename,FileMgr);
986
987 if (!TU) {
988 fprintf(stderr, "error: file '%s' could not be deserialized\n",
989 InFile.c_str());
990 exit (1);
991 }
992
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000993 ASTConsumer* Consumer = CreateASTConsumer(InFile,Diag,
994 FileMgr,TU->getLangOpts());
Ted Kremenek20e97482007-12-12 23:41:08 +0000995
996 if (!Consumer) {
997 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
998 exit (1);
999 }
1000
1001 // FIXME: only work on consumers that do not require MainFileID.
1002 Consumer->Initialize(*TU->getContext(),0);
1003
1004 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1005 Consumer->HandleTopLevelDecl(*I);
1006
1007 delete Consumer;
1008}
1009
1010
Reid Spencer5f016e22007-07-11 17:01:13 +00001011static llvm::cl::list<std::string>
1012InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1013
Ted Kremenek20e97482007-12-12 23:41:08 +00001014static bool isSerializedFile(const std::string& InFile) {
1015 if (InFile.size() < 4)
1016 return false;
1017
1018 const char* s = InFile.c_str()+InFile.size()-4;
1019
1020 return s[0] == '.' &&
1021 s[1] == 'a' &&
1022 s[2] == 's' &&
1023 s[3] == 't';
1024}
1025
Reid Spencer5f016e22007-07-11 17:01:13 +00001026
1027int main(int argc, char **argv) {
1028 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1029 llvm::sys::PrintStackTraceOnErrorSignal();
1030
1031 // If no input was specified, read from stdin.
1032 if (InputFilenames.empty())
1033 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001034
Reid Spencer5f016e22007-07-11 17:01:13 +00001035 // Create a file manager object to provide access to and cache the filesystem.
1036 FileManager FileMgr;
1037
Ted Kremenek31e703b2007-12-11 23:28:38 +00001038 // Create the diagnostic client for reporting errors or for
1039 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001040 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001041 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001043 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001044 } else {
1045 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001046 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001047
1048 if (InputFilenames.size() != 1) {
1049 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001050 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 return 1;
1052 }
1053 }
1054
1055 // Configure our handling of diagnostics.
1056 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001057 InitializeDiagnostics(Diags);
1058
Chris Lattner4f037832007-12-05 23:24:17 +00001059 // -I- is a deprecated GCC feature, scan for it and reject it.
1060 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1061 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001062 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001063 I_dirs.erase(I_dirs.begin()+i);
1064 --i;
1065 }
1066 }
1067
Reid Spencer5f016e22007-07-11 17:01:13 +00001068 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001069 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001070
Ted Kremenek20e97482007-12-12 23:41:08 +00001071 if (isSerializedFile(InFile))
1072 ProcessSerializedFile(InFile,Diags,FileMgr);
1073 else {
1074 /// Create a SourceManager object. This tracks and owns all the file
1075 /// buffers allocated to a translation unit.
1076 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001077
Ted Kremenek20e97482007-12-12 23:41:08 +00001078 // Initialize language options, inferring file types from input filenames.
1079 LangOptions LangInfo;
1080 InitializeBaseLanguage();
1081 LangKind LK = GetLanguage(InFile);
1082 InitializeLangOptions(LangInfo, LK);
1083 InitializeLanguageStandard(LangInfo, LK);
1084
1085 // Process the -I options and set them in the HeaderInfo.
1086 HeaderSearch HeaderInfo(FileMgr);
1087 DiagClient->setHeaderSearch(HeaderInfo);
1088 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1089
1090 // Get information about the targets being compiled for. Note that this
1091 // pointer and the TargetInfoImpl objects are never deleted by this toy
1092 // driver.
1093 TargetInfo *Target;
1094
1095 // Create triples, and create the TargetInfo.
1096 std::vector<std::string> triples;
1097 CreateTargetTriples(triples);
1098 Target = TargetInfo::CreateTargetInfo(&triples[0],
1099 &triples[0]+triples.size(),
1100 &Diags);
1101
1102 if (Target == 0) {
1103 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1104 triples[0].c_str());
1105 fprintf(stderr, "Please use -triple or -arch.\n");
1106 exit(1);
1107 }
1108
1109 // Set up the preprocessor with these options.
1110 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1111
1112 std::vector<char> PredefineBuffer;
Chris Lattnerdee73592007-12-15 20:48:40 +00001113 unsigned MainFileID = InitializePreprocessor(PP, InFile, PredefineBuffer);
Ted Kremenek20e97482007-12-12 23:41:08 +00001114
1115 if (!MainFileID) continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00001116
Chris Lattnerdee73592007-12-15 20:48:40 +00001117 ProcessInputFile(PP, MainFileID, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001118
1119 HeaderInfo.ClearFileInfo();
1120
1121 if (Stats)
1122 SourceMgr.PrintStats();
1123 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 }
1125
1126 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1127
1128 if (NumDiagnostics)
1129 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1130 (NumDiagnostics == 1 ? "" : "s"));
1131
1132 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 FileMgr.PrintStats();
1134 fprintf(stderr, "\n");
1135 }
1136
Chris Lattner96f1a642007-07-21 05:40:53 +00001137 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001138}