blob: fba375f353bfaf7d3f6c971bbca3ee3dff98129b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenek80d53372007-12-12 23:41:08 +000029#include "TranslationUnit.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000030#include "clang/Sema/ASTStreamer.h"
31#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000032#include "clang/Parse/Parser.h"
33#include "clang/Lex/HeaderSearch.h"
34#include "clang/Basic/FileManager.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/TargetInfo.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000038#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/MemoryBuffer.h"
40#include "llvm/System/Signals.h"
Ted Kremenek40499482007-12-03 22:06:55 +000041#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000042#include <memory>
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46// Global options.
47//===----------------------------------------------------------------------===//
48
49static llvm::cl::opt<bool>
50Verbose("v", llvm::cl::desc("Enable verbose output"));
51static llvm::cl::opt<bool>
52Stats("stats", llvm::cl::desc("Print performance metrics and statistics"));
53
54enum ProgActions {
Chris Lattnerb429ae42007-10-11 00:43:27 +000055 RewriteTest, // Rewriter testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000056 EmitLLVM, // Emit a .ll file.
Ted Kremenek397de012007-12-13 00:37:31 +000057 SerializeAST, // Emit a .ast file.
Chris Lattner4045a8a2007-10-11 00:18:28 +000058 ASTPrint, // Parse ASTs and print them.
59 ASTDump, // Parse ASTs and dump them.
60 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenek97f75312007-08-21 21:42:03 +000061 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000062 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremenekaa04c512007-09-06 00:17:54 +000063 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000064 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek0841c702007-09-25 18:37:20 +000065 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek0a03ce62007-09-17 20:49:30 +000066 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000067 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000068 ParsePrintCallbacks, // Parse and print each callback.
69 ParseSyntaxOnly, // Parse and perform semantic analysis.
70 ParseNoop, // Parse with noop callbacks.
71 RunPreprocessorOnly, // Just lex, no output.
72 PrintPreprocessedInput, // -E mode.
73 DumpTokens // Token dump mode.
74};
75
76static llvm::cl::opt<ProgActions>
77ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
78 llvm::cl::init(ParseSyntaxOnly),
79 llvm::cl::values(
80 clEnumValN(RunPreprocessorOnly, "Eonly",
81 "Just run preprocessor, no output (for timings)"),
82 clEnumValN(PrintPreprocessedInput, "E",
83 "Run preprocessor, emit preprocessed file"),
84 clEnumValN(DumpTokens, "dumptokens",
85 "Run preprocessor, dump internal rep of tokens"),
86 clEnumValN(ParseNoop, "parse-noop",
87 "Run parser with noop callbacks (for timings)"),
88 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
89 "Run parser and perform semantic analysis"),
90 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
91 "Run parser and print each callback invoked"),
Chris Lattner4045a8a2007-10-11 00:18:28 +000092 clEnumValN(ASTPrint, "ast-print",
93 "Build ASTs and then pretty-print them"),
94 clEnumValN(ASTDump, "ast-dump",
95 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +000096 clEnumValN(ASTView, "ast-view",
Chris Lattner4045a8a2007-10-11 00:18:28 +000097 "Build ASTs and view them with GraphViz."),
Ted Kremenek97f75312007-08-21 21:42:03 +000098 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000099 "Run parser, then build and print CFGs."),
100 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremenekaa04c512007-09-06 00:17:54 +0000101 "Run parser, then build and view CFGs with Graphviz."),
102 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek05334682007-09-06 21:26:58 +0000103 "Print results of live variable analysis."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000104 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremeneke805c4a2007-09-06 23:00:42 +0000105 "Flag warnings of stores to dead variables."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000106 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000107 "Flag warnings of uses of unitialized variables."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000108 clEnumValN(TestSerialization, "test-pickling",
109 "Run prototype serializtion code."),
Chris Lattner4b009652007-07-25 00:24:17 +0000110 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000111 "Build ASTs then convert to LLVM, emit .ll file"),
Ted Kremenek397de012007-12-13 00:37:31 +0000112 clEnumValN(SerializeAST, "serialize-ast",
113 "Build ASTs and emit .ast file"),
Chris Lattnerb429ae42007-10-11 00:43:27 +0000114 clEnumValN(RewriteTest, "rewrite-test",
115 "Playground for the code rewriter"),
Chris Lattner4b009652007-07-25 00:24:17 +0000116 clEnumValEnd));
117
Ted Kremenek10389cf2007-09-26 19:42:19 +0000118static llvm::cl::opt<bool>
119VerifyDiagnostics("verify",
120 llvm::cl::desc("Verify emitted diagnostics and warnings."));
121
Chris Lattner4b009652007-07-25 00:24:17 +0000122//===----------------------------------------------------------------------===//
123// Language Options
124//===----------------------------------------------------------------------===//
125
126enum LangKind {
127 langkind_unspecified,
128 langkind_c,
129 langkind_c_cpp,
130 langkind_cxx,
131 langkind_cxx_cpp,
132 langkind_objc,
133 langkind_objc_cpp,
134 langkind_objcxx,
135 langkind_objcxx_cpp
136};
137
138/* TODO: GCC also accepts:
139 c-header c++-header objective-c-header objective-c++-header
140 assembler assembler-with-cpp
141 ada, f77*, ratfor (!), f95, java, treelang
142 */
143static llvm::cl::opt<LangKind>
144BaseLang("x", llvm::cl::desc("Base language to compile"),
145 llvm::cl::init(langkind_unspecified),
146 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
147 clEnumValN(langkind_cxx, "c++", "C++"),
148 clEnumValN(langkind_objc, "objective-c", "Objective C"),
149 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
150 clEnumValN(langkind_c_cpp, "c-cpp-output",
151 "Preprocessed C"),
152 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
153 "Preprocessed C++"),
154 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
155 "Preprocessed Objective C"),
156 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
157 "Preprocessed Objective C++"),
158 clEnumValEnd));
159
160static llvm::cl::opt<bool>
161LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
162 llvm::cl::Hidden);
163static llvm::cl::opt<bool>
164LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
165 llvm::cl::Hidden);
166
Ted Kremenek11ad8952007-12-05 23:49:08 +0000167/// InitializeBaseLanguage - Handle the -x foo options.
168static void InitializeBaseLanguage() {
169 if (LangObjC)
170 BaseLang = langkind_objc;
171 else if (LangObjCXX)
172 BaseLang = langkind_objcxx;
173}
174
175static LangKind GetLanguage(const std::string &Filename) {
176 if (BaseLang != langkind_unspecified)
177 return BaseLang;
178
179 std::string::size_type DotPos = Filename.rfind('.');
180
181 if (DotPos == std::string::npos) {
182 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4b009652007-07-25 00:24:17 +0000183 }
184
Ted Kremenek11ad8952007-12-05 23:49:08 +0000185 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
186 // C header: .h
187 // C++ header: .hh or .H;
188 // assembler no preprocessing: .s
189 // assembler: .S
190 if (Ext == "c")
191 return langkind_c;
192 else if (Ext == "i")
193 return langkind_c_cpp;
194 else if (Ext == "ii")
195 return langkind_cxx_cpp;
196 else if (Ext == "m")
197 return langkind_objc;
198 else if (Ext == "mi")
199 return langkind_objc_cpp;
200 else if (Ext == "mm" || Ext == "M")
201 return langkind_objcxx;
202 else if (Ext == "mii")
203 return langkind_objcxx_cpp;
204 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
205 Ext == "c++" || Ext == "cp" || Ext == "cxx")
206 return langkind_cxx;
207 else
208 return langkind_c;
209}
210
211
212static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000213 // FIXME: implement -fpreprocessed mode.
214 bool NoPreprocess = false;
215
Ted Kremenek11ad8952007-12-05 23:49:08 +0000216 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000217 default: assert(0 && "Unknown language kind!");
218 case langkind_c_cpp:
219 NoPreprocess = true;
220 // FALLTHROUGH
221 case langkind_c:
222 break;
223 case langkind_cxx_cpp:
224 NoPreprocess = true;
225 // FALLTHROUGH
226 case langkind_cxx:
227 Options.CPlusPlus = 1;
228 break;
229 case langkind_objc_cpp:
230 NoPreprocess = true;
231 // FALLTHROUGH
232 case langkind_objc:
233 Options.ObjC1 = Options.ObjC2 = 1;
234 break;
235 case langkind_objcxx_cpp:
236 NoPreprocess = true;
237 // FALLTHROUGH
238 case langkind_objcxx:
239 Options.ObjC1 = Options.ObjC2 = 1;
240 Options.CPlusPlus = 1;
241 break;
242 }
243}
244
245/// LangStds - Language standards we support.
246enum LangStds {
247 lang_unspecified,
248 lang_c89, lang_c94, lang_c99,
249 lang_gnu89, lang_gnu99,
250 lang_cxx98, lang_gnucxx98,
251 lang_cxx0x, lang_gnucxx0x
252};
253
254static llvm::cl::opt<LangStds>
255LangStd("std", llvm::cl::desc("Language standard to compile for"),
256 llvm::cl::init(lang_unspecified),
257 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
258 clEnumValN(lang_c89, "c90", "ISO C 1990"),
259 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
260 clEnumValN(lang_c94, "iso9899:199409",
261 "ISO C 1990 with amendment 1"),
262 clEnumValN(lang_c99, "c99", "ISO C 1999"),
263// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
264 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
265// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
266 clEnumValN(lang_gnu89, "gnu89",
267 "ISO C 1990 with GNU extensions (default for C)"),
268 clEnumValN(lang_gnu99, "gnu99",
269 "ISO C 1999 with GNU extensions"),
270 clEnumValN(lang_gnu99, "gnu9x",
271 "ISO C 1999 with GNU extensions"),
272 clEnumValN(lang_cxx98, "c++98",
273 "ISO C++ 1998 with amendments"),
274 clEnumValN(lang_gnucxx98, "gnu++98",
275 "ISO C++ 1998 with amendments and GNU "
276 "extensions (default for C++)"),
277 clEnumValN(lang_cxx0x, "c++0x",
278 "Upcoming ISO C++ 200x with amendments"),
279 clEnumValN(lang_gnucxx0x, "gnu++0x",
280 "Upcoming ISO C++ 200x with amendments and GNU "
281 "extensions (default for C++)"),
282 clEnumValEnd));
283
284static llvm::cl::opt<bool>
285NoOperatorNames("fno-operator-names",
286 llvm::cl::desc("Do not treat C++ operator name keywords as "
287 "synonyms for operators"));
288
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000289static llvm::cl::opt<bool>
290PascalStrings("fpascal-strings",
291 llvm::cl::desc("Recognize and construct Pascal-style "
292 "string literals"));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000293
294static llvm::cl::opt<bool>
295WritableStrings("fwritable-strings",
296 llvm::cl::desc("Store string literals as writable data."));
Anders Carlssone87cd982007-11-30 04:21:22 +0000297
298static llvm::cl::opt<bool>
299LaxVectorConversions("flax-vector-conversions",
300 llvm::cl::desc("Allow implicit conversions between vectors"
301 " with a different number of elements or "
302 "different element types."));
Chris Lattner4b009652007-07-25 00:24:17 +0000303// FIXME: add:
304// -ansi
305// -trigraphs
306// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000307// -fpascal-strings
Ted Kremenek11ad8952007-12-05 23:49:08 +0000308static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000309 if (LangStd == lang_unspecified) {
310 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000311 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000312 default: assert(0 && "Unknown base language");
313 case langkind_c:
314 case langkind_c_cpp:
315 case langkind_objc:
316 case langkind_objc_cpp:
317 LangStd = lang_gnu99;
318 break;
319 case langkind_cxx:
320 case langkind_cxx_cpp:
321 case langkind_objcxx:
322 case langkind_objcxx_cpp:
323 LangStd = lang_gnucxx98;
324 break;
325 }
326 }
327
328 switch (LangStd) {
329 default: assert(0 && "Unknown language standard!");
330
331 // Fall through from newer standards to older ones. This isn't really right.
332 // FIXME: Enable specifically the right features based on the language stds.
333 case lang_gnucxx0x:
334 case lang_cxx0x:
335 Options.CPlusPlus0x = 1;
336 // FALL THROUGH
337 case lang_gnucxx98:
338 case lang_cxx98:
339 Options.CPlusPlus = 1;
340 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000341 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000342 // FALL THROUGH.
343 case lang_gnu99:
344 case lang_c99:
345 Options.Digraphs = 1;
346 Options.C99 = 1;
347 Options.HexFloats = 1;
348 // FALL THROUGH.
349 case lang_gnu89:
350 Options.BCPLComment = 1; // Only for C99/C++.
351 // FALL THROUGH.
352 case lang_c94:
353 case lang_c89:
354 break;
355 }
356
357 Options.Trigraphs = 1; // -trigraphs or -ansi
358 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000359 Options.PascalStrings = PascalStrings;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000360 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000361 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000362}
363
364//===----------------------------------------------------------------------===//
365// Our DiagnosticClient implementation
366//===----------------------------------------------------------------------===//
367
368// FIXME: Werror should take a list of things, -Werror=foo,bar
369static llvm::cl::opt<bool>
370WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
371
372static llvm::cl::opt<bool>
373WarnOnExtensions("pedantic", llvm::cl::init(false),
374 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
375
376static llvm::cl::opt<bool>
377ErrorOnExtensions("pedantic-errors",
378 llvm::cl::desc("Issue an error on uses of GCC extensions"));
379
380static llvm::cl::opt<bool>
381WarnUnusedMacros("Wunused_macros",
382 llvm::cl::desc("Warn for unused macros in the main translation unit"));
383
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000384static llvm::cl::opt<bool>
385WarnFloatEqual("Wfloat-equal",
386 llvm::cl::desc("Warn about equality comparisons of floating point values."));
387
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000388static llvm::cl::opt<bool>
389WarnNoFormatNonLiteral("Wno-format-nonliteral",
390 llvm::cl::desc("Do not warn about non-literal format strings."));
391
Chris Lattner4b009652007-07-25 00:24:17 +0000392/// InitializeDiagnostics - Initialize the diagnostic object, based on the
393/// current command line option settings.
394static void InitializeDiagnostics(Diagnostic &Diags) {
395 Diags.setWarningsAsErrors(WarningsAsErrors);
396 Diags.setWarnOnExtensions(WarnOnExtensions);
397 Diags.setErrorOnExtensions(ErrorOnExtensions);
398
399 // Silence the "macro is not used" warning unless requested.
400 if (!WarnUnusedMacros)
401 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000402
403 // Silence "floating point comparison" warnings unless requested.
404 if (!WarnFloatEqual)
405 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000406
407 // Silence "format string is not a string literal" warnings if requested
408 if (WarnNoFormatNonLiteral)
409 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant, diag::MAP_IGNORE);
410
Chris Lattner4b009652007-07-25 00:24:17 +0000411}
412
413//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000414// Target Triple Processing.
415//===----------------------------------------------------------------------===//
416
417static llvm::cl::opt<std::string>
418TargetTriple("triple",
419 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
420
421static llvm::cl::list<std::string>
422Archs("arch",
423 llvm::cl::desc("Specify target architecture (e.g. i686)."));
424
425namespace {
426 class TripleProcessor {
427 llvm::StringMap<char> TriplesProcessed;
428 std::vector<std::string>& triples;
429 public:
430 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
431
432 void addTriple(const std::string& t) {
433 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
434 TriplesProcessed.end()) {
435 triples.push_back(t);
436 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
437 }
438 }
439 };
440}
441
442static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenek40499482007-12-03 22:06:55 +0000443 // Initialize base triple. If a -triple option has been specified, use
444 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000445 std::string Triple = TargetTriple;
446 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000447
448 // Decompose the base triple into "arch" and suffix.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000449 std::string::size_type firstDash = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000450
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000451 if (firstDash == std::string::npos) {
452 fprintf(stderr,
453 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner210c0cc2007-12-12 05:01:48 +0000454 Triple.c_str());
455 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000456 }
Ted Kremenek40499482007-12-03 22:06:55 +0000457
Chris Lattner210c0cc2007-12-12 05:01:48 +0000458 std::string suffix(Triple, firstDash+1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000459
460 if (suffix.empty()) {
Chris Lattner210c0cc2007-12-12 05:01:48 +0000461 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
462 Triple.c_str());
463 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000464 }
Ted Kremenek40499482007-12-03 22:06:55 +0000465
466 // Create triple cacher.
467 TripleProcessor tp(triples);
468
469 // Add the primary triple to our set of triples if we are using the
470 // host-triple with no archs or using a specified target triple.
471 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner210c0cc2007-12-12 05:01:48 +0000472 tp.addTriple(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000473
474 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
475 tp.addTriple(Archs[i] + "-" + suffix);
476}
477
478//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000479// Preprocessor Initialization
480//===----------------------------------------------------------------------===//
481
482// FIXME: Preprocessor builtins to support.
483// -A... - Play with #assertions
484// -undef - Undefine all predefined macros
485
486static llvm::cl::list<std::string>
487D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
488 llvm::cl::desc("Predefine the specified macro"));
489static llvm::cl::list<std::string>
490U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
491 llvm::cl::desc("Undefine the specified macro"));
492
493// Append a #define line to Buf for Macro. Macro should be of the form XXX,
494// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
495// "#define XXX Y z W". To get a #define with no value, use "XXX=".
496static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
497 const char *Command = "#define ") {
498 Buf.insert(Buf.end(), Command, Command+strlen(Command));
499 if (const char *Equal = strchr(Macro, '=')) {
500 // Turn the = into ' '.
501 Buf.insert(Buf.end(), Macro, Equal);
502 Buf.push_back(' ');
503 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
504 } else {
505 // Push "macroname 1".
506 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
507 Buf.push_back(' ');
508 Buf.push_back('1');
509 }
510 Buf.push_back('\n');
511}
512
Chris Lattner4b009652007-07-25 00:24:17 +0000513
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000514/// InitializePreprocessor - Initialize the preprocessor getting it and the
515/// environment ready to process a single file. This returns the file ID for the
516/// input file. If a failure happens, it returns 0.
517///
518static unsigned InitializePreprocessor(Preprocessor &PP,
519 const std::string &InFile,
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000520 std::vector<char> &PredefineBuffer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000521
Chris Lattner968982d2007-12-15 20:48:40 +0000522 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000523
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000524 // Figure out where to get and map in the main file.
525 unsigned MainFileID = 0;
Chris Lattner968982d2007-12-15 20:48:40 +0000526 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000527 if (InFile != "-") {
528 const FileEntry *File = FileMgr.getFile(InFile);
529 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
530 if (MainFileID == 0) {
531 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
532 return 0;
533 }
534 } else {
535 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
536 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
537 if (MainFileID == 0) {
538 fprintf(stderr, "Error reading standard input! Empty?\n");
539 return 0;
540 }
Chris Lattner4b009652007-07-25 00:24:17 +0000541 }
542
Chris Lattner4b009652007-07-25 00:24:17 +0000543 // Add macros from the command line.
544 // FIXME: Should traverse the #define/#undef lists in parallel.
545 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000546 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000547 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000548 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
549
550 // FIXME: Read any files specified by -imacros or -include.
551
552 // Null terminate PredefinedBuffer and add it.
553 PredefineBuffer.push_back(0);
554 PP.setPredefines(&PredefineBuffer[0]);
555
556 // Once we've read this, we're done.
557 return MainFileID;
Chris Lattner4b009652007-07-25 00:24:17 +0000558}
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000559
560
Chris Lattner4b009652007-07-25 00:24:17 +0000561
562//===----------------------------------------------------------------------===//
563// Preprocessor include path information.
564//===----------------------------------------------------------------------===//
565
566// This tool exports a large number of command line options to control how the
567// preprocessor searches for header files. At root, however, the Preprocessor
568// object takes a very simple interface: a list of directories to search for
569//
570// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000571// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000572//
573// FIXME: -include,-imacros
574
575static llvm::cl::opt<bool>
576nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
577
578// Various command line options. These four add directories to each chain.
579static llvm::cl::list<std::string>
580F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
581 llvm::cl::desc("Add directory to framework include search path"));
582static llvm::cl::list<std::string>
583I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
584 llvm::cl::desc("Add directory to include search path"));
585static llvm::cl::list<std::string>
586idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
587 llvm::cl::desc("Add directory to AFTER include search path"));
588static llvm::cl::list<std::string>
589iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
590 llvm::cl::desc("Add directory to QUOTE include search path"));
591static llvm::cl::list<std::string>
592isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
593 llvm::cl::desc("Add directory to SYSTEM include search path"));
594
595// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
596static llvm::cl::list<std::string>
597iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
598 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
599static llvm::cl::list<std::string>
600iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
601 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
602static llvm::cl::list<std::string>
603iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
604 llvm::cl::Prefix,
605 llvm::cl::desc("Set directory to include search path with prefix"));
606
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000607static llvm::cl::opt<std::string>
608isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
609 llvm::cl::desc("Set the system root directory (usually /)"));
610
Chris Lattner4b009652007-07-25 00:24:17 +0000611// Finally, implement the code that groks the options above.
612enum IncludeDirGroup {
613 Quoted = 0,
614 Angled,
615 System,
616 After
617};
618
619static std::vector<DirectoryLookup> IncludeGroup[4];
620
621/// AddPath - Add the specified path to the specified group list.
622///
623static void AddPath(const std::string &Path, IncludeDirGroup Group,
624 bool isCXXAware, bool isUserSupplied,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000625 bool isFramework, HeaderSearch &HS) {
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000626 assert(!Path.empty() && "can't handle empty path here");
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000627 FileManager &FM = HS.getFileMgr();
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000628
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000629 // Compute the actual path, taking into consideration -isysroot.
630 llvm::SmallString<256> MappedPath;
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000631
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000632 // Handle isysroot.
633 if (Group == System) {
Chris Lattner2a2702a2007-12-17 06:51:34 +0000634 // FIXME: Portability. This should be a sys::Path interface, this doesn't
635 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000636 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
637 MappedPath.append(isysroot.begin(), isysroot.end());
638 if (Path[0] != '/') // If in the system group, add a /.
639 MappedPath.push_back('/');
Chris Lattner4b009652007-07-25 00:24:17 +0000640 }
641
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000642 MappedPath.append(Path.begin(), Path.end());
643
644 // Compute the DirectoryLookup type.
Chris Lattner4b009652007-07-25 00:24:17 +0000645 DirectoryLookup::DirType Type;
646 if (Group == Quoted || Group == Angled)
647 Type = DirectoryLookup::NormalHeaderDir;
648 else if (isCXXAware)
649 Type = DirectoryLookup::SystemHeaderDir;
650 else
651 Type = DirectoryLookup::ExternCSystemHeaderDir;
652
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000653
654 // If the directory exists, add it.
655 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
656 &MappedPath[0]+
657 MappedPath.size())) {
658 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
659 isFramework));
660 return;
661 }
662
Chris Lattnerb7426782007-12-17 07:52:39 +0000663 // Check to see if this is an apple-style headermap (which are not allowed to
664 // be frameworks).
665 if (!isFramework) {
666 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
667 &MappedPath[0]+MappedPath.size())) {
668 std::string ErrorInfo;
669 const HeaderMap *HM = HS.CreateHeaderMap(FE, ErrorInfo);
670 if (HM) {
671 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
672 return;
673 }
674
675 // If this looked like a headermap but was corrupted, emit that error,
676 // otherwise treat it as a missing directory.
677 if (!ErrorInfo.empty()) {
678 fprintf(stderr, "%s\n", ErrorInfo.c_str());
679 return;
680 }
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000681 }
682 }
683
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000684 if (Verbose)
685 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000686}
687
688/// RemoveDuplicates - If there are duplicate directory entries in the specified
689/// search list, remove the later (dead) ones.
690static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattnerac139d22007-12-15 23:20:07 +0000691 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerb7426782007-12-17 07:52:39 +0000692 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnercf33e932007-12-17 06:44:29 +0000693 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Chris Lattner4b009652007-07-25 00:24:17 +0000694 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnercf33e932007-12-17 06:44:29 +0000695 if (SearchList[i].isNormalDir()) {
696 // If this isn't the first time we've seen this dir, remove it.
697 if (SeenDirs.insert(SearchList[i].getDir()))
698 continue;
699
Chris Lattner4b009652007-07-25 00:24:17 +0000700 if (Verbose)
701 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
702 SearchList[i].getDir()->getName());
Chris Lattnerb7426782007-12-17 07:52:39 +0000703 } else if (SearchList[i].isFramework()) {
704 // If this isn't the first time we've seen this framework dir, remove it.
705 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
706 continue;
707
708 if (Verbose)
709 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
710 SearchList[i].getFrameworkDir()->getName());
711
Chris Lattnercf33e932007-12-17 06:44:29 +0000712 } else {
713 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
714 // If this isn't the first time we've seen this headermap, remove it.
715 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
716 continue;
717
718 if (Verbose)
719 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
720 SearchList[i].getDir()->getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000721 }
Chris Lattnercf33e932007-12-17 06:44:29 +0000722
723 // This is reached if the current entry is a duplicate.
724 SearchList.erase(SearchList.begin()+i);
725 --i;
Chris Lattner4b009652007-07-25 00:24:17 +0000726 }
727}
728
729/// InitializeIncludePaths - Process the -I options and set them in the
730/// HeaderSearch object.
731static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner45a56e02007-12-05 23:24:17 +0000732 const LangOptions &Lang) {
Chris Lattner4b009652007-07-25 00:24:17 +0000733 // Handle -F... options.
734 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000735 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000736
737 // Handle -I... options.
Chris Lattner45a56e02007-12-05 23:24:17 +0000738 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000739 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000740
741 // Handle -idirafter... options.
742 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000743 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000744
745 // Handle -iquote... options.
746 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000747 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000748
749 // Handle -isystem... options.
750 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000751 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000752
753 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
754 // parallel, processing the values in order of occurance to get the right
755 // prefixes.
756 {
757 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
758 unsigned iprefix_idx = 0;
759 unsigned iwithprefix_idx = 0;
760 unsigned iwithprefixbefore_idx = 0;
761 bool iprefix_done = iprefix_vals.empty();
762 bool iwithprefix_done = iwithprefix_vals.empty();
763 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
764 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
765 if (!iprefix_done &&
766 (iwithprefix_done ||
767 iprefix_vals.getPosition(iprefix_idx) <
768 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
769 (iwithprefixbefore_done ||
770 iprefix_vals.getPosition(iprefix_idx) <
771 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
772 Prefix = iprefix_vals[iprefix_idx];
773 ++iprefix_idx;
774 iprefix_done = iprefix_idx == iprefix_vals.size();
775 } else if (!iwithprefix_done &&
776 (iwithprefixbefore_done ||
777 iwithprefix_vals.getPosition(iwithprefix_idx) <
778 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
779 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000780 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000781 ++iwithprefix_idx;
782 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
783 } else {
784 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000785 Angled, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000786 ++iwithprefixbefore_idx;
787 iwithprefixbefore_done =
788 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
789 }
790 }
791 }
792
793 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
794 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
795
796 // FIXME: temporary hack: hard-coded paths.
797 // FIXME: get these from the target?
798 if (!nostdinc) {
799 if (Lang.CPlusPlus) {
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000800 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000801 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000802 false, Headers);
803 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
804 Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000805 }
806
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000807 AddPath("/usr/local/include", System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000808 // leopard
809 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000810 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000811 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000812 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000813 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
814 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000815 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000816
817 // tiger
818 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000819 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000820 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000821 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000822 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
823 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000824 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000825
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000826 AddPath("/usr/include", System, false, false, false, Headers);
827 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
828 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000829 }
830
831 // Now that we have collected all of the include paths, merge them all
832 // together and tell the preprocessor about them.
833
834 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
835 std::vector<DirectoryLookup> SearchList;
836 SearchList = IncludeGroup[Angled];
837 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
838 IncludeGroup[System].end());
839 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
840 IncludeGroup[After].end());
841 RemoveDuplicates(SearchList);
842 RemoveDuplicates(IncludeGroup[Quoted]);
843
844 // Prepend QUOTED list on the search list.
845 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
846 IncludeGroup[Quoted].end());
847
848
849 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
850 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
851 DontSearchCurDir);
852
853 // If verbose, print the list of directories that will be searched.
854 if (Verbose) {
855 fprintf(stderr, "#include \"...\" search starts here:\n");
856 unsigned QuotedIdx = IncludeGroup[Quoted].size();
857 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
858 if (i == QuotedIdx)
859 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner0f64f652007-12-17 17:42:26 +0000860 if (SearchList[i].isNormalDir())
861 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
862 else if (SearchList[i].isFramework())
863 fprintf(stderr, " %s (framework directory)\n",
864 SearchList[i].getFrameworkDir()->getName());
865 else {
866 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
867 //fprintf(stderr, " %s (headermap)\n",
868 // SearchList[i].getHeaderMap()->getName());
869 }
Chris Lattner4b009652007-07-25 00:24:17 +0000870 }
Chris Lattnerac553842007-12-15 23:11:06 +0000871 fprintf(stderr, "End of search list.\n");
Chris Lattner4b009652007-07-25 00:24:17 +0000872 }
873}
874
875
Chris Lattner4b009652007-07-25 00:24:17 +0000876//===----------------------------------------------------------------------===//
877// Basic Parser driver
878//===----------------------------------------------------------------------===//
879
880static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
881 Parser P(PP, *PA);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000882 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000883
884 // Parsing the specified input file.
885 P.ParseTranslationUnit();
886 delete PA;
887}
888
889//===----------------------------------------------------------------------===//
890// Main driver
891//===----------------------------------------------------------------------===//
892
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000893/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
894/// action. These consumers can operate on both ASTs that are freshly
895/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenek397de012007-12-13 00:37:31 +0000896static ASTConsumer* CreateASTConsumer(const std::string& InFile,
897 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000898 const LangOptions& LangOpts) {
899 switch (ProgAction) {
900 default:
901 return NULL;
902
903 case ASTPrint:
904 return CreateASTPrinter();
905
906 case ASTDump:
907 return CreateASTDumper();
908
909 case ASTView:
910 return CreateASTViewer();
911
912 case ParseCFGDump:
913 case ParseCFGView:
914 return CreateCFGDumper(ProgAction == ParseCFGView);
915
916 case AnalysisLiveVariables:
917 return CreateLiveVarAnalyzer();
918
919 case WarnDeadStores:
920 return CreateDeadStoreChecker(Diag);
921
922 case WarnUninitVals:
923 return CreateUnitValsChecker(Diag);
924
925 case TestSerialization:
Ted Kremenek2939b8a2007-12-05 21:34:36 +0000926 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000927
928 case EmitLLVM:
929 return CreateLLVMEmitter(Diag, LangOpts);
930
Ted Kremenek397de012007-12-13 00:37:31 +0000931 case SerializeAST: {
932 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek8df2a4d2007-12-13 17:50:11 +0000933 // FIXME: This is a hack: "/" separator not portable.
934 std::string::size_type idx = InFile.rfind("/");
Ted Kremenek397de012007-12-13 00:37:31 +0000935
Ted Kremenek8df2a4d2007-12-13 17:50:11 +0000936 if (idx != std::string::npos && idx == InFile.size()-1)
Ted Kremenek397de012007-12-13 00:37:31 +0000937 return NULL;
Ted Kremenek8df2a4d2007-12-13 17:50:11 +0000938
939 std::string TargetPrefix( idx == std::string::npos ?
940 InFile : InFile.substr(idx+1));
941
942 llvm::sys::Path FName = llvm::sys::Path((TargetPrefix + ".ast").c_str());
Ted Kremenek397de012007-12-13 00:37:31 +0000943
944 return CreateASTSerializer(FName, Diag, LangOpts);
945 }
946
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000947 case RewriteTest:
948 return CreateCodeRewriterTest(Diag);
949 }
950}
951
Chris Lattner4b009652007-07-25 00:24:17 +0000952/// ProcessInputFile - Process a single input file with the specified state.
953///
954static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
955 const std::string &InFile,
Chris Lattner968982d2007-12-15 20:48:40 +0000956 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenek6856c632007-09-26 18:39:29 +0000957
958 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +0000959 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +0000960
Chris Lattner4b009652007-07-25 00:24:17 +0000961 switch (ProgAction) {
962 default:
Ted Kremenek397de012007-12-13 00:37:31 +0000963 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
Chris Lattner968982d2007-12-15 20:48:40 +0000964 PP.getFileManager(),
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000965 PP.getLangOptions());
966
967 if (!Consumer) {
968 fprintf(stderr, "Unexpected program action!\n");
969 return;
970 }
971 break;
972
Chris Lattner4b009652007-07-25 00:24:17 +0000973 case DumpTokens: { // Token dump mode.
974 Token Tok;
975 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000976 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000977 do {
978 PP.Lex(Tok);
979 PP.DumpToken(Tok, true);
980 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +0000981 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000982 ClearSourceMgr = true;
983 break;
984 }
985 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
986 Token Tok;
987 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000988 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000989 do {
990 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +0000991 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000992 ClearSourceMgr = true;
993 break;
994 }
995
996 case PrintPreprocessedInput: // -E mode.
Chris Lattner968982d2007-12-15 20:48:40 +0000997 DoPrintPreprocessedInput(MainFileID, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000998 ClearSourceMgr = true;
999 break;
1000
1001 case ParseNoop: // -parse-noop
Steve Naroffebeb4282007-10-31 20:55:39 +00001002 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +00001003 ClearSourceMgr = true;
1004 break;
1005
1006 case ParsePrintCallbacks:
Steve Naroffebeb4282007-10-31 20:55:39 +00001007 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
1008 MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +00001009 ClearSourceMgr = true;
1010 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001011
Ted Kremenek6856c632007-09-26 18:39:29 +00001012 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +00001013 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001014 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001015 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001016
1017 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001018 if (VerifyDiagnostics)
Chris Lattner8593cbf2007-11-03 06:24:16 +00001019 exit(CheckASTConsumer(PP, MainFileID, Consumer));
1020
1021 // This deletes Consumer.
1022 ParseAST(PP, MainFileID, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001023 }
1024
1025 if (Stats) {
1026 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
1027 PP.PrintStats();
1028 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001029 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001030 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001031 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001032 fprintf(stderr, "\n");
1033 }
1034
1035 // For a multi-file compilation, some things are ok with nuking the source
1036 // manager tables, other require stable fileid/macroid's across multiple
1037 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001038 if (ClearSourceMgr)
1039 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001040}
1041
Ted Kremenek80d53372007-12-12 23:41:08 +00001042static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1043 FileManager& FileMgr) {
1044
1045 if (VerifyDiagnostics) {
1046 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1047 exit (1);
1048 }
1049
1050 llvm::sys::Path Filename(InFile);
1051
1052 if (!Filename.isValid()) {
1053 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1054 exit (1);
1055 }
1056
Ted Kremenek2bd42412007-12-13 18:11:11 +00001057 TranslationUnit* TU = TranslationUnit::ReadBitcodeFile(Filename,FileMgr);
1058
1059 if (!TU) {
1060 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1061 InFile.c_str());
1062 exit (1);
1063 }
1064
Ted Kremenek397de012007-12-13 00:37:31 +00001065 ASTConsumer* Consumer = CreateASTConsumer(InFile,Diag,
1066 FileMgr,TU->getLangOpts());
Ted Kremenek80d53372007-12-12 23:41:08 +00001067
1068 if (!Consumer) {
1069 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1070 exit (1);
1071 }
1072
1073 // FIXME: only work on consumers that do not require MainFileID.
1074 Consumer->Initialize(*TU->getContext(),0);
1075
1076 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1077 Consumer->HandleTopLevelDecl(*I);
1078
1079 delete Consumer;
1080}
1081
1082
Chris Lattner4b009652007-07-25 00:24:17 +00001083static llvm::cl::list<std::string>
1084InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1085
Ted Kremenek80d53372007-12-12 23:41:08 +00001086static bool isSerializedFile(const std::string& InFile) {
1087 if (InFile.size() < 4)
1088 return false;
1089
1090 const char* s = InFile.c_str()+InFile.size()-4;
1091
1092 return s[0] == '.' &&
1093 s[1] == 'a' &&
1094 s[2] == 's' &&
1095 s[3] == 't';
1096}
1097
Chris Lattner4b009652007-07-25 00:24:17 +00001098
1099int main(int argc, char **argv) {
1100 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1101 llvm::sys::PrintStackTraceOnErrorSignal();
1102
1103 // If no input was specified, read from stdin.
1104 if (InputFilenames.empty())
1105 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001106
Chris Lattner4b009652007-07-25 00:24:17 +00001107 // Create a file manager object to provide access to and cache the filesystem.
1108 FileManager FileMgr;
1109
Ted Kremenekb240e822007-12-11 23:28:38 +00001110 // Create the diagnostic client for reporting errors or for
1111 // implementing -verify.
Chris Lattner4b009652007-07-25 00:24:17 +00001112 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek56b70862007-09-26 20:14:22 +00001113 if (!VerifyDiagnostics) {
Chris Lattner4b009652007-07-25 00:24:17 +00001114 // Print diagnostics to stderr by default.
Ted Kremenekb3ee1932007-12-11 21:27:55 +00001115 DiagClient.reset(new TextDiagnosticPrinter());
Chris Lattner4b009652007-07-25 00:24:17 +00001116 } else {
1117 // When checking diagnostics, just buffer them up.
Ted Kremenekb3ee1932007-12-11 21:27:55 +00001118 DiagClient.reset(new TextDiagnosticBuffer());
Chris Lattner4b009652007-07-25 00:24:17 +00001119
1120 if (InputFilenames.size() != 1) {
1121 fprintf(stderr,
Ted Kremenek56b70862007-09-26 20:14:22 +00001122 "-verify only works on single input files for now.\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001123 return 1;
1124 }
1125 }
1126
1127 // Configure our handling of diagnostics.
1128 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +00001129 InitializeDiagnostics(Diags);
1130
Chris Lattner45a56e02007-12-05 23:24:17 +00001131 // -I- is a deprecated GCC feature, scan for it and reject it.
1132 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1133 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001134 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001135 I_dirs.erase(I_dirs.begin()+i);
1136 --i;
1137 }
1138 }
1139
Chris Lattner4b009652007-07-25 00:24:17 +00001140 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001141 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001142
Ted Kremenek80d53372007-12-12 23:41:08 +00001143 if (isSerializedFile(InFile))
1144 ProcessSerializedFile(InFile,Diags,FileMgr);
1145 else {
1146 /// Create a SourceManager object. This tracks and owns all the file
1147 /// buffers allocated to a translation unit.
1148 SourceManager SourceMgr;
Ted Kremenekb240e822007-12-11 23:28:38 +00001149
Ted Kremenek80d53372007-12-12 23:41:08 +00001150 // Initialize language options, inferring file types from input filenames.
1151 LangOptions LangInfo;
1152 InitializeBaseLanguage();
1153 LangKind LK = GetLanguage(InFile);
1154 InitializeLangOptions(LangInfo, LK);
1155 InitializeLanguageStandard(LangInfo, LK);
1156
1157 // Process the -I options and set them in the HeaderInfo.
1158 HeaderSearch HeaderInfo(FileMgr);
1159 DiagClient->setHeaderSearch(HeaderInfo);
1160 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1161
1162 // Get information about the targets being compiled for. Note that this
1163 // pointer and the TargetInfoImpl objects are never deleted by this toy
1164 // driver.
1165 TargetInfo *Target;
1166
1167 // Create triples, and create the TargetInfo.
1168 std::vector<std::string> triples;
1169 CreateTargetTriples(triples);
1170 Target = TargetInfo::CreateTargetInfo(&triples[0],
1171 &triples[0]+triples.size(),
1172 &Diags);
1173
1174 if (Target == 0) {
1175 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1176 triples[0].c_str());
1177 fprintf(stderr, "Please use -triple or -arch.\n");
1178 exit(1);
1179 }
1180
1181 // Set up the preprocessor with these options.
1182 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1183
1184 std::vector<char> PredefineBuffer;
Chris Lattner968982d2007-12-15 20:48:40 +00001185 unsigned MainFileID = InitializePreprocessor(PP, InFile, PredefineBuffer);
Ted Kremenek80d53372007-12-12 23:41:08 +00001186
1187 if (!MainFileID) continue;
Chris Lattner4b009652007-07-25 00:24:17 +00001188
Chris Lattner968982d2007-12-15 20:48:40 +00001189 ProcessInputFile(PP, MainFileID, InFile, *DiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001190
1191 HeaderInfo.ClearFileInfo();
1192
1193 if (Stats)
1194 SourceMgr.PrintStats();
1195 }
Chris Lattner4b009652007-07-25 00:24:17 +00001196 }
1197
1198 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1199
1200 if (NumDiagnostics)
1201 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1202 (NumDiagnostics == 1 ? "" : "s"));
1203
1204 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001205 FileMgr.PrintStats();
1206 fprintf(stderr, "\n");
1207 }
1208
1209 return Diags.getNumErrors() != 0;
1210}