blob: 80d6c241b7e2b13d2bdb167bec48deaa14a57f1c [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"
Ted Kremenek77cda502007-12-18 21:34:28 +000029#include "clang/AST/TranslationUnit.h"
Chris Lattner556beb72007-09-15 22:56:56 +000030#include "clang/Sema/ASTStreamer.h"
31#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner8f3dab82007-12-15 23:20:07 +000037#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/MemoryBuffer.h"
40#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000041#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner77cd2a02007-10-11 00:43:27 +000055 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000056 EmitLLVM, // Emit a .ll file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000057 SerializeAST, // Emit a .ast file.
Chris Lattner3b427b32007-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 Kremenekfddd5182007-08-21 21:42:03 +000061 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000062 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000063 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek055c2752007-09-06 23:00:42 +000064 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000065 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000066 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000067 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner3b427b32007-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 Lattnerea254db2007-10-11 00:37:43 +000096 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +000097 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +000098 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +000099 "Run parser, then build and print CFGs."),
100 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000101 "Run parser, then build and view CFGs with Graphviz."),
102 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000103 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000104 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000105 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000106 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000107 "Flag warnings of uses of unitialized variables."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000108 clEnumValN(TestSerialization, "test-pickling",
109 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000111 "Build ASTs then convert to LLVM, emit .ll file"),
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000112 clEnumValN(SerializeAST, "serialize-ast",
113 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000114 clEnumValN(RewriteTest, "rewrite-test",
115 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 clEnumValEnd));
117
Ted Kremenek41193e42007-09-26 19:42:19 +0000118static llvm::cl::opt<bool>
119VerifyDiagnostics("verify",
120 llvm::cl::desc("Verify emitted diagnostics and warnings."));
121
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek8904f152007-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.
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 }
184
Ted Kremenek8904f152007-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) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 // FIXME: implement -fpreprocessed mode.
214 bool NoPreprocess = false;
215
Ted Kremenek8904f152007-12-05 23:49:08 +0000216 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +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,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000250 lang_cxx98, lang_gnucxx98,
251 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000252};
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++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000277 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++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 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 Carlssonee98ac52007-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 Lattner45e8cbd2007-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 Carlsson695dbb62007-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."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000303// FIXME: add:
304// -ansi
305// -trigraphs
306// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000307// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000308static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 if (LangStd == lang_unspecified) {
310 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000311 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +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.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000333 case lang_gnucxx0x:
334 case lang_cxx0x:
335 Options.CPlusPlus0x = 1;
336 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 case lang_gnucxx98:
338 case lang_cxx98:
339 Options.CPlusPlus = 1;
340 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000341 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +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 Carlssonee98ac52007-10-15 02:50:23 +0000359 Options.PascalStrings = PascalStrings;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000360 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000361 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenekdb87bca2007-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 Kremenek73da5902007-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
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenekdb87bca2007-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 Kremenek73da5902007-12-17 17:50:07 +0000406
407 // Silence "format string is not a string literal" warnings if requested
408 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000409 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
410 diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412}
413
414//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000415// Target Triple Processing.
416//===----------------------------------------------------------------------===//
417
418static llvm::cl::opt<std::string>
419TargetTriple("triple",
420 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
421
422static llvm::cl::list<std::string>
423Archs("arch",
424 llvm::cl::desc("Specify target architecture (e.g. i686)."));
425
426namespace {
427 class TripleProcessor {
428 llvm::StringMap<char> TriplesProcessed;
429 std::vector<std::string>& triples;
430 public:
431 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
432
433 void addTriple(const std::string& t) {
434 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
435 TriplesProcessed.end()) {
436 triples.push_back(t);
437 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
438 }
439 }
440 };
441}
442
443static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000444 // Initialize base triple. If a -triple option has been specified, use
445 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000446 std::string Triple = TargetTriple;
447 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000448
449 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000450 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000451
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000452 if (firstDash == std::string::npos) {
453 fprintf(stderr,
454 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000455 Triple.c_str());
456 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000457 }
Ted Kremenekae360762007-12-03 22:06:55 +0000458
Chris Lattner6590d212007-12-12 05:01:48 +0000459 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000460
461 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000462 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
463 Triple.c_str());
464 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000465 }
Ted Kremenekae360762007-12-03 22:06:55 +0000466
467 // Create triple cacher.
468 TripleProcessor tp(triples);
469
470 // Add the primary triple to our set of triples if we are using the
471 // host-triple with no archs or using a specified target triple.
472 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000473 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000474
475 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
476 tp.addTriple(Archs[i] + "-" + suffix);
477}
478
479//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000480// Preprocessor Initialization
481//===----------------------------------------------------------------------===//
482
483// FIXME: Preprocessor builtins to support.
484// -A... - Play with #assertions
485// -undef - Undefine all predefined macros
486
487static llvm::cl::list<std::string>
488D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
489 llvm::cl::desc("Predefine the specified macro"));
490static llvm::cl::list<std::string>
491U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
492 llvm::cl::desc("Undefine the specified macro"));
493
494// Append a #define line to Buf for Macro. Macro should be of the form XXX,
495// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
496// "#define XXX Y z W". To get a #define with no value, use "XXX=".
497static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
498 const char *Command = "#define ") {
499 Buf.insert(Buf.end(), Command, Command+strlen(Command));
500 if (const char *Equal = strchr(Macro, '=')) {
501 // Turn the = into ' '.
502 Buf.insert(Buf.end(), Macro, Equal);
503 Buf.push_back(' ');
504 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
505 } else {
506 // Push "macroname 1".
507 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
508 Buf.push_back(' ');
509 Buf.push_back('1');
510 }
511 Buf.push_back('\n');
512}
513
Reid Spencer5f016e22007-07-11 17:01:13 +0000514
Chris Lattner53b0dab2007-10-09 22:10:18 +0000515/// InitializePreprocessor - Initialize the preprocessor getting it and the
516/// environment ready to process a single file. This returns the file ID for the
517/// input file. If a failure happens, it returns 0.
518///
519static unsigned InitializePreprocessor(Preprocessor &PP,
520 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000521 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000522
Chris Lattnerdee73592007-12-15 20:48:40 +0000523 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000524
Chris Lattner53b0dab2007-10-09 22:10:18 +0000525 // Figure out where to get and map in the main file.
526 unsigned MainFileID = 0;
Chris Lattnerdee73592007-12-15 20:48:40 +0000527 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000528 if (InFile != "-") {
529 const FileEntry *File = FileMgr.getFile(InFile);
530 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
531 if (MainFileID == 0) {
532 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
533 return 0;
534 }
535 } else {
536 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
537 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
538 if (MainFileID == 0) {
539 fprintf(stderr, "Error reading standard input! Empty?\n");
540 return 0;
541 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 }
543
Reid Spencer5f016e22007-07-11 17:01:13 +0000544 // Add macros from the command line.
545 // FIXME: Should traverse the #define/#undef lists in parallel.
546 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000547 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000549 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
550
551 // FIXME: Read any files specified by -imacros or -include.
552
553 // Null terminate PredefinedBuffer and add it.
554 PredefineBuffer.push_back(0);
555 PP.setPredefines(&PredefineBuffer[0]);
556
557 // Once we've read this, we're done.
558 return MainFileID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000559}
Chris Lattner53b0dab2007-10-09 22:10:18 +0000560
561
Reid Spencer5f016e22007-07-11 17:01:13 +0000562
563//===----------------------------------------------------------------------===//
564// Preprocessor include path information.
565//===----------------------------------------------------------------------===//
566
567// This tool exports a large number of command line options to control how the
568// preprocessor searches for header files. At root, however, the Preprocessor
569// object takes a very simple interface: a list of directories to search for
570//
571// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000572// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000573//
574// FIXME: -include,-imacros
575
576static llvm::cl::opt<bool>
577nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
578
579// Various command line options. These four add directories to each chain.
580static llvm::cl::list<std::string>
581F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
582 llvm::cl::desc("Add directory to framework include search path"));
583static llvm::cl::list<std::string>
584I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
585 llvm::cl::desc("Add directory to include search path"));
586static llvm::cl::list<std::string>
587idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
588 llvm::cl::desc("Add directory to AFTER include search path"));
589static llvm::cl::list<std::string>
590iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
591 llvm::cl::desc("Add directory to QUOTE include search path"));
592static llvm::cl::list<std::string>
593isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
594 llvm::cl::desc("Add directory to SYSTEM include search path"));
595
596// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
597static llvm::cl::list<std::string>
598iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
599 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
600static llvm::cl::list<std::string>
601iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
602 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
603static llvm::cl::list<std::string>
604iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
605 llvm::cl::Prefix,
606 llvm::cl::desc("Set directory to include search path with prefix"));
607
Chris Lattner0c946412007-08-26 17:47:35 +0000608static llvm::cl::opt<std::string>
609isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
610 llvm::cl::desc("Set the system root directory (usually /)"));
611
Reid Spencer5f016e22007-07-11 17:01:13 +0000612// Finally, implement the code that groks the options above.
613enum IncludeDirGroup {
614 Quoted = 0,
615 Angled,
616 System,
617 After
618};
619
620static std::vector<DirectoryLookup> IncludeGroup[4];
621
622/// AddPath - Add the specified path to the specified group list.
623///
624static void AddPath(const std::string &Path, IncludeDirGroup Group,
625 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000626 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000627 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000628 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000629
Chris Lattnerd6655272007-12-17 05:59:27 +0000630 // Compute the actual path, taking into consideration -isysroot.
631 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000632
Chris Lattnerd6655272007-12-17 05:59:27 +0000633 // Handle isysroot.
634 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000635 // FIXME: Portability. This should be a sys::Path interface, this doesn't
636 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000637 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
638 MappedPath.append(isysroot.begin(), isysroot.end());
639 if (Path[0] != '/') // If in the system group, add a /.
640 MappedPath.push_back('/');
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 }
642
Chris Lattnerd6655272007-12-17 05:59:27 +0000643 MappedPath.append(Path.begin(), Path.end());
644
645 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000646 DirectoryLookup::DirType Type;
647 if (Group == Quoted || Group == Angled)
648 Type = DirectoryLookup::NormalHeaderDir;
649 else if (isCXXAware)
650 Type = DirectoryLookup::SystemHeaderDir;
651 else
652 Type = DirectoryLookup::ExternCSystemHeaderDir;
653
Chris Lattnerd6655272007-12-17 05:59:27 +0000654
655 // If the directory exists, add it.
656 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
657 &MappedPath[0]+
658 MappedPath.size())) {
659 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
660 isFramework));
661 return;
662 }
663
Chris Lattnerdf772332007-12-17 07:52:39 +0000664 // Check to see if this is an apple-style headermap (which are not allowed to
665 // be frameworks).
666 if (!isFramework) {
667 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
668 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000669 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
670 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000671 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
672 return;
673 }
Chris Lattner822da612007-12-17 06:36:45 +0000674 }
675 }
676
Chris Lattnerd6655272007-12-17 05:59:27 +0000677 if (Verbose)
678 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000679}
680
681/// RemoveDuplicates - If there are duplicate directory entries in the specified
682/// search list, remove the later (dead) ones.
683static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000684 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000685 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000686 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000687 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000688 if (SearchList[i].isNormalDir()) {
689 // If this isn't the first time we've seen this dir, remove it.
690 if (SeenDirs.insert(SearchList[i].getDir()))
691 continue;
692
Reid Spencer5f016e22007-07-11 17:01:13 +0000693 if (Verbose)
694 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
695 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000696 } else if (SearchList[i].isFramework()) {
697 // If this isn't the first time we've seen this framework dir, remove it.
698 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
699 continue;
700
701 if (Verbose)
702 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
703 SearchList[i].getFrameworkDir()->getName());
704
Chris Lattnerb94c7072007-12-17 06:44:29 +0000705 } else {
706 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
707 // If this isn't the first time we've seen this headermap, remove it.
708 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
709 continue;
710
711 if (Verbose)
712 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
713 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000715
716 // This is reached if the current entry is a duplicate.
717 SearchList.erase(SearchList.begin()+i);
718 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 }
720}
721
722/// InitializeIncludePaths - Process the -I options and set them in the
723/// HeaderSearch object.
724static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000725 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 // Handle -F... options.
727 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000728 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000729
730 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000731 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000732 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000733
734 // Handle -idirafter... options.
735 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000736 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000737
738 // Handle -iquote... options.
739 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000740 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000741
742 // Handle -isystem... options.
743 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000744 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000745
746 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
747 // parallel, processing the values in order of occurance to get the right
748 // prefixes.
749 {
750 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
751 unsigned iprefix_idx = 0;
752 unsigned iwithprefix_idx = 0;
753 unsigned iwithprefixbefore_idx = 0;
754 bool iprefix_done = iprefix_vals.empty();
755 bool iwithprefix_done = iwithprefix_vals.empty();
756 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
757 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
758 if (!iprefix_done &&
759 (iwithprefix_done ||
760 iprefix_vals.getPosition(iprefix_idx) <
761 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
762 (iwithprefixbefore_done ||
763 iprefix_vals.getPosition(iprefix_idx) <
764 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
765 Prefix = iprefix_vals[iprefix_idx];
766 ++iprefix_idx;
767 iprefix_done = iprefix_idx == iprefix_vals.size();
768 } else if (!iwithprefix_done &&
769 (iwithprefixbefore_done ||
770 iwithprefix_vals.getPosition(iwithprefix_idx) <
771 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
772 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000773 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 ++iwithprefix_idx;
775 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
776 } else {
777 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000778 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000779 ++iwithprefixbefore_idx;
780 iwithprefixbefore_done =
781 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
782 }
783 }
784 }
785
786 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
787 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
788
789 // FIXME: temporary hack: hard-coded paths.
790 // FIXME: get these from the target?
791 if (!nostdinc) {
792 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000793 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000795 false, Headers);
796 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
797 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 }
799
Chris Lattner822da612007-12-17 06:36:45 +0000800 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 // leopard
802 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000803 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000805 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
807 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000808 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000809
810 // tiger
811 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000812 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000814 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
816 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000817 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000818
Chris Lattner822da612007-12-17 06:36:45 +0000819 AddPath("/usr/include", System, false, false, false, Headers);
820 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
821 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 }
823
824 // Now that we have collected all of the include paths, merge them all
825 // together and tell the preprocessor about them.
826
827 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
828 std::vector<DirectoryLookup> SearchList;
829 SearchList = IncludeGroup[Angled];
830 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
831 IncludeGroup[System].end());
832 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
833 IncludeGroup[After].end());
834 RemoveDuplicates(SearchList);
835 RemoveDuplicates(IncludeGroup[Quoted]);
836
837 // Prepend QUOTED list on the search list.
838 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
839 IncludeGroup[Quoted].end());
840
841
842 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
843 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
844 DontSearchCurDir);
845
846 // If verbose, print the list of directories that will be searched.
847 if (Verbose) {
848 fprintf(stderr, "#include \"...\" search starts here:\n");
849 unsigned QuotedIdx = IncludeGroup[Quoted].size();
850 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
851 if (i == QuotedIdx)
852 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000853 const char *Name = SearchList[i].getName();
854 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000855 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000856 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000857 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000858 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000859 else {
860 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000861 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000862 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000863 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 }
Chris Lattner80e17152007-12-15 23:11:06 +0000865 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 }
867}
868
869
Reid Spencer5f016e22007-07-11 17:01:13 +0000870//===----------------------------------------------------------------------===//
871// Basic Parser driver
872//===----------------------------------------------------------------------===//
873
874static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
875 Parser P(PP, *PA);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000876 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000877
878 // Parsing the specified input file.
879 P.ParseTranslationUnit();
880 delete PA;
881}
882
883//===----------------------------------------------------------------------===//
884// Main driver
885//===----------------------------------------------------------------------===//
886
Ted Kremenekdb094a22007-12-05 18:27:04 +0000887/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
888/// action. These consumers can operate on both ASTs that are freshly
889/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000890static ASTConsumer* CreateASTConsumer(const std::string& InFile,
891 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremenekdb094a22007-12-05 18:27:04 +0000892 const LangOptions& LangOpts) {
893 switch (ProgAction) {
894 default:
895 return NULL;
896
897 case ASTPrint:
898 return CreateASTPrinter();
899
900 case ASTDump:
901 return CreateASTDumper();
902
903 case ASTView:
904 return CreateASTViewer();
905
906 case ParseCFGDump:
907 case ParseCFGView:
908 return CreateCFGDumper(ProgAction == ParseCFGView);
909
910 case AnalysisLiveVariables:
911 return CreateLiveVarAnalyzer();
912
913 case WarnDeadStores:
914 return CreateDeadStoreChecker(Diag);
915
916 case WarnUninitVals:
917 return CreateUnitValsChecker(Diag);
918
919 case TestSerialization:
Ted Kremenekacc9f332007-12-05 21:34:36 +0000920 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000921
922 case EmitLLVM:
923 return CreateLLVMEmitter(Diag, LangOpts);
924
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000925 case SerializeAST: {
926 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek3821d402007-12-13 17:50:11 +0000927 // FIXME: This is a hack: "/" separator not portable.
928 std::string::size_type idx = InFile.rfind("/");
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000929
Ted Kremenek3821d402007-12-13 17:50:11 +0000930 if (idx != std::string::npos && idx == InFile.size()-1)
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000931 return NULL;
Ted Kremenek3821d402007-12-13 17:50:11 +0000932
933 std::string TargetPrefix( idx == std::string::npos ?
934 InFile : InFile.substr(idx+1));
935
936 llvm::sys::Path FName = llvm::sys::Path((TargetPrefix + ".ast").c_str());
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000937
938 return CreateASTSerializer(FName, Diag, LangOpts);
939 }
940
Ted Kremenekdb094a22007-12-05 18:27:04 +0000941 case RewriteTest:
942 return CreateCodeRewriterTest(Diag);
943 }
944}
945
Reid Spencer5f016e22007-07-11 17:01:13 +0000946/// ProcessInputFile - Process a single input file with the specified state.
947///
948static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
949 const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +0000950 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000951
952 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000953 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000954
Reid Spencer5f016e22007-07-11 17:01:13 +0000955 switch (ProgAction) {
956 default:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000957 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +0000958 PP.getFileManager(),
Ted Kremenekdb094a22007-12-05 18:27:04 +0000959 PP.getLangOptions());
960
961 if (!Consumer) {
962 fprintf(stderr, "Unexpected program action!\n");
963 return;
964 }
965 break;
966
Reid Spencer5f016e22007-07-11 17:01:13 +0000967 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000968 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000969 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000970 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 do {
972 PP.Lex(Tok);
973 PP.DumpToken(Tok, true);
974 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000975 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000976 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 break;
978 }
979 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000980 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000981 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000982 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000983 do {
984 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000985 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000986 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 break;
988 }
989
990 case PrintPreprocessedInput: // -E mode.
Chris Lattnerdee73592007-12-15 20:48:40 +0000991 DoPrintPreprocessedInput(MainFileID, PP);
Chris Lattnerbd247762007-07-22 06:05:44 +0000992 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 break;
994
995 case ParseNoop: // -parse-noop
Steve Naroffb4292f22007-10-31 20:55:39 +0000996 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000997 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000998 break;
999
1000 case ParsePrintCallbacks:
Steve Naroffb4292f22007-10-31 20:55:39 +00001001 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
1002 MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +00001003 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001004 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001005
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001006 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001007 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001008 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001009 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001010
1011 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001012 if (VerifyDiagnostics)
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001013 exit(CheckASTConsumer(PP, MainFileID, Consumer));
1014
1015 // This deletes Consumer.
1016 ParseAST(PP, MainFileID, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 }
1018
1019 if (Stats) {
1020 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
1021 PP.PrintStats();
1022 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001023 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001024 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001025 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001026 fprintf(stderr, "\n");
1027 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001028
1029 // For a multi-file compilation, some things are ok with nuking the source
1030 // manager tables, other require stable fileid/macroid's across multiple
1031 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001032 if (ClearSourceMgr)
1033 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001034}
1035
Ted Kremenek20e97482007-12-12 23:41:08 +00001036static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1037 FileManager& FileMgr) {
1038
1039 if (VerifyDiagnostics) {
1040 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1041 exit (1);
1042 }
1043
1044 llvm::sys::Path Filename(InFile);
1045
1046 if (!Filename.isValid()) {
1047 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1048 exit (1);
1049 }
1050
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001051 TranslationUnit* TU = TranslationUnit::ReadBitcodeFile(Filename,FileMgr);
1052
1053 if (!TU) {
1054 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1055 InFile.c_str());
1056 exit (1);
1057 }
1058
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001059 ASTConsumer* Consumer = CreateASTConsumer(InFile,Diag,
1060 FileMgr,TU->getLangOpts());
Ted Kremenek20e97482007-12-12 23:41:08 +00001061
1062 if (!Consumer) {
1063 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1064 exit (1);
1065 }
1066
1067 // FIXME: only work on consumers that do not require MainFileID.
1068 Consumer->Initialize(*TU->getContext(),0);
1069
1070 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1071 Consumer->HandleTopLevelDecl(*I);
1072
1073 delete Consumer;
1074}
1075
1076
Reid Spencer5f016e22007-07-11 17:01:13 +00001077static llvm::cl::list<std::string>
1078InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1079
Ted Kremenek20e97482007-12-12 23:41:08 +00001080static bool isSerializedFile(const std::string& InFile) {
1081 if (InFile.size() < 4)
1082 return false;
1083
1084 const char* s = InFile.c_str()+InFile.size()-4;
1085
1086 return s[0] == '.' &&
1087 s[1] == 'a' &&
1088 s[2] == 's' &&
1089 s[3] == 't';
1090}
1091
Reid Spencer5f016e22007-07-11 17:01:13 +00001092
1093int main(int argc, char **argv) {
1094 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1095 llvm::sys::PrintStackTraceOnErrorSignal();
1096
1097 // If no input was specified, read from stdin.
1098 if (InputFilenames.empty())
1099 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001100
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 // Create a file manager object to provide access to and cache the filesystem.
1102 FileManager FileMgr;
1103
Ted Kremenek31e703b2007-12-11 23:28:38 +00001104 // Create the diagnostic client for reporting errors or for
1105 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001107 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001109 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001110 } else {
1111 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001112 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001113
1114 if (InputFilenames.size() != 1) {
1115 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001116 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 return 1;
1118 }
1119 }
1120
1121 // Configure our handling of diagnostics.
1122 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001123 InitializeDiagnostics(Diags);
1124
Chris Lattner4f037832007-12-05 23:24:17 +00001125 // -I- is a deprecated GCC feature, scan for it and reject it.
1126 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1127 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001128 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001129 I_dirs.erase(I_dirs.begin()+i);
1130 --i;
1131 }
1132 }
1133
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001135 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001136
Ted Kremenek20e97482007-12-12 23:41:08 +00001137 if (isSerializedFile(InFile))
1138 ProcessSerializedFile(InFile,Diags,FileMgr);
1139 else {
1140 /// Create a SourceManager object. This tracks and owns all the file
1141 /// buffers allocated to a translation unit.
1142 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001143
Ted Kremenek20e97482007-12-12 23:41:08 +00001144 // Initialize language options, inferring file types from input filenames.
1145 LangOptions LangInfo;
1146 InitializeBaseLanguage();
1147 LangKind LK = GetLanguage(InFile);
1148 InitializeLangOptions(LangInfo, LK);
1149 InitializeLanguageStandard(LangInfo, LK);
1150
1151 // Process the -I options and set them in the HeaderInfo.
1152 HeaderSearch HeaderInfo(FileMgr);
1153 DiagClient->setHeaderSearch(HeaderInfo);
1154 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1155
1156 // Get information about the targets being compiled for. Note that this
1157 // pointer and the TargetInfoImpl objects are never deleted by this toy
1158 // driver.
1159 TargetInfo *Target;
1160
1161 // Create triples, and create the TargetInfo.
1162 std::vector<std::string> triples;
1163 CreateTargetTriples(triples);
1164 Target = TargetInfo::CreateTargetInfo(&triples[0],
1165 &triples[0]+triples.size(),
1166 &Diags);
1167
1168 if (Target == 0) {
1169 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1170 triples[0].c_str());
1171 fprintf(stderr, "Please use -triple or -arch.\n");
1172 exit(1);
1173 }
1174
1175 // Set up the preprocessor with these options.
1176 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1177
1178 std::vector<char> PredefineBuffer;
Chris Lattnerdee73592007-12-15 20:48:40 +00001179 unsigned MainFileID = InitializePreprocessor(PP, InFile, PredefineBuffer);
Ted Kremenek20e97482007-12-12 23:41:08 +00001180
1181 if (!MainFileID) continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00001182
Chris Lattnerdee73592007-12-15 20:48:40 +00001183 ProcessInputFile(PP, MainFileID, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001184
1185 HeaderInfo.ClearFileInfo();
1186
1187 if (Stats)
1188 SourceMgr.PrintStats();
1189 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 }
1191
1192 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1193
1194 if (NumDiagnostics)
1195 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1196 (NumDiagnostics == 1 ? "" : "s"));
1197
1198 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 FileMgr.PrintStats();
1200 fprintf(stderr, "\n");
1201 }
1202
Chris Lattner96f1a642007-07-21 05:40:53 +00001203 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001204}