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