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