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