blob: f85ab52cc77c3ca144932236e5dfba2a1d4926a5 [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"));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000281
282static llvm::cl::opt<bool>
283WritableStrings("fwritable-strings",
284 llvm::cl::desc("Store string literals as writable data."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000285// FIXME: add:
286// -ansi
287// -trigraphs
288// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000289// -fpascal-strings
Reid Spencer5f016e22007-07-11 17:01:13 +0000290static void InitializeLanguageStandard(LangOptions &Options) {
291 if (LangStd == lang_unspecified) {
292 // Based on the base language, pick one.
293 switch (BaseLang) {
294 default: assert(0 && "Unknown base language");
295 case langkind_c:
296 case langkind_c_cpp:
297 case langkind_objc:
298 case langkind_objc_cpp:
299 LangStd = lang_gnu99;
300 break;
301 case langkind_cxx:
302 case langkind_cxx_cpp:
303 case langkind_objcxx:
304 case langkind_objcxx_cpp:
305 LangStd = lang_gnucxx98;
306 break;
307 }
308 }
309
310 switch (LangStd) {
311 default: assert(0 && "Unknown language standard!");
312
313 // Fall through from newer standards to older ones. This isn't really right.
314 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000315 case lang_gnucxx0x:
316 case lang_cxx0x:
317 Options.CPlusPlus0x = 1;
318 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 case lang_gnucxx98:
320 case lang_cxx98:
321 Options.CPlusPlus = 1;
322 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000323 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 // FALL THROUGH.
325 case lang_gnu99:
326 case lang_c99:
327 Options.Digraphs = 1;
328 Options.C99 = 1;
329 Options.HexFloats = 1;
330 // FALL THROUGH.
331 case lang_gnu89:
332 Options.BCPLComment = 1; // Only for C99/C++.
333 // FALL THROUGH.
334 case lang_c94:
335 case lang_c89:
336 break;
337 }
338
339 Options.Trigraphs = 1; // -trigraphs or -ansi
340 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000341 Options.PascalStrings = PascalStrings;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000342 Options.WritableStrings = WritableStrings;
Reid Spencer5f016e22007-07-11 17:01:13 +0000343}
344
345//===----------------------------------------------------------------------===//
346// Our DiagnosticClient implementation
347//===----------------------------------------------------------------------===//
348
349// FIXME: Werror should take a list of things, -Werror=foo,bar
350static llvm::cl::opt<bool>
351WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
352
353static llvm::cl::opt<bool>
354WarnOnExtensions("pedantic", llvm::cl::init(false),
355 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
356
357static llvm::cl::opt<bool>
358ErrorOnExtensions("pedantic-errors",
359 llvm::cl::desc("Issue an error on uses of GCC extensions"));
360
361static llvm::cl::opt<bool>
362WarnUnusedMacros("Wunused_macros",
363 llvm::cl::desc("Warn for unused macros in the main translation unit"));
364
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000365static llvm::cl::opt<bool>
366WarnFloatEqual("Wfloat-equal",
367 llvm::cl::desc("Warn about equality comparisons of floating point values."));
368
Reid Spencer5f016e22007-07-11 17:01:13 +0000369/// InitializeDiagnostics - Initialize the diagnostic object, based on the
370/// current command line option settings.
371static void InitializeDiagnostics(Diagnostic &Diags) {
372 Diags.setWarningsAsErrors(WarningsAsErrors);
373 Diags.setWarnOnExtensions(WarnOnExtensions);
374 Diags.setErrorOnExtensions(ErrorOnExtensions);
375
376 // Silence the "macro is not used" warning unless requested.
377 if (!WarnUnusedMacros)
378 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000379
380 // Silence "floating point comparison" warnings unless requested.
381 if (!WarnFloatEqual)
382 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000383}
384
385//===----------------------------------------------------------------------===//
386// Preprocessor Initialization
387//===----------------------------------------------------------------------===//
388
389// FIXME: Preprocessor builtins to support.
390// -A... - Play with #assertions
391// -undef - Undefine all predefined macros
392
393static llvm::cl::list<std::string>
394D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
395 llvm::cl::desc("Predefine the specified macro"));
396static llvm::cl::list<std::string>
397U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
398 llvm::cl::desc("Undefine the specified macro"));
399
400// Append a #define line to Buf for Macro. Macro should be of the form XXX,
401// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
402// "#define XXX Y z W". To get a #define with no value, use "XXX=".
403static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
404 const char *Command = "#define ") {
405 Buf.insert(Buf.end(), Command, Command+strlen(Command));
406 if (const char *Equal = strchr(Macro, '=')) {
407 // Turn the = into ' '.
408 Buf.insert(Buf.end(), Macro, Equal);
409 Buf.push_back(' ');
410 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
411 } else {
412 // Push "macroname 1".
413 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
414 Buf.push_back(' ');
415 Buf.push_back('1');
416 }
417 Buf.push_back('\n');
418}
419
Reid Spencer5f016e22007-07-11 17:01:13 +0000420
Chris Lattner53b0dab2007-10-09 22:10:18 +0000421/// InitializePreprocessor - Initialize the preprocessor getting it and the
422/// environment ready to process a single file. This returns the file ID for the
423/// input file. If a failure happens, it returns 0.
424///
425static unsigned InitializePreprocessor(Preprocessor &PP,
426 const std::string &InFile,
427 SourceManager &SourceMgr,
428 HeaderSearch &HeaderInfo,
429 const LangOptions &LangInfo,
430 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000431
Chris Lattner53b0dab2007-10-09 22:10:18 +0000432 FileManager &FileMgr = HeaderInfo.getFileMgr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000433
Chris Lattner53b0dab2007-10-09 22:10:18 +0000434 // Figure out where to get and map in the main file.
435 unsigned MainFileID = 0;
436 if (InFile != "-") {
437 const FileEntry *File = FileMgr.getFile(InFile);
438 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
439 if (MainFileID == 0) {
440 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
441 return 0;
442 }
443 } else {
444 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
445 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
446 if (MainFileID == 0) {
447 fprintf(stderr, "Error reading standard input! Empty?\n");
448 return 0;
449 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 }
451
Reid Spencer5f016e22007-07-11 17:01:13 +0000452 // Add macros from the command line.
453 // FIXME: Should traverse the #define/#undef lists in parallel.
454 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000455 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000457 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
458
459 // FIXME: Read any files specified by -imacros or -include.
460
461 // Null terminate PredefinedBuffer and add it.
462 PredefineBuffer.push_back(0);
463 PP.setPredefines(&PredefineBuffer[0]);
464
465 // Once we've read this, we're done.
466 return MainFileID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000467}
Chris Lattner53b0dab2007-10-09 22:10:18 +0000468
469
Reid Spencer5f016e22007-07-11 17:01:13 +0000470
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
Reid Spencer5f016e22007-07-11 17:01:13 +0000718//===----------------------------------------------------------------------===//
719// Basic Parser driver
720//===----------------------------------------------------------------------===//
721
722static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
723 Parser P(PP, *PA);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000724 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000725
726 // Parsing the specified input file.
727 P.ParseTranslationUnit();
728 delete PA;
729}
730
731//===----------------------------------------------------------------------===//
732// Main driver
733//===----------------------------------------------------------------------===//
734
Reid Spencer5f016e22007-07-11 17:01:13 +0000735/// ProcessInputFile - Process a single input file with the specified state.
736///
737static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
738 const std::string &InFile,
739 SourceManager &SourceMgr,
740 TextDiagnostics &OurDiagnosticClient,
741 HeaderSearch &HeaderInfo,
742 const LangOptions &LangInfo) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000743
744 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000745 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000746
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 switch (ProgAction) {
748 default:
749 fprintf(stderr, "Unexpected program action!\n");
750 return;
751 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000752 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000754 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000755 do {
756 PP.Lex(Tok);
757 PP.DumpToken(Tok, true);
758 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000759 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000760 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 break;
762 }
763 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000764 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000766 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000767 do {
768 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000769 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000770 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000771 break;
772 }
773
774 case PrintPreprocessedInput: // -E mode.
775 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
Chris Lattnerbd247762007-07-22 06:05:44 +0000776 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 break;
778
779 case ParseNoop: // -parse-noop
Steve Naroffb4292f22007-10-31 20:55:39 +0000780 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000781 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000782 break;
783
784 case ParsePrintCallbacks:
Steve Naroffb4292f22007-10-31 20:55:39 +0000785 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
786 MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000787 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 break;
Ted Kremenek44579782007-09-25 18:37:20 +0000789
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000790 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000791 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +0000792 break;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000793
Chris Lattner3b427b32007-10-11 00:18:28 +0000794 case ASTPrint:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000795 Consumer = CreateASTPrinter();
796 break;
797
Chris Lattner3b427b32007-10-11 00:18:28 +0000798 case ASTDump:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000799 Consumer = CreateASTDumper();
800 break;
801
Chris Lattner3b427b32007-10-11 00:18:28 +0000802 case ASTView:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000803 Consumer = CreateASTViewer();
804 break;
805
806 case ParseCFGDump:
807 case ParseCFGView:
808 Consumer = CreateCFGDumper(ProgAction == ParseCFGView);
809 break;
810
811 case AnalysisLiveVariables:
812 Consumer = CreateLiveVarAnalyzer();
813 break;
814
815 case WarnDeadStores:
816 Consumer = CreateDeadStoreChecker(PP.getDiagnostics());
817 break;
818
819 case WarnUninitVals:
820 Consumer = CreateUnitValsChecker(PP.getDiagnostics());
821 break;
822
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000823 case TestSerialization:
824 Consumer = CreateSerializationTest();
825 break;
826
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000827 case EmitLLVM:
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000828 Consumer = CreateLLVMEmitter(PP.getDiagnostics(), PP.getLangOptions());
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 break;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000830
831 case RewriteTest:
832 Consumer = CreateCodeRewriterTest();
833 break;
Chris Lattner580980b2007-09-16 19:46:59 +0000834 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000835
836 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000837 if (VerifyDiagnostics)
Chris Lattner31e6c7d2007-11-03 06:24:16 +0000838 exit(CheckASTConsumer(PP, MainFileID, Consumer));
839
840 // This deletes Consumer.
841 ParseAST(PP, MainFileID, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 }
843
844 if (Stats) {
845 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
846 PP.PrintStats();
847 PP.getIdentifierTable().PrintStats();
848 HeaderInfo.PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +0000849 if (ClearSourceMgr)
850 SourceMgr.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000851 fprintf(stderr, "\n");
852 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000853
854 // For a multi-file compilation, some things are ok with nuking the source
855 // manager tables, other require stable fileid/macroid's across multiple
856 // files.
857 if (ClearSourceMgr) {
858 SourceMgr.clearIDTables();
859 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000860}
861
862static llvm::cl::list<std::string>
863InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
864
865
866int main(int argc, char **argv) {
867 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
868 llvm::sys::PrintStackTraceOnErrorSignal();
869
870 // If no input was specified, read from stdin.
871 if (InputFilenames.empty())
872 InputFilenames.push_back("-");
873
874 /// Create a SourceManager object. This tracks and owns all the file buffers
875 /// allocated to the program.
876 SourceManager SourceMgr;
877
878 // Create a file manager object to provide access to and cache the filesystem.
879 FileManager FileMgr;
880
881 // Initialize language options, inferring file types from input filenames.
882 // FIXME: This infers info from the first file, we should clump by language
883 // to handle 'x.c y.c a.cpp b.cpp'.
884 LangOptions LangInfo;
885 InitializeBaseLanguage(LangInfo, InputFilenames[0]);
886 InitializeLanguageStandard(LangInfo);
887
888 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000889 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 // Print diagnostics to stderr by default.
891 DiagClient.reset(new TextDiagnosticPrinter(SourceMgr));
892 } else {
893 // When checking diagnostics, just buffer them up.
894 DiagClient.reset(new TextDiagnosticBuffer(SourceMgr));
895
896 if (InputFilenames.size() != 1) {
897 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000898 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 return 1;
900 }
901 }
902
903 // Configure our handling of diagnostics.
904 Diagnostic Diags(*DiagClient);
905 InitializeDiagnostics(Diags);
906
907 // Get information about the targets being compiled for. Note that this
908 // pointer and the TargetInfoImpl objects are never deleted by this toy
909 // driver.
910 TargetInfo *Target = CreateTargetInfo(Diags);
911 if (Target == 0) {
912 fprintf(stderr,
913 "Sorry, don't know what target this is, please use -arch.\n");
914 exit(1);
915 }
916
917 // Process the -I options and set them in the HeaderInfo.
918 HeaderSearch HeaderInfo(FileMgr);
919 DiagClient->setHeaderSearch(HeaderInfo);
920 InitializeIncludePaths(HeaderInfo, FileMgr, Diags, LangInfo);
921
922 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
923 // Set up the preprocessor with these options.
924 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 const std::string &InFile = InputFilenames[i];
Chris Lattner53b0dab2007-10-09 22:10:18 +0000926 std::vector<char> PredefineBuffer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000927 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
928 HeaderInfo, LangInfo,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000929 PredefineBuffer);
Reid Spencer5f016e22007-07-11 17:01:13 +0000930
931 if (!MainFileID) continue;
932
933 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
934 *DiagClient, HeaderInfo, LangInfo);
935 HeaderInfo.ClearFileInfo();
936 }
937
938 unsigned NumDiagnostics = Diags.getNumDiagnostics();
939
940 if (NumDiagnostics)
941 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
942 (NumDiagnostics == 1 ? "" : "s"));
943
944 if (Stats) {
945 // Printed from high-to-low level.
946 SourceMgr.PrintStats();
947 FileMgr.PrintStats();
948 fprintf(stderr, "\n");
949 }
950
Chris Lattner96f1a642007-07-21 05:40:53 +0000951 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000952}