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