blob: b31cee44d84a75f9b4b0e7c84a59a02b44f0da1f [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 {
Chris Lattner77cd2a02007-10-11 00:43:27 +000052 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000053 EmitLLVM, // Emit a .ll file.
Chris Lattner3b427b32007-10-11 00:18:28 +000054 ASTPrint, // Parse ASTs and print them.
55 ASTDump, // Parse ASTs and dump them.
56 ASTView, // Parse ASTs and view them in Graphviz.
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.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000063 TestSerialization, // Run experimental serialization code.
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 Lattner3b427b32007-10-11 00:18:28 +000088 clEnumValN(ASTPrint, "ast-print",
89 "Build ASTs and then pretty-print them"),
90 clEnumValN(ASTDump, "ast-dump",
91 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +000092 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +000093 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +000094 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +000095 "Run parser, then build and print CFGs."),
96 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +000097 "Run parser, then build and view CFGs with Graphviz."),
98 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +000099 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000100 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000101 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000102 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000103 "Flag warnings of uses of unitialized variables."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000104 clEnumValN(TestSerialization, "test-pickling",
105 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000107 "Build ASTs then convert to LLVM, emit .ll file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000108 clEnumValN(RewriteTest, "rewrite-test",
109 "Playground for the code rewriter"),
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
Anders Carlssonee98ac52007-10-15 02:50:23 +0000277static llvm::cl::opt<bool>
278PascalStrings("fpascal-strings",
279 llvm::cl::desc("Recognize and construct Pascal-style "
280 "string literals"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000281// FIXME: add:
282// -ansi
283// -trigraphs
284// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000285// -fpascal-strings
Reid Spencer5f016e22007-07-11 17:01:13 +0000286static void InitializeLanguageStandard(LangOptions &Options) {
287 if (LangStd == lang_unspecified) {
288 // Based on the base language, pick one.
289 switch (BaseLang) {
290 default: assert(0 && "Unknown base language");
291 case langkind_c:
292 case langkind_c_cpp:
293 case langkind_objc:
294 case langkind_objc_cpp:
295 LangStd = lang_gnu99;
296 break;
297 case langkind_cxx:
298 case langkind_cxx_cpp:
299 case langkind_objcxx:
300 case langkind_objcxx_cpp:
301 LangStd = lang_gnucxx98;
302 break;
303 }
304 }
305
306 switch (LangStd) {
307 default: assert(0 && "Unknown language standard!");
308
309 // Fall through from newer standards to older ones. This isn't really right.
310 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000311 case lang_gnucxx0x:
312 case lang_cxx0x:
313 Options.CPlusPlus0x = 1;
314 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 case lang_gnucxx98:
316 case lang_cxx98:
317 Options.CPlusPlus = 1;
318 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000319 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000320 // FALL THROUGH.
321 case lang_gnu99:
322 case lang_c99:
323 Options.Digraphs = 1;
324 Options.C99 = 1;
325 Options.HexFloats = 1;
326 // FALL THROUGH.
327 case lang_gnu89:
328 Options.BCPLComment = 1; // Only for C99/C++.
329 // FALL THROUGH.
330 case lang_c94:
331 case lang_c89:
332 break;
333 }
334
335 Options.Trigraphs = 1; // -trigraphs or -ansi
336 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000337 Options.PascalStrings = PascalStrings;
Reid Spencer5f016e22007-07-11 17:01:13 +0000338}
339
340//===----------------------------------------------------------------------===//
341// Our DiagnosticClient implementation
342//===----------------------------------------------------------------------===//
343
344// FIXME: Werror should take a list of things, -Werror=foo,bar
345static llvm::cl::opt<bool>
346WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
347
348static llvm::cl::opt<bool>
349WarnOnExtensions("pedantic", llvm::cl::init(false),
350 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
351
352static llvm::cl::opt<bool>
353ErrorOnExtensions("pedantic-errors",
354 llvm::cl::desc("Issue an error on uses of GCC extensions"));
355
356static llvm::cl::opt<bool>
357WarnUnusedMacros("Wunused_macros",
358 llvm::cl::desc("Warn for unused macros in the main translation unit"));
359
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000360static llvm::cl::opt<bool>
361WarnFloatEqual("Wfloat-equal",
362 llvm::cl::desc("Warn about equality comparisons of floating point values."));
363
Reid Spencer5f016e22007-07-11 17:01:13 +0000364/// InitializeDiagnostics - Initialize the diagnostic object, based on the
365/// current command line option settings.
366static void InitializeDiagnostics(Diagnostic &Diags) {
367 Diags.setWarningsAsErrors(WarningsAsErrors);
368 Diags.setWarnOnExtensions(WarnOnExtensions);
369 Diags.setErrorOnExtensions(ErrorOnExtensions);
370
371 // Silence the "macro is not used" warning unless requested.
372 if (!WarnUnusedMacros)
373 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000374
375 // Silence "floating point comparison" warnings unless requested.
376 if (!WarnFloatEqual)
377 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000378}
379
380//===----------------------------------------------------------------------===//
381// Preprocessor Initialization
382//===----------------------------------------------------------------------===//
383
384// FIXME: Preprocessor builtins to support.
385// -A... - Play with #assertions
386// -undef - Undefine all predefined macros
387
388static llvm::cl::list<std::string>
389D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
390 llvm::cl::desc("Predefine the specified macro"));
391static llvm::cl::list<std::string>
392U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
393 llvm::cl::desc("Undefine the specified macro"));
394
395// Append a #define line to Buf for Macro. Macro should be of the form XXX,
396// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
397// "#define XXX Y z W". To get a #define with no value, use "XXX=".
398static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
399 const char *Command = "#define ") {
400 Buf.insert(Buf.end(), Command, Command+strlen(Command));
401 if (const char *Equal = strchr(Macro, '=')) {
402 // Turn the = into ' '.
403 Buf.insert(Buf.end(), Macro, Equal);
404 Buf.push_back(' ');
405 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
406 } else {
407 // Push "macroname 1".
408 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
409 Buf.push_back(' ');
410 Buf.push_back('1');
411 }
412 Buf.push_back('\n');
413}
414
Reid Spencer5f016e22007-07-11 17:01:13 +0000415
Chris Lattner53b0dab2007-10-09 22:10:18 +0000416/// InitializePreprocessor - Initialize the preprocessor getting it and the
417/// environment ready to process a single file. This returns the file ID for the
418/// input file. If a failure happens, it returns 0.
419///
420static unsigned InitializePreprocessor(Preprocessor &PP,
421 const std::string &InFile,
422 SourceManager &SourceMgr,
423 HeaderSearch &HeaderInfo,
424 const LangOptions &LangInfo,
425 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000426
Chris Lattner53b0dab2007-10-09 22:10:18 +0000427 FileManager &FileMgr = HeaderInfo.getFileMgr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000428
Chris Lattner53b0dab2007-10-09 22:10:18 +0000429 // Figure out where to get and map in the main file.
430 unsigned MainFileID = 0;
431 if (InFile != "-") {
432 const FileEntry *File = FileMgr.getFile(InFile);
433 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
434 if (MainFileID == 0) {
435 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
436 return 0;
437 }
438 } else {
439 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
440 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
441 if (MainFileID == 0) {
442 fprintf(stderr, "Error reading standard input! Empty?\n");
443 return 0;
444 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000445 }
446
Reid Spencer5f016e22007-07-11 17:01:13 +0000447 // Add macros from the command line.
448 // FIXME: Should traverse the #define/#undef lists in parallel.
449 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000450 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000452 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
453
454 // FIXME: Read any files specified by -imacros or -include.
455
456 // Null terminate PredefinedBuffer and add it.
457 PredefineBuffer.push_back(0);
458 PP.setPredefines(&PredefineBuffer[0]);
459
460 // Once we've read this, we're done.
461 return MainFileID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000462}
Chris Lattner53b0dab2007-10-09 22:10:18 +0000463
464
Reid Spencer5f016e22007-07-11 17:01:13 +0000465
466//===----------------------------------------------------------------------===//
467// Preprocessor include path information.
468//===----------------------------------------------------------------------===//
469
470// This tool exports a large number of command line options to control how the
471// preprocessor searches for header files. At root, however, the Preprocessor
472// object takes a very simple interface: a list of directories to search for
473//
474// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000475// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000476//
477// FIXME: -include,-imacros
478
479static llvm::cl::opt<bool>
480nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
481
482// Various command line options. These four add directories to each chain.
483static llvm::cl::list<std::string>
484F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
485 llvm::cl::desc("Add directory to framework include search path"));
486static llvm::cl::list<std::string>
487I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
488 llvm::cl::desc("Add directory to include search path"));
489static llvm::cl::list<std::string>
490idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
491 llvm::cl::desc("Add directory to AFTER include search path"));
492static llvm::cl::list<std::string>
493iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
494 llvm::cl::desc("Add directory to QUOTE include search path"));
495static llvm::cl::list<std::string>
496isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
497 llvm::cl::desc("Add directory to SYSTEM include search path"));
498
499// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
500static llvm::cl::list<std::string>
501iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
502 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
503static llvm::cl::list<std::string>
504iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
505 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
506static llvm::cl::list<std::string>
507iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
508 llvm::cl::Prefix,
509 llvm::cl::desc("Set directory to include search path with prefix"));
510
Chris Lattner0c946412007-08-26 17:47:35 +0000511static llvm::cl::opt<std::string>
512isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
513 llvm::cl::desc("Set the system root directory (usually /)"));
514
Reid Spencer5f016e22007-07-11 17:01:13 +0000515// Finally, implement the code that groks the options above.
516enum IncludeDirGroup {
517 Quoted = 0,
518 Angled,
519 System,
520 After
521};
522
523static std::vector<DirectoryLookup> IncludeGroup[4];
524
525/// AddPath - Add the specified path to the specified group list.
526///
527static void AddPath(const std::string &Path, IncludeDirGroup Group,
528 bool isCXXAware, bool isUserSupplied,
529 bool isFramework, FileManager &FM) {
Chris Lattner0c946412007-08-26 17:47:35 +0000530 const DirectoryEntry *DE;
531 if (Group == System)
532 DE = FM.getDirectory(isysroot + "/" + Path);
533 else
534 DE = FM.getDirectory(Path);
535
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 if (DE == 0) {
537 if (Verbose)
538 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
539 Path.c_str());
540 return;
541 }
542
543 DirectoryLookup::DirType Type;
544 if (Group == Quoted || Group == Angled)
545 Type = DirectoryLookup::NormalHeaderDir;
546 else if (isCXXAware)
547 Type = DirectoryLookup::SystemHeaderDir;
548 else
549 Type = DirectoryLookup::ExternCSystemHeaderDir;
550
551 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
552 isFramework));
553}
554
555/// RemoveDuplicates - If there are duplicate directory entries in the specified
556/// search list, remove the later (dead) ones.
557static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
558 std::set<const DirectoryEntry *> SeenDirs;
559 for (unsigned i = 0; i != SearchList.size(); ++i) {
560 // If this isn't the first time we've seen this dir, remove it.
561 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
562 if (Verbose)
563 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
564 SearchList[i].getDir()->getName());
565 SearchList.erase(SearchList.begin()+i);
566 --i;
567 }
568 }
569}
570
571/// InitializeIncludePaths - Process the -I options and set them in the
572/// HeaderSearch object.
573static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
574 Diagnostic &Diags, const LangOptions &Lang) {
575 // Handle -F... options.
576 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
577 AddPath(F_dirs[i], Angled, false, true, true, FM);
578
579 // Handle -I... options.
580 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
581 if (I_dirs[i] == "-") {
582 // -I- is a deprecated GCC feature.
583 Diags.Report(SourceLocation(), diag::err_pp_I_dash_not_supported);
584 } else {
585 AddPath(I_dirs[i], Angled, false, true, false, FM);
586 }
587 }
588
589 // Handle -idirafter... options.
590 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
591 AddPath(idirafter_dirs[i], After, false, true, false, FM);
592
593 // Handle -iquote... options.
594 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
595 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
596
597 // Handle -isystem... options.
598 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
599 AddPath(isystem_dirs[i], System, false, true, false, FM);
600
601 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
602 // parallel, processing the values in order of occurance to get the right
603 // prefixes.
604 {
605 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
606 unsigned iprefix_idx = 0;
607 unsigned iwithprefix_idx = 0;
608 unsigned iwithprefixbefore_idx = 0;
609 bool iprefix_done = iprefix_vals.empty();
610 bool iwithprefix_done = iwithprefix_vals.empty();
611 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
612 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
613 if (!iprefix_done &&
614 (iwithprefix_done ||
615 iprefix_vals.getPosition(iprefix_idx) <
616 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
617 (iwithprefixbefore_done ||
618 iprefix_vals.getPosition(iprefix_idx) <
619 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
620 Prefix = iprefix_vals[iprefix_idx];
621 ++iprefix_idx;
622 iprefix_done = iprefix_idx == iprefix_vals.size();
623 } else if (!iwithprefix_done &&
624 (iwithprefixbefore_done ||
625 iwithprefix_vals.getPosition(iwithprefix_idx) <
626 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
627 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
628 System, false, false, false, FM);
629 ++iwithprefix_idx;
630 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
631 } else {
632 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
633 Angled, false, false, false, FM);
634 ++iwithprefixbefore_idx;
635 iwithprefixbefore_done =
636 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
637 }
638 }
639 }
640
641 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
642 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
643
644 // FIXME: temporary hack: hard-coded paths.
645 // FIXME: get these from the target?
646 if (!nostdinc) {
647 if (Lang.CPlusPlus) {
648 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
649 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
650 false, FM);
651 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
652 }
653
654 AddPath("/usr/local/include", System, false, false, false, FM);
655 // leopard
656 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
657 false, false, false, FM);
658 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
659 System, false, false, false, FM);
660 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
661 "4.0.1/../../../../powerpc-apple-darwin0/include",
662 System, false, false, false, FM);
663
664 // tiger
665 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
666 false, false, false, FM);
667 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
668 System, false, false, false, FM);
669 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
670 "4.0.1/../../../../powerpc-apple-darwin8/include",
671 System, false, false, false, FM);
672
673 AddPath("/usr/include", System, false, false, false, FM);
674 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
675 AddPath("/Library/Frameworks", System, true, false, true, FM);
676 }
677
678 // Now that we have collected all of the include paths, merge them all
679 // together and tell the preprocessor about them.
680
681 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
682 std::vector<DirectoryLookup> SearchList;
683 SearchList = IncludeGroup[Angled];
684 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
685 IncludeGroup[System].end());
686 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
687 IncludeGroup[After].end());
688 RemoveDuplicates(SearchList);
689 RemoveDuplicates(IncludeGroup[Quoted]);
690
691 // Prepend QUOTED list on the search list.
692 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
693 IncludeGroup[Quoted].end());
694
695
696 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
697 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
698 DontSearchCurDir);
699
700 // If verbose, print the list of directories that will be searched.
701 if (Verbose) {
702 fprintf(stderr, "#include \"...\" search starts here:\n");
703 unsigned QuotedIdx = IncludeGroup[Quoted].size();
704 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
705 if (i == QuotedIdx)
706 fprintf(stderr, "#include <...> search starts here:\n");
707 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
708 }
709 }
710}
711
712
Reid Spencer5f016e22007-07-11 17:01:13 +0000713//===----------------------------------------------------------------------===//
714// Basic Parser driver
715//===----------------------------------------------------------------------===//
716
717static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
718 Parser P(PP, *PA);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000719 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000720
721 // Parsing the specified input file.
722 P.ParseTranslationUnit();
723 delete PA;
724}
725
726//===----------------------------------------------------------------------===//
727// Main driver
728//===----------------------------------------------------------------------===//
729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730/// ProcessInputFile - Process a single input file with the specified state.
731///
732static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
733 const std::string &InFile,
734 SourceManager &SourceMgr,
735 TextDiagnostics &OurDiagnosticClient,
736 HeaderSearch &HeaderInfo,
737 const LangOptions &LangInfo) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000738
739 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000740 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000741
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 switch (ProgAction) {
743 default:
744 fprintf(stderr, "Unexpected program action!\n");
745 return;
746 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000747 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000749 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 do {
751 PP.Lex(Tok);
752 PP.DumpToken(Tok, true);
753 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000754 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000755 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 break;
757 }
758 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000759 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000761 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 do {
763 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000764 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000765 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000766 break;
767 }
768
769 case PrintPreprocessedInput: // -E mode.
770 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
Chris Lattnerbd247762007-07-22 06:05:44 +0000771 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000772 break;
773
774 case ParseNoop: // -parse-noop
Steve Naroffb4292f22007-10-31 20:55:39 +0000775 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000776 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 break;
778
779 case ParsePrintCallbacks:
Steve Naroffb4292f22007-10-31 20:55:39 +0000780 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
781 MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000782 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 break;
Ted Kremenek44579782007-09-25 18:37:20 +0000784
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000785 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000786 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +0000787 break;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000788
Chris Lattner3b427b32007-10-11 00:18:28 +0000789 case ASTPrint:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000790 Consumer = CreateASTPrinter();
791 break;
792
Chris Lattner3b427b32007-10-11 00:18:28 +0000793 case ASTDump:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000794 Consumer = CreateASTDumper();
795 break;
796
Chris Lattner3b427b32007-10-11 00:18:28 +0000797 case ASTView:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000798 Consumer = CreateASTViewer();
799 break;
800
801 case ParseCFGDump:
802 case ParseCFGView:
803 Consumer = CreateCFGDumper(ProgAction == ParseCFGView);
804 break;
805
806 case AnalysisLiveVariables:
807 Consumer = CreateLiveVarAnalyzer();
808 break;
809
810 case WarnDeadStores:
811 Consumer = CreateDeadStoreChecker(PP.getDiagnostics());
812 break;
813
814 case WarnUninitVals:
815 Consumer = CreateUnitValsChecker(PP.getDiagnostics());
816 break;
817
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000818 case TestSerialization:
819 Consumer = CreateSerializationTest();
820 break;
821
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000822 case EmitLLVM:
823 Consumer = CreateLLVMEmitter(PP.getDiagnostics());
Reid Spencer5f016e22007-07-11 17:01:13 +0000824 break;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000825
826 case RewriteTest:
827 Consumer = CreateCodeRewriterTest();
828 break;
Chris Lattner580980b2007-09-16 19:46:59 +0000829 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000830
831 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000832 if (VerifyDiagnostics)
Chris Lattner31e6c7d2007-11-03 06:24:16 +0000833 exit(CheckASTConsumer(PP, MainFileID, Consumer));
834
835 // This deletes Consumer.
836 ParseAST(PP, MainFileID, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 }
838
839 if (Stats) {
840 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
841 PP.PrintStats();
842 PP.getIdentifierTable().PrintStats();
843 HeaderInfo.PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +0000844 if (ClearSourceMgr)
845 SourceMgr.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000846 fprintf(stderr, "\n");
847 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000848
849 // For a multi-file compilation, some things are ok with nuking the source
850 // manager tables, other require stable fileid/macroid's across multiple
851 // files.
852 if (ClearSourceMgr) {
853 SourceMgr.clearIDTables();
854 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000855}
856
857static llvm::cl::list<std::string>
858InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
859
860
861int main(int argc, char **argv) {
862 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
863 llvm::sys::PrintStackTraceOnErrorSignal();
864
865 // If no input was specified, read from stdin.
866 if (InputFilenames.empty())
867 InputFilenames.push_back("-");
868
869 /// Create a SourceManager object. This tracks and owns all the file buffers
870 /// allocated to the program.
871 SourceManager SourceMgr;
872
873 // Create a file manager object to provide access to and cache the filesystem.
874 FileManager FileMgr;
875
876 // Initialize language options, inferring file types from input filenames.
877 // FIXME: This infers info from the first file, we should clump by language
878 // to handle 'x.c y.c a.cpp b.cpp'.
879 LangOptions LangInfo;
880 InitializeBaseLanguage(LangInfo, InputFilenames[0]);
881 InitializeLanguageStandard(LangInfo);
882
883 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000884 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 // Print diagnostics to stderr by default.
886 DiagClient.reset(new TextDiagnosticPrinter(SourceMgr));
887 } else {
888 // When checking diagnostics, just buffer them up.
889 DiagClient.reset(new TextDiagnosticBuffer(SourceMgr));
890
891 if (InputFilenames.size() != 1) {
892 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000893 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000894 return 1;
895 }
896 }
897
898 // Configure our handling of diagnostics.
899 Diagnostic Diags(*DiagClient);
900 InitializeDiagnostics(Diags);
901
902 // Get information about the targets being compiled for. Note that this
903 // pointer and the TargetInfoImpl objects are never deleted by this toy
904 // driver.
905 TargetInfo *Target = CreateTargetInfo(Diags);
906 if (Target == 0) {
907 fprintf(stderr,
908 "Sorry, don't know what target this is, please use -arch.\n");
909 exit(1);
910 }
911
912 // Process the -I options and set them in the HeaderInfo.
913 HeaderSearch HeaderInfo(FileMgr);
914 DiagClient->setHeaderSearch(HeaderInfo);
915 InitializeIncludePaths(HeaderInfo, FileMgr, Diags, LangInfo);
916
917 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
918 // Set up the preprocessor with these options.
919 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000920 const std::string &InFile = InputFilenames[i];
Chris Lattner53b0dab2007-10-09 22:10:18 +0000921 std::vector<char> PredefineBuffer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000922 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
923 HeaderInfo, LangInfo,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000924 PredefineBuffer);
Reid Spencer5f016e22007-07-11 17:01:13 +0000925
926 if (!MainFileID) continue;
927
928 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
929 *DiagClient, HeaderInfo, LangInfo);
930 HeaderInfo.ClearFileInfo();
931 }
932
933 unsigned NumDiagnostics = Diags.getNumDiagnostics();
934
935 if (NumDiagnostics)
936 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
937 (NumDiagnostics == 1 ? "" : "s"));
938
939 if (Stats) {
940 // Printed from high-to-low level.
941 SourceMgr.PrintStats();
942 FileMgr.PrintStats();
943 fprintf(stderr, "\n");
944 }
945
Chris Lattner96f1a642007-07-21 05:40:53 +0000946 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000947}