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