blob: 806e7b1c54af779cf7c1a9ffd9601d3856f8fc79 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenek80d53372007-12-12 23:41:08 +000029#include "TranslationUnit.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000030#include "clang/Sema/ASTStreamer.h"
31#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenek40499482007-12-03 22:06:55 +000040#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerb429ae42007-10-11 00:43:27 +000054 RewriteTest, // Rewriter testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000055 EmitLLVM, // Emit a .ll file.
Ted Kremenek397de012007-12-13 00:37:31 +000056 SerializeAST, // Emit a .ast file.
Chris Lattner4045a8a2007-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 Kremenek97f75312007-08-21 21:42:03 +000060 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000061 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremenekaa04c512007-09-06 00:17:54 +000062 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000063 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek0841c702007-09-25 18:37:20 +000064 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek0a03ce62007-09-17 20:49:30 +000065 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000066 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner4045a8a2007-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 Lattner664dd082007-10-11 00:37:43 +000095 clEnumValN(ASTView, "ast-view",
Chris Lattner4045a8a2007-10-11 00:18:28 +000096 "Build ASTs and view them with GraphViz."),
Ted Kremenek97f75312007-08-21 21:42:03 +000097 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000098 "Run parser, then build and print CFGs."),
99 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremenekaa04c512007-09-06 00:17:54 +0000100 "Run parser, then build and view CFGs with Graphviz."),
101 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek05334682007-09-06 21:26:58 +0000102 "Print results of live variable analysis."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000103 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremeneke805c4a2007-09-06 23:00:42 +0000104 "Flag warnings of stores to dead variables."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000105 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000106 "Flag warnings of uses of unitialized variables."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000107 clEnumValN(TestSerialization, "test-pickling",
108 "Run prototype serializtion code."),
Chris Lattner4b009652007-07-25 00:24:17 +0000109 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000110 "Build ASTs then convert to LLVM, emit .ll file"),
Ted Kremenek397de012007-12-13 00:37:31 +0000111 clEnumValN(SerializeAST, "serialize-ast",
112 "Build ASTs and emit .ast file"),
Chris Lattnerb429ae42007-10-11 00:43:27 +0000113 clEnumValN(RewriteTest, "rewrite-test",
114 "Playground for the code rewriter"),
Chris Lattner4b009652007-07-25 00:24:17 +0000115 clEnumValEnd));
116
Ted Kremenek10389cf2007-09-26 19:42:19 +0000117static llvm::cl::opt<bool>
118VerifyDiagnostics("verify",
119 llvm::cl::desc("Verify emitted diagnostics and warnings."));
120
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenek11ad8952007-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.
Chris Lattner4b009652007-07-25 00:24:17 +0000182 }
183
Ted Kremenek11ad8952007-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) {
Chris Lattner4b009652007-07-25 00:24:17 +0000212 // FIXME: implement -fpreprocessed mode.
213 bool NoPreprocess = false;
214
Ted Kremenek11ad8952007-12-05 23:49:08 +0000215 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +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,
249 lang_cxx98, lang_gnucxx98,
250 lang_cxx0x, lang_gnucxx0x
251};
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++)"),
276 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++)"),
281 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 Carlsson55bfe0d2007-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 Lattnerdb6be562007-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 Carlssone87cd982007-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."));
Chris Lattner4b009652007-07-25 00:24:17 +0000302// FIXME: add:
303// -ansi
304// -trigraphs
305// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000306// -fpascal-strings
Ted Kremenek11ad8952007-12-05 23:49:08 +0000307static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000308 if (LangStd == lang_unspecified) {
309 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000310 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +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.
332 case lang_gnucxx0x:
333 case lang_cxx0x:
334 Options.CPlusPlus0x = 1;
335 // FALL THROUGH
336 case lang_gnucxx98:
337 case lang_cxx98:
338 Options.CPlusPlus = 1;
339 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000340 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +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 Carlsson55bfe0d2007-10-15 02:50:23 +0000358 Options.PascalStrings = PascalStrings;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000359 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000360 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenek24f59fb2007-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenek24f59fb2007-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);
Chris Lattner4b009652007-07-25 00:24:17 +0000401}
402
403//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-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 Kremenek40499482007-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 Lattner210c0cc2007-12-12 05:01:48 +0000435 std::string Triple = TargetTriple;
436 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000437
438 // Decompose the base triple into "arch" and suffix.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000439 std::string::size_type firstDash = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000440
Ted Kremenek0a8ce9d2007-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 Lattner210c0cc2007-12-12 05:01:48 +0000444 Triple.c_str());
445 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000446 }
Ted Kremenek40499482007-12-03 22:06:55 +0000447
Chris Lattner210c0cc2007-12-12 05:01:48 +0000448 std::string suffix(Triple, firstDash+1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000449
450 if (suffix.empty()) {
Chris Lattner210c0cc2007-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 Kremenek0a8ce9d2007-12-03 22:11:31 +0000454 }
Ted Kremenek40499482007-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 Lattner210c0cc2007-12-12 05:01:48 +0000462 tp.addTriple(Triple);
Ted Kremenek40499482007-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//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +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
Chris Lattner4b009652007-07-25 00:24:17 +0000503
Chris Lattnerd1f21e12007-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 Lattnerd1f21e12007-10-09 22:10:18 +0000510 std::vector<char> &PredefineBuffer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000511
Chris Lattner968982d2007-12-15 20:48:40 +0000512 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000513
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000514 // Figure out where to get and map in the main file.
515 unsigned MainFileID = 0;
Chris Lattner968982d2007-12-15 20:48:40 +0000516 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattnerd1f21e12007-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 }
Chris Lattner4b009652007-07-25 00:24:17 +0000531 }
532
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerd1f21e12007-10-09 22:10:18 +0000536 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000537 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-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;
Chris Lattner4b009652007-07-25 00:24:17 +0000548}
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000549
550
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerae3dcc02007-08-26 17:47:35 +0000561// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerae3dcc02007-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerc8d80bb2007-12-09 00:39:55 +0000616 assert(!Path.empty() && "can't handle empty path here");
617
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000618 const DirectoryEntry *DE;
Chris Lattnerc8d80bb2007-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 Lattnerae3dcc02007-08-26 17:47:35 +0000627 DE = FM.getDirectory(Path);
628
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner45a56e02007-12-05 23:24:17 +0000667 const LangOptions &Lang) {
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner45a56e02007-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);
Chris Lattner4b009652007-07-25 00:24:17 +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");
794 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
795 }
796 }
797}
798
799
Chris Lattner4b009652007-07-25 00:24:17 +0000800//===----------------------------------------------------------------------===//
801// Basic Parser driver
802//===----------------------------------------------------------------------===//
803
804static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
805 Parser P(PP, *PA);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000806 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000807
808 // Parsing the specified input file.
809 P.ParseTranslationUnit();
810 delete PA;
811}
812
813//===----------------------------------------------------------------------===//
814// Main driver
815//===----------------------------------------------------------------------===//
816
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000817/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
818/// action. These consumers can operate on both ASTs that are freshly
819/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenek397de012007-12-13 00:37:31 +0000820static ASTConsumer* CreateASTConsumer(const std::string& InFile,
821 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000822 const LangOptions& LangOpts) {
823 switch (ProgAction) {
824 default:
825 return NULL;
826
827 case ASTPrint:
828 return CreateASTPrinter();
829
830 case ASTDump:
831 return CreateASTDumper();
832
833 case ASTView:
834 return CreateASTViewer();
835
836 case ParseCFGDump:
837 case ParseCFGView:
838 return CreateCFGDumper(ProgAction == ParseCFGView);
839
840 case AnalysisLiveVariables:
841 return CreateLiveVarAnalyzer();
842
843 case WarnDeadStores:
844 return CreateDeadStoreChecker(Diag);
845
846 case WarnUninitVals:
847 return CreateUnitValsChecker(Diag);
848
849 case TestSerialization:
Ted Kremenek2939b8a2007-12-05 21:34:36 +0000850 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000851
852 case EmitLLVM:
853 return CreateLLVMEmitter(Diag, LangOpts);
854
Ted Kremenek397de012007-12-13 00:37:31 +0000855 case SerializeAST: {
856 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek8df2a4d2007-12-13 17:50:11 +0000857 // FIXME: This is a hack: "/" separator not portable.
858 std::string::size_type idx = InFile.rfind("/");
Ted Kremenek397de012007-12-13 00:37:31 +0000859
Ted Kremenek8df2a4d2007-12-13 17:50:11 +0000860 if (idx != std::string::npos && idx == InFile.size()-1)
Ted Kremenek397de012007-12-13 00:37:31 +0000861 return NULL;
Ted Kremenek8df2a4d2007-12-13 17:50:11 +0000862
863 std::string TargetPrefix( idx == std::string::npos ?
864 InFile : InFile.substr(idx+1));
865
866 llvm::sys::Path FName = llvm::sys::Path((TargetPrefix + ".ast").c_str());
Ted Kremenek397de012007-12-13 00:37:31 +0000867
868 return CreateASTSerializer(FName, Diag, LangOpts);
869 }
870
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000871 case RewriteTest:
872 return CreateCodeRewriterTest(Diag);
873 }
874}
875
Chris Lattner4b009652007-07-25 00:24:17 +0000876/// ProcessInputFile - Process a single input file with the specified state.
877///
878static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
879 const std::string &InFile,
Chris Lattner968982d2007-12-15 20:48:40 +0000880 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenek6856c632007-09-26 18:39:29 +0000881
882 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +0000883 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +0000884
Chris Lattner4b009652007-07-25 00:24:17 +0000885 switch (ProgAction) {
886 default:
Ted Kremenek397de012007-12-13 00:37:31 +0000887 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
Chris Lattner968982d2007-12-15 20:48:40 +0000888 PP.getFileManager(),
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000889 PP.getLangOptions());
890
891 if (!Consumer) {
892 fprintf(stderr, "Unexpected program action!\n");
893 return;
894 }
895 break;
896
Chris Lattner4b009652007-07-25 00:24:17 +0000897 case DumpTokens: { // Token dump mode.
898 Token Tok;
899 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000900 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000901 do {
902 PP.Lex(Tok);
903 PP.DumpToken(Tok, true);
904 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +0000905 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000906 ClearSourceMgr = true;
907 break;
908 }
909 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
910 Token Tok;
911 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000912 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000913 do {
914 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +0000915 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000916 ClearSourceMgr = true;
917 break;
918 }
919
920 case PrintPreprocessedInput: // -E mode.
Chris Lattner968982d2007-12-15 20:48:40 +0000921 DoPrintPreprocessedInput(MainFileID, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000922 ClearSourceMgr = true;
923 break;
924
925 case ParseNoop: // -parse-noop
Steve Naroffebeb4282007-10-31 20:55:39 +0000926 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000927 ClearSourceMgr = true;
928 break;
929
930 case ParsePrintCallbacks:
Steve Naroffebeb4282007-10-31 20:55:39 +0000931 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
932 MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000933 ClearSourceMgr = true;
934 break;
Ted Kremenek0841c702007-09-25 18:37:20 +0000935
Ted Kremenek6856c632007-09-26 18:39:29 +0000936 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +0000937 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000938 break;
Chris Lattner129758d2007-09-16 19:46:59 +0000939 }
Ted Kremenek6856c632007-09-26 18:39:29 +0000940
941 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +0000942 if (VerifyDiagnostics)
Chris Lattner8593cbf2007-11-03 06:24:16 +0000943 exit(CheckASTConsumer(PP, MainFileID, Consumer));
944
945 // This deletes Consumer.
946 ParseAST(PP, MainFileID, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +0000947 }
948
949 if (Stats) {
950 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
951 PP.PrintStats();
952 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +0000953 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +0000954 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +0000955 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +0000956 fprintf(stderr, "\n");
957 }
958
959 // For a multi-file compilation, some things are ok with nuking the source
960 // manager tables, other require stable fileid/macroid's across multiple
961 // files.
Chris Lattner968982d2007-12-15 20:48:40 +0000962 if (ClearSourceMgr)
963 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +0000964}
965
Ted Kremenek80d53372007-12-12 23:41:08 +0000966static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
967 FileManager& FileMgr) {
968
969 if (VerifyDiagnostics) {
970 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
971 exit (1);
972 }
973
974 llvm::sys::Path Filename(InFile);
975
976 if (!Filename.isValid()) {
977 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
978 exit (1);
979 }
980
Ted Kremenek2bd42412007-12-13 18:11:11 +0000981 TranslationUnit* TU = TranslationUnit::ReadBitcodeFile(Filename,FileMgr);
982
983 if (!TU) {
984 fprintf(stderr, "error: file '%s' could not be deserialized\n",
985 InFile.c_str());
986 exit (1);
987 }
988
Ted Kremenek397de012007-12-13 00:37:31 +0000989 ASTConsumer* Consumer = CreateASTConsumer(InFile,Diag,
990 FileMgr,TU->getLangOpts());
Ted Kremenek80d53372007-12-12 23:41:08 +0000991
992 if (!Consumer) {
993 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
994 exit (1);
995 }
996
997 // FIXME: only work on consumers that do not require MainFileID.
998 Consumer->Initialize(*TU->getContext(),0);
999
1000 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1001 Consumer->HandleTopLevelDecl(*I);
1002
1003 delete Consumer;
1004}
1005
1006
Chris Lattner4b009652007-07-25 00:24:17 +00001007static llvm::cl::list<std::string>
1008InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1009
Ted Kremenek80d53372007-12-12 23:41:08 +00001010static bool isSerializedFile(const std::string& InFile) {
1011 if (InFile.size() < 4)
1012 return false;
1013
1014 const char* s = InFile.c_str()+InFile.size()-4;
1015
1016 return s[0] == '.' &&
1017 s[1] == 'a' &&
1018 s[2] == 's' &&
1019 s[3] == 't';
1020}
1021
Chris Lattner4b009652007-07-25 00:24:17 +00001022
1023int main(int argc, char **argv) {
1024 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1025 llvm::sys::PrintStackTraceOnErrorSignal();
1026
1027 // If no input was specified, read from stdin.
1028 if (InputFilenames.empty())
1029 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001030
Chris Lattner4b009652007-07-25 00:24:17 +00001031 // Create a file manager object to provide access to and cache the filesystem.
1032 FileManager FileMgr;
1033
Ted Kremenekb240e822007-12-11 23:28:38 +00001034 // Create the diagnostic client for reporting errors or for
1035 // implementing -verify.
Chris Lattner4b009652007-07-25 00:24:17 +00001036 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek56b70862007-09-26 20:14:22 +00001037 if (!VerifyDiagnostics) {
Chris Lattner4b009652007-07-25 00:24:17 +00001038 // Print diagnostics to stderr by default.
Ted Kremenekb3ee1932007-12-11 21:27:55 +00001039 DiagClient.reset(new TextDiagnosticPrinter());
Chris Lattner4b009652007-07-25 00:24:17 +00001040 } else {
1041 // When checking diagnostics, just buffer them up.
Ted Kremenekb3ee1932007-12-11 21:27:55 +00001042 DiagClient.reset(new TextDiagnosticBuffer());
Chris Lattner4b009652007-07-25 00:24:17 +00001043
1044 if (InputFilenames.size() != 1) {
1045 fprintf(stderr,
Ted Kremenek56b70862007-09-26 20:14:22 +00001046 "-verify only works on single input files for now.\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001047 return 1;
1048 }
1049 }
1050
1051 // Configure our handling of diagnostics.
1052 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +00001053 InitializeDiagnostics(Diags);
1054
Chris Lattner45a56e02007-12-05 23:24:17 +00001055 // -I- is a deprecated GCC feature, scan for it and reject it.
1056 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1057 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001058 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001059 I_dirs.erase(I_dirs.begin()+i);
1060 --i;
1061 }
1062 }
1063
Chris Lattner4b009652007-07-25 00:24:17 +00001064 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001065 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001066
Ted Kremenek80d53372007-12-12 23:41:08 +00001067 if (isSerializedFile(InFile))
1068 ProcessSerializedFile(InFile,Diags,FileMgr);
1069 else {
1070 /// Create a SourceManager object. This tracks and owns all the file
1071 /// buffers allocated to a translation unit.
1072 SourceManager SourceMgr;
Ted Kremenekb240e822007-12-11 23:28:38 +00001073
Ted Kremenek80d53372007-12-12 23:41:08 +00001074 // Initialize language options, inferring file types from input filenames.
1075 LangOptions LangInfo;
1076 InitializeBaseLanguage();
1077 LangKind LK = GetLanguage(InFile);
1078 InitializeLangOptions(LangInfo, LK);
1079 InitializeLanguageStandard(LangInfo, LK);
1080
1081 // Process the -I options and set them in the HeaderInfo.
1082 HeaderSearch HeaderInfo(FileMgr);
1083 DiagClient->setHeaderSearch(HeaderInfo);
1084 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1085
1086 // Get information about the targets being compiled for. Note that this
1087 // pointer and the TargetInfoImpl objects are never deleted by this toy
1088 // driver.
1089 TargetInfo *Target;
1090
1091 // Create triples, and create the TargetInfo.
1092 std::vector<std::string> triples;
1093 CreateTargetTriples(triples);
1094 Target = TargetInfo::CreateTargetInfo(&triples[0],
1095 &triples[0]+triples.size(),
1096 &Diags);
1097
1098 if (Target == 0) {
1099 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1100 triples[0].c_str());
1101 fprintf(stderr, "Please use -triple or -arch.\n");
1102 exit(1);
1103 }
1104
1105 // Set up the preprocessor with these options.
1106 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1107
1108 std::vector<char> PredefineBuffer;
Chris Lattner968982d2007-12-15 20:48:40 +00001109 unsigned MainFileID = InitializePreprocessor(PP, InFile, PredefineBuffer);
Ted Kremenek80d53372007-12-12 23:41:08 +00001110
1111 if (!MainFileID) continue;
Chris Lattner4b009652007-07-25 00:24:17 +00001112
Chris Lattner968982d2007-12-15 20:48:40 +00001113 ProcessInputFile(PP, MainFileID, InFile, *DiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001114
1115 HeaderInfo.ClearFileInfo();
1116
1117 if (Stats)
1118 SourceMgr.PrintStats();
1119 }
Chris Lattner4b009652007-07-25 00:24:17 +00001120 }
1121
1122 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1123
1124 if (NumDiagnostics)
1125 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1126 (NumDiagnostics == 1 ? "" : "s"));
1127
1128 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001129 FileMgr.PrintStats();
1130 fprintf(stderr, "\n");
1131 }
1132
1133 return Diags.getNumErrors() != 0;
1134}