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