blob: 6e8dd9e967287aa7c373634e171e0a5a390c496b [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.
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 Lattner3b427b32007-10-11 00:18:28 +000087 clEnumValN(ASTPrint, "ast-print",
88 "Build ASTs and then pretty-print them"),
89 clEnumValN(ASTDump, "ast-dump",
90 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +000091 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +000092 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +000093 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +000094 "Run parser, then build and print CFGs."),
95 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +000096 "Run parser, then build and view CFGs with Graphviz."),
97 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +000098 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +000099 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000100 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000101 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000102 "Flag warnings of uses of unitialized variables."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000104 "Build ASTs then convert to LLVM, emit .ll file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000105 clEnumValN(RewriteTest, "rewrite-test",
106 "Playground for the code rewriter"),
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
Anders Carlssonee98ac52007-10-15 02:50:23 +0000274static llvm::cl::opt<bool>
275PascalStrings("fpascal-strings",
276 llvm::cl::desc("Recognize and construct Pascal-style "
277 "string literals"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000278// FIXME: add:
279// -ansi
280// -trigraphs
281// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000282// -fpascal-strings
Reid Spencer5f016e22007-07-11 17:01:13 +0000283static void InitializeLanguageStandard(LangOptions &Options) {
284 if (LangStd == lang_unspecified) {
285 // Based on the base language, pick one.
286 switch (BaseLang) {
287 default: assert(0 && "Unknown base language");
288 case langkind_c:
289 case langkind_c_cpp:
290 case langkind_objc:
291 case langkind_objc_cpp:
292 LangStd = lang_gnu99;
293 break;
294 case langkind_cxx:
295 case langkind_cxx_cpp:
296 case langkind_objcxx:
297 case langkind_objcxx_cpp:
298 LangStd = lang_gnucxx98;
299 break;
300 }
301 }
302
303 switch (LangStd) {
304 default: assert(0 && "Unknown language standard!");
305
306 // Fall through from newer standards to older ones. This isn't really right.
307 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000308 case lang_gnucxx0x:
309 case lang_cxx0x:
310 Options.CPlusPlus0x = 1;
311 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 case lang_gnucxx98:
313 case lang_cxx98:
314 Options.CPlusPlus = 1;
315 Options.CXXOperatorNames = !NoOperatorNames;
316 // FALL THROUGH.
317 case lang_gnu99:
318 case lang_c99:
319 Options.Digraphs = 1;
320 Options.C99 = 1;
321 Options.HexFloats = 1;
322 // FALL THROUGH.
323 case lang_gnu89:
324 Options.BCPLComment = 1; // Only for C99/C++.
325 // FALL THROUGH.
326 case lang_c94:
327 case lang_c89:
328 break;
329 }
330
331 Options.Trigraphs = 1; // -trigraphs or -ansi
332 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000333 Options.PascalStrings = PascalStrings;
Reid Spencer5f016e22007-07-11 17:01:13 +0000334}
335
336//===----------------------------------------------------------------------===//
337// Our DiagnosticClient implementation
338//===----------------------------------------------------------------------===//
339
340// FIXME: Werror should take a list of things, -Werror=foo,bar
341static llvm::cl::opt<bool>
342WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
343
344static llvm::cl::opt<bool>
345WarnOnExtensions("pedantic", llvm::cl::init(false),
346 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
347
348static llvm::cl::opt<bool>
349ErrorOnExtensions("pedantic-errors",
350 llvm::cl::desc("Issue an error on uses of GCC extensions"));
351
352static llvm::cl::opt<bool>
353WarnUnusedMacros("Wunused_macros",
354 llvm::cl::desc("Warn for unused macros in the main translation unit"));
355
Reid Spencer5f016e22007-07-11 17:01:13 +0000356/// InitializeDiagnostics - Initialize the diagnostic object, based on the
357/// current command line option settings.
358static void InitializeDiagnostics(Diagnostic &Diags) {
359 Diags.setWarningsAsErrors(WarningsAsErrors);
360 Diags.setWarnOnExtensions(WarnOnExtensions);
361 Diags.setErrorOnExtensions(ErrorOnExtensions);
362
363 // Silence the "macro is not used" warning unless requested.
364 if (!WarnUnusedMacros)
365 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
366}
367
368//===----------------------------------------------------------------------===//
369// Preprocessor Initialization
370//===----------------------------------------------------------------------===//
371
372// FIXME: Preprocessor builtins to support.
373// -A... - Play with #assertions
374// -undef - Undefine all predefined macros
375
376static llvm::cl::list<std::string>
377D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
378 llvm::cl::desc("Predefine the specified macro"));
379static llvm::cl::list<std::string>
380U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
381 llvm::cl::desc("Undefine the specified macro"));
382
383// Append a #define line to Buf for Macro. Macro should be of the form XXX,
384// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
385// "#define XXX Y z W". To get a #define with no value, use "XXX=".
386static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
387 const char *Command = "#define ") {
388 Buf.insert(Buf.end(), Command, Command+strlen(Command));
389 if (const char *Equal = strchr(Macro, '=')) {
390 // Turn the = into ' '.
391 Buf.insert(Buf.end(), Macro, Equal);
392 Buf.push_back(' ');
393 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
394 } else {
395 // Push "macroname 1".
396 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
397 Buf.push_back(' ');
398 Buf.push_back('1');
399 }
400 Buf.push_back('\n');
401}
402
Reid Spencer5f016e22007-07-11 17:01:13 +0000403
Chris Lattner53b0dab2007-10-09 22:10:18 +0000404/// InitializePreprocessor - Initialize the preprocessor getting it and the
405/// environment ready to process a single file. This returns the file ID for the
406/// input file. If a failure happens, it returns 0.
407///
408static unsigned InitializePreprocessor(Preprocessor &PP,
409 const std::string &InFile,
410 SourceManager &SourceMgr,
411 HeaderSearch &HeaderInfo,
412 const LangOptions &LangInfo,
413 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000414
Chris Lattner53b0dab2007-10-09 22:10:18 +0000415 FileManager &FileMgr = HeaderInfo.getFileMgr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000416
Chris Lattner53b0dab2007-10-09 22:10:18 +0000417 // Figure out where to get and map in the main file.
418 unsigned MainFileID = 0;
419 if (InFile != "-") {
420 const FileEntry *File = FileMgr.getFile(InFile);
421 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
422 if (MainFileID == 0) {
423 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
424 return 0;
425 }
426 } else {
427 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
428 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
429 if (MainFileID == 0) {
430 fprintf(stderr, "Error reading standard input! Empty?\n");
431 return 0;
432 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 }
434
Reid Spencer5f016e22007-07-11 17:01:13 +0000435 // Add macros from the command line.
436 // FIXME: Should traverse the #define/#undef lists in parallel.
437 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000438 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000439 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000440 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
441
442 // FIXME: Read any files specified by -imacros or -include.
443
444 // Null terminate PredefinedBuffer and add it.
445 PredefineBuffer.push_back(0);
446 PP.setPredefines(&PredefineBuffer[0]);
447
448 // Once we've read this, we're done.
449 return MainFileID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000450}
Chris Lattner53b0dab2007-10-09 22:10:18 +0000451
452
Reid Spencer5f016e22007-07-11 17:01:13 +0000453
454//===----------------------------------------------------------------------===//
455// Preprocessor include path information.
456//===----------------------------------------------------------------------===//
457
458// This tool exports a large number of command line options to control how the
459// preprocessor searches for header files. At root, however, the Preprocessor
460// object takes a very simple interface: a list of directories to search for
461//
462// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000463// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000464//
465// FIXME: -include,-imacros
466
467static llvm::cl::opt<bool>
468nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
469
470// Various command line options. These four add directories to each chain.
471static llvm::cl::list<std::string>
472F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
473 llvm::cl::desc("Add directory to framework include search path"));
474static llvm::cl::list<std::string>
475I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
476 llvm::cl::desc("Add directory to include search path"));
477static llvm::cl::list<std::string>
478idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
479 llvm::cl::desc("Add directory to AFTER include search path"));
480static llvm::cl::list<std::string>
481iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
482 llvm::cl::desc("Add directory to QUOTE include search path"));
483static llvm::cl::list<std::string>
484isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
485 llvm::cl::desc("Add directory to SYSTEM include search path"));
486
487// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
488static llvm::cl::list<std::string>
489iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
490 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
491static llvm::cl::list<std::string>
492iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
493 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
494static llvm::cl::list<std::string>
495iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
496 llvm::cl::Prefix,
497 llvm::cl::desc("Set directory to include search path with prefix"));
498
Chris Lattner0c946412007-08-26 17:47:35 +0000499static llvm::cl::opt<std::string>
500isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
501 llvm::cl::desc("Set the system root directory (usually /)"));
502
Reid Spencer5f016e22007-07-11 17:01:13 +0000503// Finally, implement the code that groks the options above.
504enum IncludeDirGroup {
505 Quoted = 0,
506 Angled,
507 System,
508 After
509};
510
511static std::vector<DirectoryLookup> IncludeGroup[4];
512
513/// AddPath - Add the specified path to the specified group list.
514///
515static void AddPath(const std::string &Path, IncludeDirGroup Group,
516 bool isCXXAware, bool isUserSupplied,
517 bool isFramework, FileManager &FM) {
Chris Lattner0c946412007-08-26 17:47:35 +0000518 const DirectoryEntry *DE;
519 if (Group == System)
520 DE = FM.getDirectory(isysroot + "/" + Path);
521 else
522 DE = FM.getDirectory(Path);
523
Reid Spencer5f016e22007-07-11 17:01:13 +0000524 if (DE == 0) {
525 if (Verbose)
526 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
527 Path.c_str());
528 return;
529 }
530
531 DirectoryLookup::DirType Type;
532 if (Group == Quoted || Group == Angled)
533 Type = DirectoryLookup::NormalHeaderDir;
534 else if (isCXXAware)
535 Type = DirectoryLookup::SystemHeaderDir;
536 else
537 Type = DirectoryLookup::ExternCSystemHeaderDir;
538
539 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
540 isFramework));
541}
542
543/// RemoveDuplicates - If there are duplicate directory entries in the specified
544/// search list, remove the later (dead) ones.
545static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
546 std::set<const DirectoryEntry *> SeenDirs;
547 for (unsigned i = 0; i != SearchList.size(); ++i) {
548 // If this isn't the first time we've seen this dir, remove it.
549 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
550 if (Verbose)
551 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
552 SearchList[i].getDir()->getName());
553 SearchList.erase(SearchList.begin()+i);
554 --i;
555 }
556 }
557}
558
559/// InitializeIncludePaths - Process the -I options and set them in the
560/// HeaderSearch object.
561static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
562 Diagnostic &Diags, const LangOptions &Lang) {
563 // Handle -F... options.
564 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
565 AddPath(F_dirs[i], Angled, false, true, true, FM);
566
567 // Handle -I... options.
568 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
569 if (I_dirs[i] == "-") {
570 // -I- is a deprecated GCC feature.
571 Diags.Report(SourceLocation(), diag::err_pp_I_dash_not_supported);
572 } else {
573 AddPath(I_dirs[i], Angled, false, true, false, FM);
574 }
575 }
576
577 // Handle -idirafter... options.
578 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
579 AddPath(idirafter_dirs[i], After, false, true, false, FM);
580
581 // Handle -iquote... options.
582 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
583 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
584
585 // Handle -isystem... options.
586 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
587 AddPath(isystem_dirs[i], System, false, true, false, FM);
588
589 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
590 // parallel, processing the values in order of occurance to get the right
591 // prefixes.
592 {
593 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
594 unsigned iprefix_idx = 0;
595 unsigned iwithprefix_idx = 0;
596 unsigned iwithprefixbefore_idx = 0;
597 bool iprefix_done = iprefix_vals.empty();
598 bool iwithprefix_done = iwithprefix_vals.empty();
599 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
600 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
601 if (!iprefix_done &&
602 (iwithprefix_done ||
603 iprefix_vals.getPosition(iprefix_idx) <
604 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
605 (iwithprefixbefore_done ||
606 iprefix_vals.getPosition(iprefix_idx) <
607 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
608 Prefix = iprefix_vals[iprefix_idx];
609 ++iprefix_idx;
610 iprefix_done = iprefix_idx == iprefix_vals.size();
611 } else if (!iwithprefix_done &&
612 (iwithprefixbefore_done ||
613 iwithprefix_vals.getPosition(iwithprefix_idx) <
614 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
615 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
616 System, false, false, false, FM);
617 ++iwithprefix_idx;
618 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
619 } else {
620 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
621 Angled, false, false, false, FM);
622 ++iwithprefixbefore_idx;
623 iwithprefixbefore_done =
624 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
625 }
626 }
627 }
628
629 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
630 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
631
632 // FIXME: temporary hack: hard-coded paths.
633 // FIXME: get these from the target?
634 if (!nostdinc) {
635 if (Lang.CPlusPlus) {
636 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
637 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
638 false, FM);
639 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
640 }
641
642 AddPath("/usr/local/include", System, false, false, false, FM);
643 // leopard
644 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
645 false, false, false, FM);
646 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
647 System, false, false, false, FM);
648 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
649 "4.0.1/../../../../powerpc-apple-darwin0/include",
650 System, false, false, false, FM);
651
652 // tiger
653 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
654 false, false, false, FM);
655 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
656 System, false, false, false, FM);
657 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
658 "4.0.1/../../../../powerpc-apple-darwin8/include",
659 System, false, false, false, FM);
660
661 AddPath("/usr/include", System, false, false, false, FM);
662 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
663 AddPath("/Library/Frameworks", System, true, false, true, FM);
664 }
665
666 // Now that we have collected all of the include paths, merge them all
667 // together and tell the preprocessor about them.
668
669 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
670 std::vector<DirectoryLookup> SearchList;
671 SearchList = IncludeGroup[Angled];
672 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
673 IncludeGroup[System].end());
674 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
675 IncludeGroup[After].end());
676 RemoveDuplicates(SearchList);
677 RemoveDuplicates(IncludeGroup[Quoted]);
678
679 // Prepend QUOTED list on the search list.
680 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
681 IncludeGroup[Quoted].end());
682
683
684 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
685 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
686 DontSearchCurDir);
687
688 // If verbose, print the list of directories that will be searched.
689 if (Verbose) {
690 fprintf(stderr, "#include \"...\" search starts here:\n");
691 unsigned QuotedIdx = IncludeGroup[Quoted].size();
692 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
693 if (i == QuotedIdx)
694 fprintf(stderr, "#include <...> search starts here:\n");
695 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
696 }
697 }
698}
699
700
Reid Spencer5f016e22007-07-11 17:01:13 +0000701//===----------------------------------------------------------------------===//
702// Basic Parser driver
703//===----------------------------------------------------------------------===//
704
705static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
706 Parser P(PP, *PA);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000707 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000708
709 // Parsing the specified input file.
710 P.ParseTranslationUnit();
711 delete PA;
712}
713
714//===----------------------------------------------------------------------===//
715// Main driver
716//===----------------------------------------------------------------------===//
717
Reid Spencer5f016e22007-07-11 17:01:13 +0000718/// ProcessInputFile - Process a single input file with the specified state.
719///
720static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
721 const std::string &InFile,
722 SourceManager &SourceMgr,
723 TextDiagnostics &OurDiagnosticClient,
724 HeaderSearch &HeaderInfo,
725 const LangOptions &LangInfo) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000726
727 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000728 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 switch (ProgAction) {
731 default:
732 fprintf(stderr, "Unexpected program action!\n");
733 return;
734 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000735 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000737 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 do {
739 PP.Lex(Tok);
740 PP.DumpToken(Tok, true);
741 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000742 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000743 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 break;
745 }
746 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
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);
Chris Lattner057aaf62007-10-09 18:03:42 +0000752 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000753 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 break;
755 }
756
757 case PrintPreprocessedInput: // -E mode.
758 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
Chris Lattnerbd247762007-07-22 06:05:44 +0000759 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 break;
761
762 case ParseNoop: // -parse-noop
763 ParseFile(PP, new MinimalAction(), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000764 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 break;
766
767 case ParsePrintCallbacks:
768 ParseFile(PP, CreatePrintParserActionsAction(), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000769 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000770 break;
Ted Kremenek44579782007-09-25 18:37:20 +0000771
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000772 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000773 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +0000774 break;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000775
Chris Lattner3b427b32007-10-11 00:18:28 +0000776 case ASTPrint:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000777 Consumer = CreateASTPrinter();
778 break;
779
Chris Lattner3b427b32007-10-11 00:18:28 +0000780 case ASTDump:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000781 Consumer = CreateASTDumper();
782 break;
783
Chris Lattner3b427b32007-10-11 00:18:28 +0000784 case ASTView:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000785 Consumer = CreateASTViewer();
786 break;
787
788 case ParseCFGDump:
789 case ParseCFGView:
790 Consumer = CreateCFGDumper(ProgAction == ParseCFGView);
791 break;
792
793 case AnalysisLiveVariables:
794 Consumer = CreateLiveVarAnalyzer();
795 break;
796
797 case WarnDeadStores:
798 Consumer = CreateDeadStoreChecker(PP.getDiagnostics());
799 break;
800
801 case WarnUninitVals:
802 Consumer = CreateUnitValsChecker(PP.getDiagnostics());
803 break;
804
805 case EmitLLVM:
806 Consumer = CreateLLVMEmitter(PP.getDiagnostics());
Reid Spencer5f016e22007-07-11 17:01:13 +0000807 break;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000808
809 case RewriteTest:
810 Consumer = CreateCodeRewriterTest();
811 break;
Chris Lattner580980b2007-09-16 19:46:59 +0000812 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000813
814 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000815 if (VerifyDiagnostics)
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000816 exit (CheckASTConsumer(PP, MainFileID, Consumer));
817 else
818 ParseAST(PP, MainFileID, *Consumer, Stats);
819
820 delete Consumer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000821 }
822
823 if (Stats) {
824 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
825 PP.PrintStats();
826 PP.getIdentifierTable().PrintStats();
827 HeaderInfo.PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +0000828 if (ClearSourceMgr)
829 SourceMgr.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000830 fprintf(stderr, "\n");
831 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000832
833 // For a multi-file compilation, some things are ok with nuking the source
834 // manager tables, other require stable fileid/macroid's across multiple
835 // files.
836 if (ClearSourceMgr) {
837 SourceMgr.clearIDTables();
838 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000839}
840
841static llvm::cl::list<std::string>
842InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
843
844
845int main(int argc, char **argv) {
846 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
847 llvm::sys::PrintStackTraceOnErrorSignal();
848
849 // If no input was specified, read from stdin.
850 if (InputFilenames.empty())
851 InputFilenames.push_back("-");
852
853 /// Create a SourceManager object. This tracks and owns all the file buffers
854 /// allocated to the program.
855 SourceManager SourceMgr;
856
857 // Create a file manager object to provide access to and cache the filesystem.
858 FileManager FileMgr;
859
860 // Initialize language options, inferring file types from input filenames.
861 // FIXME: This infers info from the first file, we should clump by language
862 // to handle 'x.c y.c a.cpp b.cpp'.
863 LangOptions LangInfo;
864 InitializeBaseLanguage(LangInfo, InputFilenames[0]);
865 InitializeLanguageStandard(LangInfo);
866
867 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000868 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000869 // Print diagnostics to stderr by default.
870 DiagClient.reset(new TextDiagnosticPrinter(SourceMgr));
871 } else {
872 // When checking diagnostics, just buffer them up.
873 DiagClient.reset(new TextDiagnosticBuffer(SourceMgr));
874
875 if (InputFilenames.size() != 1) {
876 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000877 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000878 return 1;
879 }
880 }
881
882 // Configure our handling of diagnostics.
883 Diagnostic Diags(*DiagClient);
884 InitializeDiagnostics(Diags);
885
886 // Get information about the targets being compiled for. Note that this
887 // pointer and the TargetInfoImpl objects are never deleted by this toy
888 // driver.
889 TargetInfo *Target = CreateTargetInfo(Diags);
890 if (Target == 0) {
891 fprintf(stderr,
892 "Sorry, don't know what target this is, please use -arch.\n");
893 exit(1);
894 }
895
896 // Process the -I options and set them in the HeaderInfo.
897 HeaderSearch HeaderInfo(FileMgr);
898 DiagClient->setHeaderSearch(HeaderInfo);
899 InitializeIncludePaths(HeaderInfo, FileMgr, Diags, LangInfo);
900
901 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
902 // Set up the preprocessor with these options.
903 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
904 DiagClient->setPreprocessor(PP);
905 const std::string &InFile = InputFilenames[i];
Chris Lattner53b0dab2007-10-09 22:10:18 +0000906 std::vector<char> PredefineBuffer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
908 HeaderInfo, LangInfo,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000909 PredefineBuffer);
Reid Spencer5f016e22007-07-11 17:01:13 +0000910
911 if (!MainFileID) continue;
912
913 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
914 *DiagClient, HeaderInfo, LangInfo);
915 HeaderInfo.ClearFileInfo();
916 }
917
918 unsigned NumDiagnostics = Diags.getNumDiagnostics();
919
920 if (NumDiagnostics)
921 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
922 (NumDiagnostics == 1 ? "" : "s"));
923
924 if (Stats) {
925 // Printed from high-to-low level.
926 SourceMgr.PrintStats();
927 FileMgr.PrintStats();
928 fprintf(stderr, "\n");
929 }
930
Chris Lattner96f1a642007-07-21 05:40:53 +0000931 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000932}