]> granicus.if.org Git - clang/blob - Driver/clang.cpp
pull .ll and .bc writing out of the ASTConsumer destructors into some top
[clang] / Driver / clang.cpp
1 //===--- clang.cpp - C-Language Front-end ---------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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"
26 #include "ASTConsumers.h"
27 #include "TextDiagnosticBuffer.h"
28 #include "TextDiagnosticPrinter.h"
29 #include "clang/AST/TranslationUnit.h"
30 #include "clang/Sema/ParseAST.h"
31 #include "clang/AST/ASTConsumer.h"
32 #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/Module.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/Bitcode/ReaderWriter.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/System/Signals.h"
43 #include "llvm/Config/config.h"
44 #include "llvm/ADT/OwningPtr.h"
45 #include <memory>
46 #include <fstream>
47 using namespace clang;
48
49 //===----------------------------------------------------------------------===//
50 // Global options.
51 //===----------------------------------------------------------------------===//
52
53 static llvm::cl::opt<bool>
54 Verbose("v", llvm::cl::desc("Enable verbose output"));
55 static llvm::cl::opt<bool>
56 Stats("print-stats", 
57       llvm::cl::desc("Print performance metrics and statistics"));
58
59 enum ProgActions {
60   RewriteTest,                  // Rewriter testing stuff.
61   EmitLLVM,                     // Emit a .ll file.
62   EmitBC,                       // Emit a .bc file.
63   SerializeAST,                 // Emit a .ast file.
64   ASTPrint,                     // Parse ASTs and print them.
65   ASTDump,                      // Parse ASTs and dump them.
66   ASTView,                      // Parse ASTs and view them in Graphviz.
67   ParseCFGDump,                 // Parse ASTS. Build CFGs. Print CFGs.
68   ParseCFGView,                 // Parse ASTS. Build CFGs. View CFGs.
69   AnalysisLiveVariables,        // Print results of live-variable analysis.
70   AnalysisGRConstants,          // Perform graph-reachability constant prop.
71   WarnDeadStores,               // Run DeadStores checker on parsed ASTs.
72   WarnDeadStoresCheck,          // Check diagnostics for "DeadStores".
73   WarnUninitVals,               // Run UnitializedVariables checker.
74   TestSerialization,            // Run experimental serialization code.
75   ParsePrintCallbacks,          // Parse and print each callback.
76   ParseSyntaxOnly,              // Parse and perform semantic analysis.
77   ParseNoop,                    // Parse with noop callbacks.
78   RunPreprocessorOnly,          // Just lex, no output.
79   PrintPreprocessedInput,       // -E mode.
80   DumpTokens                    // Token dump mode.
81 };
82
83 static llvm::cl::opt<ProgActions> 
84 ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
85            llvm::cl::init(ParseSyntaxOnly),
86            llvm::cl::values(
87              clEnumValN(RunPreprocessorOnly, "Eonly",
88                         "Just run preprocessor, no output (for timings)"),
89              clEnumValN(PrintPreprocessedInput, "E",
90                         "Run preprocessor, emit preprocessed file"),
91              clEnumValN(DumpTokens, "dumptokens",
92                         "Run preprocessor, dump internal rep of tokens"),
93              clEnumValN(ParseNoop, "parse-noop",
94                         "Run parser with noop callbacks (for timings)"),
95              clEnumValN(ParseSyntaxOnly, "fsyntax-only",
96                         "Run parser and perform semantic analysis"),
97              clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
98                         "Run parser and print each callback invoked"),
99              clEnumValN(ASTPrint, "ast-print",
100                         "Build ASTs and then pretty-print them"),
101              clEnumValN(ASTDump, "ast-dump",
102                         "Build ASTs and then debug dump them"),
103              clEnumValN(ASTView, "ast-view",
104                         "Build ASTs and view them with GraphViz."),
105              clEnumValN(ParseCFGDump, "dump-cfg",
106                         "Run parser, then build and print CFGs."),
107              clEnumValN(ParseCFGView, "view-cfg",
108                         "Run parser, then build and view CFGs with Graphviz."),
109              clEnumValN(AnalysisLiveVariables, "dump-live-variables",
110                         "Print results of live variable analysis."),
111              clEnumValN(WarnDeadStores, "warn-dead-stores",
112                         "Flag warnings of stores to dead variables."),
113              clEnumValN(WarnUninitVals, "warn-uninit-values",
114                         "Flag warnings of uses of unitialized variables."),
115              clEnumValN(AnalysisGRConstants, "grconstants",
116                         "Perform path-sensitive constant propagation."),
117              clEnumValN(TestSerialization, "test-pickling",
118                         "Run prototype serializtion code."),
119              clEnumValN(EmitLLVM, "emit-llvm",
120                         "Build ASTs then convert to LLVM, emit .ll file"),
121              clEnumValN(EmitBC, "emit-llvm-bc",
122                         "Build ASTs then convert to LLVM, emit .bc file"),
123              clEnumValN(SerializeAST, "serialize",
124                         "Build ASTs and emit .ast file"),
125              clEnumValN(RewriteTest, "rewrite-test",
126                         "Playground for the code rewriter"),
127              clEnumValEnd));
128
129
130 static llvm::cl::opt<std::string>
131 OutputFile("o",
132  llvm::cl::value_desc("path"),
133  llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
134                           
135 static llvm::cl::opt<bool>
136 VerifyDiagnostics("verify",
137                   llvm::cl::desc("Verify emitted diagnostics and warnings."));
138
139 //===----------------------------------------------------------------------===//
140 // Language Options
141 //===----------------------------------------------------------------------===//
142
143 enum LangKind {
144   langkind_unspecified,
145   langkind_c,
146   langkind_c_cpp,
147   langkind_cxx,
148   langkind_cxx_cpp,
149   langkind_objc,
150   langkind_objc_cpp,
151   langkind_objcxx,
152   langkind_objcxx_cpp
153 };
154
155 /* TODO: GCC also accepts:
156    c-header c++-header objective-c-header objective-c++-header
157    assembler  assembler-with-cpp
158    ada, f77*, ratfor (!), f95, java, treelang
159  */
160 static llvm::cl::opt<LangKind>
161 BaseLang("x", llvm::cl::desc("Base language to compile"),
162          llvm::cl::init(langkind_unspecified),
163    llvm::cl::values(clEnumValN(langkind_c,     "c",            "C"),
164                     clEnumValN(langkind_cxx,   "c++",          "C++"),
165                     clEnumValN(langkind_objc,  "objective-c",  "Objective C"),
166                     clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
167                     clEnumValN(langkind_c_cpp,     "c-cpp-output",
168                                "Preprocessed C"),
169                     clEnumValN(langkind_cxx_cpp,   "c++-cpp-output",
170                                "Preprocessed C++"),
171                     clEnumValN(langkind_objc_cpp,  "objective-c-cpp-output",
172                                "Preprocessed Objective C"),
173                     clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
174                                "Preprocessed Objective C++"),
175                     clEnumValEnd));
176
177 static llvm::cl::opt<bool>
178 LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
179          llvm::cl::Hidden);
180 static llvm::cl::opt<bool>
181 LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
182            llvm::cl::Hidden);
183
184 /// InitializeBaseLanguage - Handle the -x foo options.
185 static void InitializeBaseLanguage() {
186   if (LangObjC)
187     BaseLang = langkind_objc;
188   else if (LangObjCXX)
189     BaseLang = langkind_objcxx;
190 }
191
192 static LangKind GetLanguage(const std::string &Filename) {
193   if (BaseLang != langkind_unspecified)
194     return BaseLang;
195   
196   std::string::size_type DotPos = Filename.rfind('.');
197
198   if (DotPos == std::string::npos) {
199     BaseLang = langkind_c;  // Default to C if no extension.
200     return langkind_c;
201   }
202   
203   std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
204   // C header: .h
205   // C++ header: .hh or .H;
206   // assembler no preprocessing: .s
207   // assembler: .S
208   if (Ext == "c")
209     return langkind_c;
210   else if (Ext == "i")
211     return langkind_c_cpp;
212   else if (Ext == "ii")
213     return langkind_cxx_cpp;
214   else if (Ext == "m")
215     return langkind_objc;
216   else if (Ext == "mi")
217     return langkind_objc_cpp;
218   else if (Ext == "mm" || Ext == "M")
219     return langkind_objcxx;
220   else if (Ext == "mii")
221     return langkind_objcxx_cpp;
222   else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
223            Ext == "c++" || Ext == "cp" || Ext == "cxx")
224     return langkind_cxx;
225   else
226     return langkind_c;
227 }
228
229
230 static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
231   // FIXME: implement -fpreprocessed mode.
232   bool NoPreprocess = false;
233   
234   switch (LK) {
235   default: assert(0 && "Unknown language kind!");
236   case langkind_c_cpp:
237     NoPreprocess = true;
238     // FALLTHROUGH
239   case langkind_c:
240     break;
241   case langkind_cxx_cpp:
242     NoPreprocess = true;
243     // FALLTHROUGH
244   case langkind_cxx:
245     Options.CPlusPlus = 1;
246     break;
247   case langkind_objc_cpp:
248     NoPreprocess = true;
249     // FALLTHROUGH
250   case langkind_objc:
251     Options.ObjC1 = Options.ObjC2 = 1;
252     break;
253   case langkind_objcxx_cpp:
254     NoPreprocess = true;
255     // FALLTHROUGH
256   case langkind_objcxx:
257     Options.ObjC1 = Options.ObjC2 = 1;
258     Options.CPlusPlus = 1;
259     break;
260   }
261 }
262
263 /// LangStds - Language standards we support.
264 enum LangStds {
265   lang_unspecified,  
266   lang_c89, lang_c94, lang_c99,
267   lang_gnu89, lang_gnu99,
268   lang_cxx98, lang_gnucxx98,
269   lang_cxx0x, lang_gnucxx0x
270 };
271
272 static llvm::cl::opt<LangStds>
273 LangStd("std", llvm::cl::desc("Language standard to compile for"),
274         llvm::cl::init(lang_unspecified),
275   llvm::cl::values(clEnumValN(lang_c89,      "c89",            "ISO C 1990"),
276                    clEnumValN(lang_c89,      "c90",            "ISO C 1990"),
277                    clEnumValN(lang_c89,      "iso9899:1990",   "ISO C 1990"),
278                    clEnumValN(lang_c94,      "iso9899:199409",
279                               "ISO C 1990 with amendment 1"),
280                    clEnumValN(lang_c99,      "c99",            "ISO C 1999"),
281 //                 clEnumValN(lang_c99,      "c9x",            "ISO C 1999"),
282                    clEnumValN(lang_c99,      "iso9899:1999",   "ISO C 1999"),
283 //                 clEnumValN(lang_c99,      "iso9899:199x",   "ISO C 1999"),
284                    clEnumValN(lang_gnu89,    "gnu89",
285                               "ISO C 1990 with GNU extensions (default for C)"),
286                    clEnumValN(lang_gnu99,    "gnu99",
287                               "ISO C 1999 with GNU extensions"),
288                    clEnumValN(lang_gnu99,    "gnu9x",
289                               "ISO C 1999 with GNU extensions"),
290                    clEnumValN(lang_cxx98,    "c++98",
291                               "ISO C++ 1998 with amendments"),
292                    clEnumValN(lang_gnucxx98, "gnu++98",
293                               "ISO C++ 1998 with amendments and GNU "
294                               "extensions (default for C++)"),
295                    clEnumValN(lang_cxx0x,    "c++0x",
296                               "Upcoming ISO C++ 200x with amendments"),
297                    clEnumValN(lang_gnucxx0x, "gnu++0x",
298                               "Upcoming ISO C++ 200x with amendments and GNU "
299                               "extensions (default for C++)"),
300                    clEnumValEnd));
301
302 static llvm::cl::opt<bool>
303 NoOperatorNames("fno-operator-names",
304                 llvm::cl::desc("Do not treat C++ operator name keywords as "
305                                "synonyms for operators"));
306
307 static llvm::cl::opt<bool>
308 PascalStrings("fpascal-strings",
309               llvm::cl::desc("Recognize and construct Pascal-style "
310                              "string literals"));
311
312 static llvm::cl::opt<bool>
313 WritableStrings("fwritable-strings",
314               llvm::cl::desc("Store string literals as writable data."));
315
316 static llvm::cl::opt<bool>
317 LaxVectorConversions("flax-vector-conversions",
318                      llvm::cl::desc("Allow implicit conversions between vectors"
319                                     " with a different number of elements or "
320                                     "different element types."));
321 // FIXME: add:
322 //   -ansi
323 //   -trigraphs
324 //   -fdollars-in-identifiers
325 //   -fpascal-strings
326 static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
327   if (LangStd == lang_unspecified) {
328     // Based on the base language, pick one.
329     switch (LK) {
330     default: assert(0 && "Unknown base language");
331     case langkind_c:
332     case langkind_c_cpp:
333     case langkind_objc:
334     case langkind_objc_cpp:
335       LangStd = lang_gnu99;
336       break;
337     case langkind_cxx:
338     case langkind_cxx_cpp:
339     case langkind_objcxx:
340     case langkind_objcxx_cpp:
341       LangStd = lang_gnucxx98;
342       break;
343     }
344   }
345   
346   switch (LangStd) {
347   default: assert(0 && "Unknown language standard!");
348
349   // Fall through from newer standards to older ones.  This isn't really right.
350   // FIXME: Enable specifically the right features based on the language stds.
351   case lang_gnucxx0x:
352   case lang_cxx0x:
353     Options.CPlusPlus0x = 1;
354     // FALL THROUGH
355   case lang_gnucxx98:
356   case lang_cxx98:
357     Options.CPlusPlus = 1;
358     Options.CXXOperatorNames = !NoOperatorNames;
359     Options.Boolean = 1;
360     // FALL THROUGH.
361   case lang_gnu99:
362   case lang_c99:
363     Options.Digraphs = 1;
364     Options.C99 = 1;
365     Options.HexFloats = 1;
366     // FALL THROUGH.
367   case lang_gnu89:
368     Options.BCPLComment = 1;  // Only for C99/C++.
369     // FALL THROUGH.
370   case lang_c94:
371   case lang_c89:
372     break;
373   }
374   
375   Options.Trigraphs = 1; // -trigraphs or -ansi
376   Options.DollarIdents = 1;  // FIXME: Really a target property.
377   Options.PascalStrings = PascalStrings;
378   Options.WritableStrings = WritableStrings;
379   Options.LaxVectorConversions = LaxVectorConversions;
380 }
381
382 //===----------------------------------------------------------------------===//
383 // Our DiagnosticClient implementation
384 //===----------------------------------------------------------------------===//
385
386 // FIXME: Werror should take a list of things, -Werror=foo,bar
387 static llvm::cl::opt<bool>
388 WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
389
390 static llvm::cl::opt<bool>
391 WarnOnExtensions("pedantic", llvm::cl::init(false),
392                  llvm::cl::desc("Issue a warning on uses of GCC extensions"));
393
394 static llvm::cl::opt<bool>
395 ErrorOnExtensions("pedantic-errors",
396                   llvm::cl::desc("Issue an error on uses of GCC extensions"));
397
398 static llvm::cl::opt<bool>
399 WarnUnusedMacros("Wunused_macros",
400          llvm::cl::desc("Warn for unused macros in the main translation unit"));
401
402 static llvm::cl::opt<bool>
403 WarnFloatEqual("Wfloat-equal",
404    llvm::cl::desc("Warn about equality comparisons of floating point values."));
405
406 static llvm::cl::opt<bool>
407 WarnNoFormatNonLiteral("Wno-format-nonliteral",
408    llvm::cl::desc("Do not warn about non-literal format strings."));
409
410 static llvm::cl::opt<bool>
411 WarnUndefMacros("Wundef",
412    llvm::cl::desc("Warn on use of undefined macros in #if's"));
413
414
415 /// InitializeDiagnostics - Initialize the diagnostic object, based on the
416 /// current command line option settings.
417 static void InitializeDiagnostics(Diagnostic &Diags) {
418   Diags.setWarningsAsErrors(WarningsAsErrors);
419   Diags.setWarnOnExtensions(WarnOnExtensions);
420   Diags.setErrorOnExtensions(ErrorOnExtensions);
421
422   // Silence the "macro is not used" warning unless requested.
423   if (!WarnUnusedMacros)
424     Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
425                
426   // Silence "floating point comparison" warnings unless requested.
427   if (!WarnFloatEqual)
428     Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
429
430   // Silence "format string is not a string literal" warnings if requested
431   if (WarnNoFormatNonLiteral)
432     Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
433                                diag::MAP_IGNORE);
434   if (!WarnUndefMacros)
435     Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
436 }
437
438 //===----------------------------------------------------------------------===//
439 // Target Triple Processing.
440 //===----------------------------------------------------------------------===//
441
442 static llvm::cl::opt<std::string>
443 TargetTriple("triple",
444   llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
445
446 static llvm::cl::list<std::string>
447 Archs("arch",
448   llvm::cl::desc("Specify target architecture (e.g. i686)."));
449
450 namespace {
451   class TripleProcessor {
452     llvm::StringMap<char> TriplesProcessed;
453     std::vector<std::string>& triples;
454   public:
455     TripleProcessor(std::vector<std::string>& t) :  triples(t) {}
456     
457     void addTriple(const std::string& t) {
458       if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
459           TriplesProcessed.end()) {
460         triples.push_back(t);
461         TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
462       }
463     }
464   };
465 }
466
467 static void CreateTargetTriples(std::vector<std::string>& triples) {
468   // Initialize base triple.  If a -triple option has been specified, use
469   // that triple.  Otherwise, default to the host triple.
470   std::string Triple = TargetTriple;
471   if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
472   
473   // Decompose the base triple into "arch" and suffix.
474   std::string::size_type firstDash = Triple.find("-");
475   
476   if (firstDash == std::string::npos) {
477     fprintf(stderr, 
478             "Malformed target triple: \"%s\" ('-' could not be found).\n",
479             Triple.c_str());
480     exit(1);
481   }
482   
483   std::string suffix(Triple, firstDash+1);
484   
485   if (suffix.empty()) {
486     fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
487             Triple.c_str());
488     exit(1);
489   }
490
491   // Create triple cacher.
492   TripleProcessor tp(triples);
493
494   // Add the primary triple to our set of triples if we are using the
495   // host-triple with no archs or using a specified target triple.
496   if (!TargetTriple.getValue().empty() || Archs.empty())
497     tp.addTriple(Triple);
498            
499   for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
500     tp.addTriple(Archs[i] + "-" + suffix);
501 }
502
503 //===----------------------------------------------------------------------===//
504 // Preprocessor Initialization
505 //===----------------------------------------------------------------------===//
506
507 // FIXME: Preprocessor builtins to support.
508 //   -A...    - Play with #assertions
509 //   -undef   - Undefine all predefined macros
510
511 static llvm::cl::list<std::string>
512 D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
513        llvm::cl::desc("Predefine the specified macro"));
514 static llvm::cl::list<std::string>
515 U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
516          llvm::cl::desc("Undefine the specified macro"));
517
518 static llvm::cl::list<std::string>
519 ImplicitIncludes("include", llvm::cl::value_desc("file"),
520                  llvm::cl::desc("Include file before parsing"));
521
522
523 // Append a #define line to Buf for Macro.  Macro should be of the form XXX,
524 // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
525 // "#define XXX Y z W".  To get a #define with no value, use "XXX=".
526 static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
527                                const char *Command = "#define ") {
528   Buf.insert(Buf.end(), Command, Command+strlen(Command));
529   if (const char *Equal = strchr(Macro, '=')) {
530     // Turn the = into ' '.
531     Buf.insert(Buf.end(), Macro, Equal);
532     Buf.push_back(' ');
533     Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
534   } else {
535     // Push "macroname 1".
536     Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
537     Buf.push_back(' ');
538     Buf.push_back('1');
539   }
540   Buf.push_back('\n');
541 }
542
543 /// AddImplicitInclude - Add an implicit #include of the specified file to the
544 /// predefines buffer.
545 static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
546   const char *Inc = "#include \"";
547   Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
548   Buf.insert(Buf.end(), File.begin(), File.end());
549   Buf.push_back('"');
550   Buf.push_back('\n');
551 }
552
553
554 /// InitializePreprocessor - Initialize the preprocessor getting it and the
555 /// environment ready to process a single file. This returns the file ID for the
556 /// input file. If a failure happens, it returns 0.
557 ///
558 static unsigned InitializePreprocessor(Preprocessor &PP,
559                                        const std::string &InFile,
560                                        std::vector<char> &PredefineBuffer) {
561   
562   FileManager &FileMgr = PP.getFileManager();
563   
564   // Figure out where to get and map in the main file.
565   SourceManager &SourceMgr = PP.getSourceManager();
566   if (InFile != "-") {
567     const FileEntry *File = FileMgr.getFile(InFile);
568     if (File) SourceMgr.createMainFileID(File, SourceLocation());
569     if (SourceMgr.getMainFileID() == 0) {
570       fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
571       return 0;
572     }
573   } else {
574     llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
575     if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
576     if (SourceMgr.getMainFileID() == 0) {
577       fprintf(stderr, "Error reading standard input!  Empty?\n");
578       return 0;
579     }
580   }
581   
582   // Add macros from the command line.
583   // FIXME: Should traverse the #define/#undef lists in parallel.
584   for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
585     DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
586   for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
587     DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
588   
589   // FIXME: Read any files specified by -imacros.
590   
591   // Add implicit #includes from -include.
592   for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
593     AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
594   
595   // Null terminate PredefinedBuffer and add it.
596   PredefineBuffer.push_back(0);
597   PP.setPredefines(&PredefineBuffer[0]);
598   
599   // Once we've read this, we're done.
600   return SourceMgr.getMainFileID();
601 }
602
603 //===----------------------------------------------------------------------===//
604 // Preprocessor include path information.
605 //===----------------------------------------------------------------------===//
606
607 // This tool exports a large number of command line options to control how the
608 // preprocessor searches for header files.  At root, however, the Preprocessor
609 // object takes a very simple interface: a list of directories to search for
610 // 
611 // FIXME: -nostdinc,-nostdinc++
612 // FIXME: -imultilib
613 //
614 // FIXME: -imacros
615
616 static llvm::cl::opt<bool>
617 nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
618
619 // Various command line options.  These four add directories to each chain.
620 static llvm::cl::list<std::string>
621 F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
622        llvm::cl::desc("Add directory to framework include search path"));
623 static llvm::cl::list<std::string>
624 I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
625        llvm::cl::desc("Add directory to include search path"));
626 static llvm::cl::list<std::string>
627 idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
628                llvm::cl::desc("Add directory to AFTER include search path"));
629 static llvm::cl::list<std::string>
630 iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
631                llvm::cl::desc("Add directory to QUOTE include search path"));
632 static llvm::cl::list<std::string>
633 isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
634             llvm::cl::desc("Add directory to SYSTEM include search path"));
635
636 // These handle -iprefix/-iwithprefix/-iwithprefixbefore.
637 static llvm::cl::list<std::string>
638 iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
639              llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
640 static llvm::cl::list<std::string>
641 iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
642      llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
643 static llvm::cl::list<std::string>
644 iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
645                        llvm::cl::Prefix,
646             llvm::cl::desc("Set directory to include search path with prefix"));
647
648 static llvm::cl::opt<std::string>
649 isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
650          llvm::cl::desc("Set the system root directory (usually /)"));
651
652 // Finally, implement the code that groks the options above.
653 enum IncludeDirGroup {
654   Quoted = 0,
655   Angled,
656   System,
657   After
658 };
659
660 static std::vector<DirectoryLookup> IncludeGroup[4];
661
662 /// AddPath - Add the specified path to the specified group list.
663 ///
664 static void AddPath(const std::string &Path, IncludeDirGroup Group,
665                     bool isCXXAware, bool isUserSupplied,
666                     bool isFramework, HeaderSearch &HS) {
667   assert(!Path.empty() && "can't handle empty path here");
668   FileManager &FM = HS.getFileMgr();
669   
670   // Compute the actual path, taking into consideration -isysroot.
671   llvm::SmallString<256> MappedPath;
672   
673   // Handle isysroot.
674   if (Group == System) {
675     // FIXME: Portability.  This should be a sys::Path interface, this doesn't
676     // handle things like C:\ right, nor win32 \\network\device\blah.
677     if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
678       MappedPath.append(isysroot.begin(), isysroot.end());
679     if (Path[0] != '/')  // If in the system group, add a /.
680       MappedPath.push_back('/');
681   }
682   
683   MappedPath.append(Path.begin(), Path.end());
684
685   // Compute the DirectoryLookup type.
686   DirectoryLookup::DirType Type;
687   if (Group == Quoted || Group == Angled)
688     Type = DirectoryLookup::NormalHeaderDir;
689   else if (isCXXAware)
690     Type = DirectoryLookup::SystemHeaderDir;
691   else
692     Type = DirectoryLookup::ExternCSystemHeaderDir;
693   
694   
695   // If the directory exists, add it.
696   if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0], 
697                                                  &MappedPath[0]+
698                                                  MappedPath.size())) {
699     IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
700                                                   isFramework));
701     return;
702   }
703   
704   // Check to see if this is an apple-style headermap (which are not allowed to
705   // be frameworks).
706   if (!isFramework) {
707     if (const FileEntry *FE = FM.getFile(&MappedPath[0], 
708                                          &MappedPath[0]+MappedPath.size())) {
709       if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
710         // It is a headermap, add it to the search path.
711         IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
712         return;
713       }
714     }
715   }
716   
717   if (Verbose)
718     fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
719 }
720
721 /// RemoveDuplicates - If there are duplicate directory entries in the specified
722 /// search list, remove the later (dead) ones.
723 static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
724   llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
725   llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
726   llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
727   for (unsigned i = 0; i != SearchList.size(); ++i) {
728     if (SearchList[i].isNormalDir()) {
729       // If this isn't the first time we've seen this dir, remove it.
730       if (SeenDirs.insert(SearchList[i].getDir()))
731         continue;
732       
733       if (Verbose)
734         fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
735                 SearchList[i].getDir()->getName());
736     } else if (SearchList[i].isFramework()) {
737       // If this isn't the first time we've seen this framework dir, remove it.
738       if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
739         continue;
740       
741       if (Verbose)
742         fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
743                 SearchList[i].getFrameworkDir()->getName());
744       
745     } else {
746       assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
747       // If this isn't the first time we've seen this headermap, remove it.
748       if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
749         continue;
750       
751       if (Verbose)
752         fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
753                 SearchList[i].getDir()->getName());
754     }
755     
756     // This is reached if the current entry is a duplicate.
757     SearchList.erase(SearchList.begin()+i);
758     --i;
759   }
760 }
761
762 /// InitializeIncludePaths - Process the -I options and set them in the
763 /// HeaderSearch object.
764 static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
765                                    const LangOptions &Lang) {
766   // Handle -F... options.
767   for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
768     AddPath(F_dirs[i], Angled, false, true, true, Headers);
769   
770   // Handle -I... options.
771   for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
772     AddPath(I_dirs[i], Angled, false, true, false, Headers);
773   
774   // Handle -idirafter... options.
775   for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
776     AddPath(idirafter_dirs[i], After, false, true, false, Headers);
777   
778   // Handle -iquote... options.
779   for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
780     AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
781   
782   // Handle -isystem... options.
783   for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
784     AddPath(isystem_dirs[i], System, false, true, false, Headers);
785
786   // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
787   // parallel, processing the values in order of occurance to get the right
788   // prefixes.
789   {
790     std::string Prefix = "";  // FIXME: this isn't the correct default prefix.
791     unsigned iprefix_idx = 0;
792     unsigned iwithprefix_idx = 0;
793     unsigned iwithprefixbefore_idx = 0;
794     bool iprefix_done           = iprefix_vals.empty();
795     bool iwithprefix_done       = iwithprefix_vals.empty();
796     bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
797     while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
798       if (!iprefix_done &&
799           (iwithprefix_done || 
800            iprefix_vals.getPosition(iprefix_idx) < 
801            iwithprefix_vals.getPosition(iwithprefix_idx)) &&
802           (iwithprefixbefore_done || 
803            iprefix_vals.getPosition(iprefix_idx) < 
804            iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
805         Prefix = iprefix_vals[iprefix_idx];
806         ++iprefix_idx;
807         iprefix_done = iprefix_idx == iprefix_vals.size();
808       } else if (!iwithprefix_done &&
809                  (iwithprefixbefore_done || 
810                   iwithprefix_vals.getPosition(iwithprefix_idx) < 
811                   iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
812         AddPath(Prefix+iwithprefix_vals[iwithprefix_idx], 
813                 System, false, false, false, Headers);
814         ++iwithprefix_idx;
815         iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
816       } else {
817         AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx], 
818                 Angled, false, false, false, Headers);
819         ++iwithprefixbefore_idx;
820         iwithprefixbefore_done = 
821           iwithprefixbefore_idx == iwithprefixbefore_vals.size();
822       }
823     }
824   }
825   
826   // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
827   // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
828   
829   // FIXME: temporary hack: hard-coded paths.
830   // FIXME: get these from the target?
831   if (!nostdinc) {
832     if (Lang.CPlusPlus) {
833       AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
834       AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
835               false, Headers);
836       AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
837               Headers);
838     }
839     
840     AddPath("/usr/local/include", System, false, false, false, Headers);
841     // leopard
842     AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System, 
843             false, false, false, Headers);
844     AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include", 
845             System, false, false, false, Headers);
846     AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
847             "4.0.1/../../../../powerpc-apple-darwin0/include", 
848             System, false, false, false, Headers);
849
850     // tiger
851     AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System, 
852             false, false, false, Headers);
853     AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include", 
854             System, false, false, false, Headers);
855     AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
856             "4.0.1/../../../../powerpc-apple-darwin8/include", 
857             System, false, false, false, Headers);
858
859     // Ubuntu 7.10 - Gutsy Gibbon
860     AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
861             false, false, false, Headers);
862
863     AddPath("/usr/include", System, false, false, false, Headers);
864     AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
865     AddPath("/Library/Frameworks", System, true, false, true, Headers);
866   }
867
868   // Now that we have collected all of the include paths, merge them all
869   // together and tell the preprocessor about them.
870   
871   // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
872   std::vector<DirectoryLookup> SearchList;
873   SearchList = IncludeGroup[Angled];
874   SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
875                     IncludeGroup[System].end());
876   SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
877                     IncludeGroup[After].end());
878   RemoveDuplicates(SearchList);
879   RemoveDuplicates(IncludeGroup[Quoted]);
880   
881   // Prepend QUOTED list on the search list.
882   SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(), 
883                     IncludeGroup[Quoted].end());
884   
885
886   bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
887   Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
888                          DontSearchCurDir);
889
890   // If verbose, print the list of directories that will be searched.
891   if (Verbose) {
892     fprintf(stderr, "#include \"...\" search starts here:\n");
893     unsigned QuotedIdx = IncludeGroup[Quoted].size();
894     for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
895       if (i == QuotedIdx)
896         fprintf(stderr, "#include <...> search starts here:\n");
897       const char *Name = SearchList[i].getName();
898       const char *Suffix;
899       if (SearchList[i].isNormalDir())
900         Suffix = "";
901       else if (SearchList[i].isFramework())
902         Suffix = " (framework directory)";
903       else {
904         assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
905         Suffix = " (headermap)";
906       }
907       fprintf(stderr, " %s%s\n", Name, Suffix);
908     }
909     fprintf(stderr, "End of search list.\n");
910   }
911 }
912
913
914 //===----------------------------------------------------------------------===//
915 // Basic Parser driver
916 //===----------------------------------------------------------------------===//
917
918 static void ParseFile(Preprocessor &PP, MinimalAction *PA){
919   Parser P(PP, *PA);
920   PP.EnterMainSourceFile();
921   
922   // Parsing the specified input file.
923   P.ParseTranslationUnit();
924   delete PA;
925 }
926
927 //===----------------------------------------------------------------------===//
928 // Main driver
929 //===----------------------------------------------------------------------===//
930
931 /// CreateASTConsumer - Create the ASTConsumer for the corresponding program
932 ///  action.  These consumers can operate on both ASTs that are freshly
933 ///  parsed from source files as well as those deserialized from Bitcode.
934 static ASTConsumer* CreateASTConsumer(const std::string& InFile,
935                                       Diagnostic& Diag, FileManager& FileMgr, 
936                                       const LangOptions& LangOpts,
937                                       llvm::Module *&DestModule) {
938   switch (ProgAction) {
939     default:
940       return NULL;
941       
942     case ASTPrint:
943       return CreateASTPrinter();
944       
945     case ASTDump:
946       return CreateASTDumper();
947       
948     case ASTView:
949       return CreateASTViewer();      
950       
951     case ParseCFGDump:
952     case ParseCFGView:
953       return CreateCFGDumper(ProgAction == ParseCFGView);
954       
955     case AnalysisLiveVariables:
956       return CreateLiveVarAnalyzer();
957       
958     case WarnDeadStores:    
959       return CreateDeadStoreChecker(Diag);
960       
961     case WarnUninitVals:
962       return CreateUnitValsChecker(Diag);
963       
964     case AnalysisGRConstants:
965       return CreateGRConstants();
966       
967     case TestSerialization:
968       return CreateSerializationTest(Diag, FileMgr, LangOpts);
969       
970     case EmitLLVM:
971     case EmitBC:
972       DestModule = new llvm::Module(InFile);
973       return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
974
975     case SerializeAST:
976       // FIXME: Allow user to tailor where the file is written.
977       return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
978       
979     case RewriteTest:
980       return CreateCodeRewriterTest(InFile, Diag);
981   }
982 }
983
984 /// ProcessInputFile - Process a single input file with the specified state.
985 ///
986 static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
987                              TextDiagnostics &OurDiagnosticClient) {
988
989   ASTConsumer* Consumer = NULL;
990   bool ClearSourceMgr = false;
991   llvm::Module *CodeGenModule = 0;
992   
993   switch (ProgAction) {
994   default:
995     Consumer = CreateASTConsumer(InFile,
996                                  PP.getDiagnostics(),
997                                  PP.getFileManager(),
998                                  PP.getLangOptions(),
999                                  CodeGenModule);
1000     
1001     if (!Consumer) {      
1002       fprintf(stderr, "Unexpected program action!\n");
1003       return;
1004     }
1005
1006     break;
1007       
1008   case DumpTokens: {                 // Token dump mode.
1009     Token Tok;
1010     // Start parsing the specified input file.
1011     PP.EnterMainSourceFile();
1012     do {
1013       PP.Lex(Tok);
1014       PP.DumpToken(Tok, true);
1015       fprintf(stderr, "\n");
1016     } while (Tok.isNot(tok::eof));
1017     ClearSourceMgr = true;
1018     break;
1019   }
1020   case RunPreprocessorOnly: {        // Just lex as fast as we can, no output.
1021     Token Tok;
1022     // Start parsing the specified input file.
1023     PP.EnterMainSourceFile();
1024     do {
1025       PP.Lex(Tok);
1026     } while (Tok.isNot(tok::eof));
1027     ClearSourceMgr = true;
1028     break;
1029   }
1030     
1031   case PrintPreprocessedInput:       // -E mode.
1032     DoPrintPreprocessedInput(PP, OutputFile);
1033     ClearSourceMgr = true;
1034     break;
1035     
1036   case ParseNoop:                    // -parse-noop
1037     ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
1038     ClearSourceMgr = true;
1039     break;
1040     
1041   case ParsePrintCallbacks:
1042     ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
1043     ClearSourceMgr = true;
1044     break;
1045       
1046   case ParseSyntaxOnly:              // -fsyntax-only
1047     Consumer = new ASTConsumer();
1048     break;
1049   }
1050   
1051   if (Consumer) {
1052     if (VerifyDiagnostics)
1053       exit(CheckASTConsumer(PP, Consumer));
1054     
1055     // This deletes Consumer.
1056     ParseAST(PP, Consumer, Stats);
1057   }
1058
1059   // If running the code generator, finish up now.
1060   if (CodeGenModule) {
1061     std::ostream *Out;
1062     if (OutputFile == "-") {
1063       Out = llvm::cout.stream();
1064     } else if (!OutputFile.empty()) {
1065       Out = new std::ofstream(OutputFile.c_str(), 
1066                               std::ios_base::binary|std::ios_base::out);
1067     } else if (InFile == "-") {
1068       Out = llvm::cout.stream();
1069     } else {
1070       llvm::sys::Path Path(InFile);
1071       Path.eraseSuffix();
1072       if (ProgAction == EmitLLVM)
1073         Path.appendSuffix("ll");
1074       else if (ProgAction == EmitBC)
1075         Path.appendSuffix("bc");
1076       else
1077         assert(0 && "Unknown action");
1078       Out = new std::ofstream(Path.toString().c_str(), 
1079                               std::ios_base::binary|std::ios_base::out);
1080     }
1081     
1082     if (ProgAction == EmitLLVM) {
1083       CodeGenModule->print(*Out);
1084     } else {
1085       assert(ProgAction == EmitBC);
1086       llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1087     }
1088     
1089     if (Out != llvm::cout.stream())
1090       delete Out;
1091     delete CodeGenModule;
1092   }
1093   
1094   if (Stats) {
1095     fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
1096     PP.PrintStats();
1097     PP.getIdentifierTable().PrintStats();
1098     PP.getHeaderSearchInfo().PrintStats();
1099     if (ClearSourceMgr)
1100       PP.getSourceManager().PrintStats();
1101     fprintf(stderr, "\n");
1102   }
1103
1104   // For a multi-file compilation, some things are ok with nuking the source 
1105   // manager tables, other require stable fileid/macroid's across multiple
1106   // files.
1107   if (ClearSourceMgr)
1108     PP.getSourceManager().clearIDTables();
1109 }
1110
1111 static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1112                                   FileManager& FileMgr) {
1113   
1114   if (VerifyDiagnostics) {
1115     fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1116     exit (1);
1117   }
1118   
1119   llvm::sys::Path Filename(InFile);
1120   
1121   if (!Filename.isValid()) {
1122     fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1123     exit (1);
1124   }
1125   
1126   llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
1127   
1128   if (!TU) {
1129     fprintf(stderr, "error: file '%s' could not be deserialized\n", 
1130             InFile.c_str());
1131     exit (1);
1132   }
1133   
1134   // Observe that we use the source file name stored in the deserialized
1135   // translation unit, rather than InFile.
1136   llvm::Module *DestModule;
1137   llvm::OwningPtr<ASTConsumer>
1138     Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1139                                DestModule));
1140   
1141   if (!Consumer) {      
1142     fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1143     exit (1);
1144   }
1145   
1146   Consumer->Initialize(*TU->getContext());
1147   
1148   // FIXME: We need to inform Consumer about completed TagDecls as well.
1149   for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1150     Consumer->HandleTopLevelDecl(*I);
1151 }
1152
1153
1154 static llvm::cl::list<std::string>
1155 InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1156
1157 static bool isSerializedFile(const std::string& InFile) {
1158   if (InFile.size() < 4)
1159     return false;
1160   
1161   const char* s = InFile.c_str()+InFile.size()-4;
1162   
1163   return s[0] == '.' &&
1164          s[1] == 'a' &&
1165          s[2] == 's' &&
1166          s[3] == 't';    
1167 }
1168
1169
1170 int main(int argc, char **argv) {
1171   llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1172   llvm::sys::PrintStackTraceOnErrorSignal();
1173   
1174   // If no input was specified, read from stdin.
1175   if (InputFilenames.empty())
1176     InputFilenames.push_back("-");
1177     
1178   // Create a file manager object to provide access to and cache the filesystem.
1179   FileManager FileMgr;
1180   
1181   // Create the diagnostic client for reporting errors or for
1182   // implementing -verify.
1183   std::auto_ptr<TextDiagnostics> DiagClient;
1184   if (!VerifyDiagnostics) {
1185     // Print diagnostics to stderr by default.
1186     DiagClient.reset(new TextDiagnosticPrinter());
1187   } else {
1188     // When checking diagnostics, just buffer them up.
1189     DiagClient.reset(new TextDiagnosticBuffer());
1190    
1191     if (InputFilenames.size() != 1) {
1192       fprintf(stderr,
1193               "-verify only works on single input files for now.\n");
1194       return 1;
1195     }
1196   }
1197   
1198   // Configure our handling of diagnostics.
1199   Diagnostic Diags(*DiagClient);
1200   InitializeDiagnostics(Diags);  
1201
1202   // -I- is a deprecated GCC feature, scan for it and reject it.
1203   for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1204     if (I_dirs[i] == "-") {
1205       Diags.Report(diag::err_pp_I_dash_not_supported);      
1206       I_dirs.erase(I_dirs.begin()+i);
1207       --i;
1208     }
1209   }
1210   
1211   for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
1212     const std::string &InFile = InputFilenames[i];
1213     
1214     if (isSerializedFile(InFile))
1215       ProcessSerializedFile(InFile,Diags,FileMgr);
1216     else {            
1217       /// Create a SourceManager object.  This tracks and owns all the file
1218       /// buffers allocated to a translation unit.
1219       SourceManager SourceMgr;
1220       
1221       // Initialize language options, inferring file types from input filenames.
1222       LangOptions LangInfo;
1223       InitializeBaseLanguage();
1224       LangKind LK = GetLanguage(InFile);
1225       InitializeLangOptions(LangInfo, LK);
1226       InitializeLanguageStandard(LangInfo, LK);
1227       
1228       // Process the -I options and set them in the HeaderInfo.
1229       HeaderSearch HeaderInfo(FileMgr);
1230       DiagClient->setHeaderSearch(HeaderInfo);
1231       InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1232       
1233       // Get information about the targets being compiled for.  Note that this
1234       // pointer and the TargetInfoImpl objects are never deleted by this toy
1235       // driver.
1236       TargetInfo *Target;
1237       
1238       // Create triples, and create the TargetInfo.
1239       std::vector<std::string> triples;
1240       CreateTargetTriples(triples);
1241       Target = TargetInfo::CreateTargetInfo(&triples[0],
1242                                             &triples[0]+triples.size(),
1243                                             &Diags);
1244         
1245       if (Target == 0) {
1246         fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1247                 triples[0].c_str());
1248         fprintf(stderr, "Please use -triple or -arch.\n");
1249         exit(1);
1250       }
1251       
1252       // Set up the preprocessor with these options.
1253       Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1254       
1255       std::vector<char> PredefineBuffer;
1256       if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
1257         continue;
1258       
1259       ProcessInputFile(PP, InFile, *DiagClient);      
1260       HeaderInfo.ClearFileInfo();
1261       
1262       if (Stats)
1263         SourceMgr.PrintStats();
1264     }
1265   }
1266   
1267   unsigned NumDiagnostics = Diags.getNumDiagnostics();
1268   
1269   if (NumDiagnostics)
1270     fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1271             (NumDiagnostics == 1 ? "" : "s"));
1272   
1273   if (Stats) {
1274     FileMgr.PrintStats();
1275     fprintf(stderr, "\n");
1276   }
1277   
1278   return Diags.getNumErrors() != 0;
1279 }