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