blob: 2ee8a93a30051347c6ca86763d1dad86afbdf9e3 [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"
26#include "ASTStreamers.h"
27#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
29#include "clang/Parse/Parser.h"
30#include "clang/Lex/HeaderSearch.h"
31#include "clang/Basic/FileManager.h"
32#include "clang/Basic/SourceManager.h"
33#include "clang/Basic/TargetInfo.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/System/Signals.h"
37#include <memory>
38using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Global options.
42//===----------------------------------------------------------------------===//
43
44static llvm::cl::opt<bool>
45Verbose("v", llvm::cl::desc("Enable verbose output"));
46static llvm::cl::opt<bool>
47Stats("stats", llvm::cl::desc("Print performance metrics and statistics"));
48
49enum ProgActions {
50 EmitLLVM, // Emit a .ll file.
51 ParseASTPrint, // Parse ASTs and print them.
Chris Lattner95578782007-08-08 22:51:59 +000052 ParseASTDump, // Parse ASTs and dump them.
Chris Lattner4b009652007-07-25 00:24:17 +000053 ParseASTCheck, // Parse ASTs and check diagnostics.
54 ParseAST, // Parse ASTs.
55 ParsePrintCallbacks, // Parse and print each callback.
56 ParseSyntaxOnly, // Parse and perform semantic analysis.
57 ParseNoop, // Parse with noop callbacks.
58 RunPreprocessorOnly, // Just lex, no output.
59 PrintPreprocessedInput, // -E mode.
60 DumpTokens // Token dump mode.
61};
62
63static llvm::cl::opt<ProgActions>
64ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
65 llvm::cl::init(ParseSyntaxOnly),
66 llvm::cl::values(
67 clEnumValN(RunPreprocessorOnly, "Eonly",
68 "Just run preprocessor, no output (for timings)"),
69 clEnumValN(PrintPreprocessedInput, "E",
70 "Run preprocessor, emit preprocessed file"),
71 clEnumValN(DumpTokens, "dumptokens",
72 "Run preprocessor, dump internal rep of tokens"),
73 clEnumValN(ParseNoop, "parse-noop",
74 "Run parser with noop callbacks (for timings)"),
75 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
76 "Run parser and perform semantic analysis"),
77 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
78 "Run parser and print each callback invoked"),
79 clEnumValN(ParseAST, "parse-ast",
80 "Run parser and build ASTs"),
81 clEnumValN(ParseASTPrint, "parse-ast-print",
82 "Run parser, build ASTs, then print ASTs"),
Chris Lattner95578782007-08-08 22:51:59 +000083 clEnumValN(ParseASTDump, "parse-ast-dump",
84 "Run parser, build ASTs, then dump them"),
Chris Lattner4b009652007-07-25 00:24:17 +000085 clEnumValN(ParseASTCheck, "parse-ast-check",
86 "Run parser, build ASTs, then check diagnostics"),
87 clEnumValN(EmitLLVM, "emit-llvm",
88 "Build ASTs then convert to LLVM, emit .ll file"),
89 clEnumValEnd));
90
91//===----------------------------------------------------------------------===//
92// Language Options
93//===----------------------------------------------------------------------===//
94
95enum LangKind {
96 langkind_unspecified,
97 langkind_c,
98 langkind_c_cpp,
99 langkind_cxx,
100 langkind_cxx_cpp,
101 langkind_objc,
102 langkind_objc_cpp,
103 langkind_objcxx,
104 langkind_objcxx_cpp
105};
106
107/* TODO: GCC also accepts:
108 c-header c++-header objective-c-header objective-c++-header
109 assembler assembler-with-cpp
110 ada, f77*, ratfor (!), f95, java, treelang
111 */
112static llvm::cl::opt<LangKind>
113BaseLang("x", llvm::cl::desc("Base language to compile"),
114 llvm::cl::init(langkind_unspecified),
115 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
116 clEnumValN(langkind_cxx, "c++", "C++"),
117 clEnumValN(langkind_objc, "objective-c", "Objective C"),
118 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
119 clEnumValN(langkind_c_cpp, "c-cpp-output",
120 "Preprocessed C"),
121 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
122 "Preprocessed C++"),
123 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
124 "Preprocessed Objective C"),
125 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
126 "Preprocessed Objective C++"),
127 clEnumValEnd));
128
129static llvm::cl::opt<bool>
130LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
131 llvm::cl::Hidden);
132static llvm::cl::opt<bool>
133LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
134 llvm::cl::Hidden);
135
136/// InitializeBaseLanguage - Handle the -x foo options or infer a base language
137/// from the input filename.
138static void InitializeBaseLanguage(LangOptions &Options,
139 const std::string &Filename) {
140 if (BaseLang == langkind_unspecified) {
141 std::string::size_type DotPos = Filename.rfind('.');
142 if (LangObjC) {
143 BaseLang = langkind_objc;
144 } else if (LangObjCXX) {
145 BaseLang = langkind_objcxx;
146 } else if (DotPos == std::string::npos) {
147 BaseLang = langkind_c; // Default to C if no extension.
148 } else {
149 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
150 // C header: .h
151 // C++ header: .hh or .H;
152 // assembler no preprocessing: .s
153 // assembler: .S
154 if (Ext == "c")
155 BaseLang = langkind_c;
156 else if (Ext == "i")
157 BaseLang = langkind_c_cpp;
158 else if (Ext == "ii")
159 BaseLang = langkind_cxx_cpp;
160 else if (Ext == "m")
161 BaseLang = langkind_objc;
162 else if (Ext == "mi")
163 BaseLang = langkind_objc_cpp;
164 else if (Ext == "mm" || Ext == "M")
165 BaseLang = langkind_objcxx;
166 else if (Ext == "mii")
167 BaseLang = langkind_objcxx_cpp;
168 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
169 Ext == "c++" || Ext == "cp" || Ext == "cxx")
170 BaseLang = langkind_cxx;
171 else
172 BaseLang = langkind_c;
173 }
174 }
175
176 // FIXME: implement -fpreprocessed mode.
177 bool NoPreprocess = false;
178
179 switch (BaseLang) {
180 default: assert(0 && "Unknown language kind!");
181 case langkind_c_cpp:
182 NoPreprocess = true;
183 // FALLTHROUGH
184 case langkind_c:
185 break;
186 case langkind_cxx_cpp:
187 NoPreprocess = true;
188 // FALLTHROUGH
189 case langkind_cxx:
190 Options.CPlusPlus = 1;
191 break;
192 case langkind_objc_cpp:
193 NoPreprocess = true;
194 // FALLTHROUGH
195 case langkind_objc:
196 Options.ObjC1 = Options.ObjC2 = 1;
197 break;
198 case langkind_objcxx_cpp:
199 NoPreprocess = true;
200 // FALLTHROUGH
201 case langkind_objcxx:
202 Options.ObjC1 = Options.ObjC2 = 1;
203 Options.CPlusPlus = 1;
204 break;
205 }
206}
207
208/// LangStds - Language standards we support.
209enum LangStds {
210 lang_unspecified,
211 lang_c89, lang_c94, lang_c99,
212 lang_gnu89, lang_gnu99,
213 lang_cxx98, lang_gnucxx98,
214 lang_cxx0x, lang_gnucxx0x
215};
216
217static llvm::cl::opt<LangStds>
218LangStd("std", llvm::cl::desc("Language standard to compile for"),
219 llvm::cl::init(lang_unspecified),
220 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
221 clEnumValN(lang_c89, "c90", "ISO C 1990"),
222 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
223 clEnumValN(lang_c94, "iso9899:199409",
224 "ISO C 1990 with amendment 1"),
225 clEnumValN(lang_c99, "c99", "ISO C 1999"),
226// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
227 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
228// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
229 clEnumValN(lang_gnu89, "gnu89",
230 "ISO C 1990 with GNU extensions (default for C)"),
231 clEnumValN(lang_gnu99, "gnu99",
232 "ISO C 1999 with GNU extensions"),
233 clEnumValN(lang_gnu99, "gnu9x",
234 "ISO C 1999 with GNU extensions"),
235 clEnumValN(lang_cxx98, "c++98",
236 "ISO C++ 1998 with amendments"),
237 clEnumValN(lang_gnucxx98, "gnu++98",
238 "ISO C++ 1998 with amendments and GNU "
239 "extensions (default for C++)"),
240 clEnumValN(lang_cxx0x, "c++0x",
241 "Upcoming ISO C++ 200x with amendments"),
242 clEnumValN(lang_gnucxx0x, "gnu++0x",
243 "Upcoming ISO C++ 200x with amendments and GNU "
244 "extensions (default for C++)"),
245 clEnumValEnd));
246
247static llvm::cl::opt<bool>
248NoOperatorNames("fno-operator-names",
249 llvm::cl::desc("Do not treat C++ operator name keywords as "
250 "synonyms for operators"));
251
252// FIXME: add:
253// -ansi
254// -trigraphs
255// -fdollars-in-identifiers
256static void InitializeLanguageStandard(LangOptions &Options) {
257 if (LangStd == lang_unspecified) {
258 // Based on the base language, pick one.
259 switch (BaseLang) {
260 default: assert(0 && "Unknown base language");
261 case langkind_c:
262 case langkind_c_cpp:
263 case langkind_objc:
264 case langkind_objc_cpp:
265 LangStd = lang_gnu99;
266 break;
267 case langkind_cxx:
268 case langkind_cxx_cpp:
269 case langkind_objcxx:
270 case langkind_objcxx_cpp:
271 LangStd = lang_gnucxx98;
272 break;
273 }
274 }
275
276 switch (LangStd) {
277 default: assert(0 && "Unknown language standard!");
278
279 // Fall through from newer standards to older ones. This isn't really right.
280 // FIXME: Enable specifically the right features based on the language stds.
281 case lang_gnucxx0x:
282 case lang_cxx0x:
283 Options.CPlusPlus0x = 1;
284 // FALL THROUGH
285 case lang_gnucxx98:
286 case lang_cxx98:
287 Options.CPlusPlus = 1;
288 Options.CXXOperatorNames = !NoOperatorNames;
289 // FALL THROUGH.
290 case lang_gnu99:
291 case lang_c99:
292 Options.Digraphs = 1;
293 Options.C99 = 1;
294 Options.HexFloats = 1;
295 // FALL THROUGH.
296 case lang_gnu89:
297 Options.BCPLComment = 1; // Only for C99/C++.
298 // FALL THROUGH.
299 case lang_c94:
300 case lang_c89:
301 break;
302 }
303
304 Options.Trigraphs = 1; // -trigraphs or -ansi
305 Options.DollarIdents = 1; // FIXME: Really a target property.
306}
307
308//===----------------------------------------------------------------------===//
309// Our DiagnosticClient implementation
310//===----------------------------------------------------------------------===//
311
312// FIXME: Werror should take a list of things, -Werror=foo,bar
313static llvm::cl::opt<bool>
314WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
315
316static llvm::cl::opt<bool>
317WarnOnExtensions("pedantic", llvm::cl::init(false),
318 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
319
320static llvm::cl::opt<bool>
321ErrorOnExtensions("pedantic-errors",
322 llvm::cl::desc("Issue an error on uses of GCC extensions"));
323
324static llvm::cl::opt<bool>
325WarnUnusedMacros("Wunused_macros",
326 llvm::cl::desc("Warn for unused macros in the main translation unit"));
327
328
329/// InitializeDiagnostics - Initialize the diagnostic object, based on the
330/// current command line option settings.
331static void InitializeDiagnostics(Diagnostic &Diags) {
332 Diags.setWarningsAsErrors(WarningsAsErrors);
333 Diags.setWarnOnExtensions(WarnOnExtensions);
334 Diags.setErrorOnExtensions(ErrorOnExtensions);
335
336 // Silence the "macro is not used" warning unless requested.
337 if (!WarnUnusedMacros)
338 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
339}
340
341//===----------------------------------------------------------------------===//
342// Preprocessor Initialization
343//===----------------------------------------------------------------------===//
344
345// FIXME: Preprocessor builtins to support.
346// -A... - Play with #assertions
347// -undef - Undefine all predefined macros
348
349static llvm::cl::list<std::string>
350D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
351 llvm::cl::desc("Predefine the specified macro"));
352static llvm::cl::list<std::string>
353U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
354 llvm::cl::desc("Undefine the specified macro"));
355
356// Append a #define line to Buf for Macro. Macro should be of the form XXX,
357// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
358// "#define XXX Y z W". To get a #define with no value, use "XXX=".
359static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
360 const char *Command = "#define ") {
361 Buf.insert(Buf.end(), Command, Command+strlen(Command));
362 if (const char *Equal = strchr(Macro, '=')) {
363 // Turn the = into ' '.
364 Buf.insert(Buf.end(), Macro, Equal);
365 Buf.push_back(' ');
366 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
367 } else {
368 // Push "macroname 1".
369 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
370 Buf.push_back(' ');
371 Buf.push_back('1');
372 }
373 Buf.push_back('\n');
374}
375
376static void InitializePredefinedMacros(Preprocessor &PP,
377 std::vector<char> &Buf) {
378 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
379 // and __DATE__ etc.
380#if 0
381 /* __STDC__ has the value 1 under normal circumstances.
382 However, if (a) we are in a system header, (b) the option
383 stdc_0_in_system_headers is true (set by target config), and
384 (c) we are not in strictly conforming mode, then it has the
385 value 0. (b) and (c) are already checked in cpp_init_builtins. */
386 //case BT_STDC:
387 if (cpp_in_system_header (pfile))
388 number = 0;
389 else
390 number = 1;
391 break;
392#endif
393 // These should all be defined in the preprocessor according to the
394 // current language configuration.
395 DefineBuiltinMacro(Buf, "__STDC__=1");
396 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
397 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
398 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
399 else if (0) // STDC94 ?
400 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
401
402 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
403 if (PP.getLangOptions().ObjC1)
404 DefineBuiltinMacro(Buf, "__OBJC__=1");
405 if (PP.getLangOptions().ObjC2)
406 DefineBuiltinMacro(Buf, "__OBJC2__=1");
407
408 // Get the target #defines.
409 PP.getTargetInfo().getTargetDefines(Buf);
410
411 // Compiler set macros.
412 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
413 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1030");
414 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
415 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
416 DefineBuiltinMacro(Buf, "__GNUC__=4");
417 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
418 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
419 "build 5250)\"");
420
421 // Build configuration options.
422 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
423 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
424 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
425 DefineBuiltinMacro(Buf, "__PIC__=1");
426
427
428 if (PP.getLangOptions().CPlusPlus) {
429 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
430 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
431 DefineBuiltinMacro(Buf, "__GNUG__=4");
432 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
433 DefineBuiltinMacro(Buf, "__cplusplus=1");
434 DefineBuiltinMacro(Buf, "__private_extern__=extern");
435 }
436
437 // FIXME: Should emit a #line directive here.
438
439 // Add macros from the command line.
440 // FIXME: Should traverse the #define/#undef lists in parallel.
441 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
442 DefineBuiltinMacro(Buf, D_macros[i].c_str());
443 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
444 DefineBuiltinMacro(Buf, U_macros[i].c_str(), "#undef ");
445}
446
447//===----------------------------------------------------------------------===//
448// Preprocessor include path information.
449//===----------------------------------------------------------------------===//
450
451// This tool exports a large number of command line options to control how the
452// preprocessor searches for header files. At root, however, the Preprocessor
453// object takes a very simple interface: a list of directories to search for
454//
455// FIXME: -nostdinc,-nostdinc++
456// FIXME: -isysroot,-imultilib
457//
458// FIXME: -include,-imacros
459
460static llvm::cl::opt<bool>
461nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
462
463// Various command line options. These four add directories to each chain.
464static llvm::cl::list<std::string>
465F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
466 llvm::cl::desc("Add directory to framework include search path"));
467static llvm::cl::list<std::string>
468I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
469 llvm::cl::desc("Add directory to include search path"));
470static llvm::cl::list<std::string>
471idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
472 llvm::cl::desc("Add directory to AFTER include search path"));
473static llvm::cl::list<std::string>
474iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
475 llvm::cl::desc("Add directory to QUOTE include search path"));
476static llvm::cl::list<std::string>
477isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
478 llvm::cl::desc("Add directory to SYSTEM include search path"));
479
480// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
481static llvm::cl::list<std::string>
482iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
483 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
484static llvm::cl::list<std::string>
485iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
486 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
487static llvm::cl::list<std::string>
488iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
489 llvm::cl::Prefix,
490 llvm::cl::desc("Set directory to include search path with prefix"));
491
492// Finally, implement the code that groks the options above.
493enum IncludeDirGroup {
494 Quoted = 0,
495 Angled,
496 System,
497 After
498};
499
500static std::vector<DirectoryLookup> IncludeGroup[4];
501
502/// AddPath - Add the specified path to the specified group list.
503///
504static void AddPath(const std::string &Path, IncludeDirGroup Group,
505 bool isCXXAware, bool isUserSupplied,
506 bool isFramework, FileManager &FM) {
507 const DirectoryEntry *DE = FM.getDirectory(Path);
508 if (DE == 0) {
509 if (Verbose)
510 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
511 Path.c_str());
512 return;
513 }
514
515 DirectoryLookup::DirType Type;
516 if (Group == Quoted || Group == Angled)
517 Type = DirectoryLookup::NormalHeaderDir;
518 else if (isCXXAware)
519 Type = DirectoryLookup::SystemHeaderDir;
520 else
521 Type = DirectoryLookup::ExternCSystemHeaderDir;
522
523 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
524 isFramework));
525}
526
527/// RemoveDuplicates - If there are duplicate directory entries in the specified
528/// search list, remove the later (dead) ones.
529static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
530 std::set<const DirectoryEntry *> SeenDirs;
531 for (unsigned i = 0; i != SearchList.size(); ++i) {
532 // If this isn't the first time we've seen this dir, remove it.
533 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
534 if (Verbose)
535 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
536 SearchList[i].getDir()->getName());
537 SearchList.erase(SearchList.begin()+i);
538 --i;
539 }
540 }
541}
542
543/// InitializeIncludePaths - Process the -I options and set them in the
544/// HeaderSearch object.
545static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
546 Diagnostic &Diags, const LangOptions &Lang) {
547 // Handle -F... options.
548 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
549 AddPath(F_dirs[i], Angled, false, true, true, FM);
550
551 // Handle -I... options.
552 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
553 if (I_dirs[i] == "-") {
554 // -I- is a deprecated GCC feature.
555 Diags.Report(SourceLocation(), diag::err_pp_I_dash_not_supported);
556 } else {
557 AddPath(I_dirs[i], Angled, false, true, false, FM);
558 }
559 }
560
561 // Handle -idirafter... options.
562 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
563 AddPath(idirafter_dirs[i], After, false, true, false, FM);
564
565 // Handle -iquote... options.
566 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
567 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
568
569 // Handle -isystem... options.
570 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
571 AddPath(isystem_dirs[i], System, false, true, false, FM);
572
573 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
574 // parallel, processing the values in order of occurance to get the right
575 // prefixes.
576 {
577 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
578 unsigned iprefix_idx = 0;
579 unsigned iwithprefix_idx = 0;
580 unsigned iwithprefixbefore_idx = 0;
581 bool iprefix_done = iprefix_vals.empty();
582 bool iwithprefix_done = iwithprefix_vals.empty();
583 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
584 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
585 if (!iprefix_done &&
586 (iwithprefix_done ||
587 iprefix_vals.getPosition(iprefix_idx) <
588 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
589 (iwithprefixbefore_done ||
590 iprefix_vals.getPosition(iprefix_idx) <
591 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
592 Prefix = iprefix_vals[iprefix_idx];
593 ++iprefix_idx;
594 iprefix_done = iprefix_idx == iprefix_vals.size();
595 } else if (!iwithprefix_done &&
596 (iwithprefixbefore_done ||
597 iwithprefix_vals.getPosition(iwithprefix_idx) <
598 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
599 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
600 System, false, false, false, FM);
601 ++iwithprefix_idx;
602 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
603 } else {
604 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
605 Angled, false, false, false, FM);
606 ++iwithprefixbefore_idx;
607 iwithprefixbefore_done =
608 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
609 }
610 }
611 }
612
613 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
614 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
615
616 // FIXME: temporary hack: hard-coded paths.
617 // FIXME: get these from the target?
618 if (!nostdinc) {
619 if (Lang.CPlusPlus) {
620 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
621 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
622 false, FM);
623 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
624 }
625
626 AddPath("/usr/local/include", System, false, false, false, FM);
627 // leopard
628 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
629 false, false, false, FM);
630 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
631 System, false, false, false, FM);
632 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
633 "4.0.1/../../../../powerpc-apple-darwin0/include",
634 System, false, false, false, FM);
635
636 // tiger
637 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
638 false, false, false, FM);
639 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
640 System, false, false, false, FM);
641 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
642 "4.0.1/../../../../powerpc-apple-darwin8/include",
643 System, false, false, false, FM);
644
645 AddPath("/usr/include", System, false, false, false, FM);
646 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
647 AddPath("/Library/Frameworks", System, true, false, true, FM);
648 }
649
650 // Now that we have collected all of the include paths, merge them all
651 // together and tell the preprocessor about them.
652
653 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
654 std::vector<DirectoryLookup> SearchList;
655 SearchList = IncludeGroup[Angled];
656 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
657 IncludeGroup[System].end());
658 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
659 IncludeGroup[After].end());
660 RemoveDuplicates(SearchList);
661 RemoveDuplicates(IncludeGroup[Quoted]);
662
663 // Prepend QUOTED list on the search list.
664 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
665 IncludeGroup[Quoted].end());
666
667
668 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
669 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
670 DontSearchCurDir);
671
672 // If verbose, print the list of directories that will be searched.
673 if (Verbose) {
674 fprintf(stderr, "#include \"...\" search starts here:\n");
675 unsigned QuotedIdx = IncludeGroup[Quoted].size();
676 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
677 if (i == QuotedIdx)
678 fprintf(stderr, "#include <...> search starts here:\n");
679 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
680 }
681 }
682}
683
684
685// Read any files specified by -imacros or -include.
686static void ReadPrologFiles(Preprocessor &PP, std::vector<char> &Buf) {
687 // FIXME: IMPLEMENT
688}
689
690//===----------------------------------------------------------------------===//
691// Basic Parser driver
692//===----------------------------------------------------------------------===//
693
694static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
695 Parser P(PP, *PA);
696 PP.EnterSourceFile(MainFileID, 0, true);
697
698 // Parsing the specified input file.
699 P.ParseTranslationUnit();
700 delete PA;
701}
702
703//===----------------------------------------------------------------------===//
704// Main driver
705//===----------------------------------------------------------------------===//
706
707/// InitializePreprocessor - Initialize the preprocessor getting it and the
708/// environment ready to process a single file. This returns the file ID for the
709/// input file. If a failure happens, it returns 0.
710///
711static unsigned InitializePreprocessor(Preprocessor &PP,
712 const std::string &InFile,
713 SourceManager &SourceMgr,
714 HeaderSearch &HeaderInfo,
715 const LangOptions &LangInfo,
716 std::vector<char> &PrologMacros) {
717 FileManager &FileMgr = HeaderInfo.getFileMgr();
718
719 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
720 InitializePredefinedMacros(PP, PrologMacros);
721
722 // Read any files specified by -imacros or -include.
723 ReadPrologFiles(PP, PrologMacros);
724
725 // Figure out where to get and map in the main file.
726 unsigned MainFileID = 0;
727 if (InFile != "-") {
728 const FileEntry *File = FileMgr.getFile(InFile);
729 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
730 if (MainFileID == 0) {
731 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
732 return 0;
733 }
734 } else {
735 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
736 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
737 if (MainFileID == 0) {
738 fprintf(stderr, "Error reading standard input! Empty?\n");
739 return 0;
740 }
741 }
742
743 // Now that we have emitted the predefined macros, #includes, etc into
744 // PrologMacros, preprocess it to populate the initial preprocessor state.
745
746 // Memory buffer must end with a null byte!
747 PrologMacros.push_back(0);
748
749 llvm::MemoryBuffer *SB =
750 llvm::MemoryBuffer::getMemBuffer(&PrologMacros.front(),&PrologMacros.back(),
751 "<predefines>");
752 assert(SB && "Cannot fail to create predefined source buffer");
753 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
754 assert(FileID && "Could not create FileID for predefines?");
755
756 // Start parsing the predefines.
757 PP.EnterSourceFile(FileID, 0);
758
759 // Lex the file, which will read all the macros.
760 Token Tok;
761 PP.Lex(Tok);
762 assert(Tok.getKind() == tok::eof && "Didn't read entire file!");
763
764 // Once we've read this, we're done.
765 return MainFileID;
766}
767
768/// ProcessInputFile - Process a single input file with the specified state.
769///
770static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
771 const std::string &InFile,
772 SourceManager &SourceMgr,
773 TextDiagnostics &OurDiagnosticClient,
774 HeaderSearch &HeaderInfo,
775 const LangOptions &LangInfo) {
776 bool ClearSourceMgr = false;
777 switch (ProgAction) {
778 default:
779 fprintf(stderr, "Unexpected program action!\n");
780 return;
781 case DumpTokens: { // Token dump mode.
782 Token Tok;
783 // Start parsing the specified input file.
784 PP.EnterSourceFile(MainFileID, 0, true);
785 do {
786 PP.Lex(Tok);
787 PP.DumpToken(Tok, true);
788 fprintf(stderr, "\n");
789 } while (Tok.getKind() != tok::eof);
790 ClearSourceMgr = true;
791 break;
792 }
793 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
794 Token Tok;
795 // Start parsing the specified input file.
796 PP.EnterSourceFile(MainFileID, 0, true);
797 do {
798 PP.Lex(Tok);
799 } while (Tok.getKind() != tok::eof);
800 ClearSourceMgr = true;
801 break;
802 }
803
804 case PrintPreprocessedInput: // -E mode.
805 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
806 ClearSourceMgr = true;
807 break;
808
809 case ParseNoop: // -parse-noop
810 ParseFile(PP, new MinimalAction(), MainFileID);
811 ClearSourceMgr = true;
812 break;
813
814 case ParsePrintCallbacks:
815 ParseFile(PP, CreatePrintParserActionsAction(), MainFileID);
816 ClearSourceMgr = true;
817 break;
818 case ParseSyntaxOnly: // -fsyntax-only
819 case ParseAST:
820 BuildASTs(PP, MainFileID, Stats);
821 break;
822 case ParseASTPrint:
823 PrintASTs(PP, MainFileID, Stats);
824 break;
Chris Lattner95578782007-08-08 22:51:59 +0000825 case ParseASTDump:
826 DumpASTs(PP, MainFileID, Stats);
827 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000828 case EmitLLVM:
829 EmitLLVMFromASTs(PP, MainFileID, Stats);
830 break;
831 case ParseASTCheck:
832 exit(CheckDiagnostics(PP, MainFileID));
833 break;
834 }
835
836 if (Stats) {
837 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
838 PP.PrintStats();
839 PP.getIdentifierTable().PrintStats();
840 HeaderInfo.PrintStats();
841 if (ClearSourceMgr)
842 SourceMgr.PrintStats();
843 fprintf(stderr, "\n");
844 }
845
846 // For a multi-file compilation, some things are ok with nuking the source
847 // manager tables, other require stable fileid/macroid's across multiple
848 // files.
849 if (ClearSourceMgr) {
850 SourceMgr.clearIDTables();
851 }
852}
853
854static llvm::cl::list<std::string>
855InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
856
857
858int main(int argc, char **argv) {
859 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
860 llvm::sys::PrintStackTraceOnErrorSignal();
861
862 // If no input was specified, read from stdin.
863 if (InputFilenames.empty())
864 InputFilenames.push_back("-");
865
866 /// Create a SourceManager object. This tracks and owns all the file buffers
867 /// allocated to the program.
868 SourceManager SourceMgr;
869
870 // Create a file manager object to provide access to and cache the filesystem.
871 FileManager FileMgr;
872
873 // Initialize language options, inferring file types from input filenames.
874 // FIXME: This infers info from the first file, we should clump by language
875 // to handle 'x.c y.c a.cpp b.cpp'.
876 LangOptions LangInfo;
877 InitializeBaseLanguage(LangInfo, InputFilenames[0]);
878 InitializeLanguageStandard(LangInfo);
879
880 std::auto_ptr<TextDiagnostics> DiagClient;
881 if (ProgAction != ParseASTCheck) {
882 // Print diagnostics to stderr by default.
883 DiagClient.reset(new TextDiagnosticPrinter(SourceMgr));
884 } else {
885 // When checking diagnostics, just buffer them up.
886 DiagClient.reset(new TextDiagnosticBuffer(SourceMgr));
887
888 if (InputFilenames.size() != 1) {
889 fprintf(stderr,
890 "parse-ast-check only works on single input files for now.\n");
891 return 1;
892 }
893 }
894
895 // Configure our handling of diagnostics.
896 Diagnostic Diags(*DiagClient);
897 InitializeDiagnostics(Diags);
898
899 // Get information about the targets being compiled for. Note that this
900 // pointer and the TargetInfoImpl objects are never deleted by this toy
901 // driver.
902 TargetInfo *Target = CreateTargetInfo(Diags);
903 if (Target == 0) {
904 fprintf(stderr,
905 "Sorry, don't know what target this is, please use -arch.\n");
906 exit(1);
907 }
908
909 // Process the -I options and set them in the HeaderInfo.
910 HeaderSearch HeaderInfo(FileMgr);
911 DiagClient->setHeaderSearch(HeaderInfo);
912 InitializeIncludePaths(HeaderInfo, FileMgr, Diags, LangInfo);
913
914 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
915 // Set up the preprocessor with these options.
916 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
917 DiagClient->setPreprocessor(PP);
918 const std::string &InFile = InputFilenames[i];
919 std::vector<char> PrologMacros;
920 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
921 HeaderInfo, LangInfo,
922 PrologMacros);
923
924 if (!MainFileID) continue;
925
926 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
927 *DiagClient, HeaderInfo, LangInfo);
928 HeaderInfo.ClearFileInfo();
929 }
930
931 unsigned NumDiagnostics = Diags.getNumDiagnostics();
932
933 if (NumDiagnostics)
934 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
935 (NumDiagnostics == 1 ? "" : "s"));
936
937 if (Stats) {
938 // Printed from high-to-low level.
939 SourceMgr.PrintStats();
940 FileMgr.PrintStats();
941 fprintf(stderr, "\n");
942 }
943
944 return Diags.getNumErrors() != 0;
945}