blob: 02f8321b689335f88a20b02da9371ba0b8e2005d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
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"
Ted Kremenekee533642007-12-20 19:47:16 +000042#include "llvm/ADT/OwningPtr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000043#include <memory>
44using namespace clang;
45
46//===----------------------------------------------------------------------===//
47// Global options.
48//===----------------------------------------------------------------------===//
49
50static llvm::cl::opt<bool>
51Verbose("v", llvm::cl::desc("Enable verbose output"));
52static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000053Stats("print-stats",
54 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000055
56enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000057 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000058 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000059 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000060 SerializeAST, // Emit a .ast file.
Chris Lattner3b427b32007-10-11 00:18:28 +000061 ASTPrint, // Parse ASTs and print them.
62 ASTDump, // Parse ASTs and dump them.
63 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000064 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000065 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000066 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenekee985462008-01-16 18:18:48 +000067 AnalysisGRConstants, // Perform graph-reachability constant prop.
Ted Kremenek055c2752007-09-06 23:00:42 +000068 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000069 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000070 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000071 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000072 ParsePrintCallbacks, // Parse and print each callback.
73 ParseSyntaxOnly, // Parse and perform semantic analysis.
74 ParseNoop, // Parse with noop callbacks.
75 RunPreprocessorOnly, // Just lex, no output.
76 PrintPreprocessedInput, // -E mode.
77 DumpTokens // Token dump mode.
78};
79
80static llvm::cl::opt<ProgActions>
81ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
82 llvm::cl::init(ParseSyntaxOnly),
83 llvm::cl::values(
84 clEnumValN(RunPreprocessorOnly, "Eonly",
85 "Just run preprocessor, no output (for timings)"),
86 clEnumValN(PrintPreprocessedInput, "E",
87 "Run preprocessor, emit preprocessed file"),
88 clEnumValN(DumpTokens, "dumptokens",
89 "Run preprocessor, dump internal rep of tokens"),
90 clEnumValN(ParseNoop, "parse-noop",
91 "Run parser with noop callbacks (for timings)"),
92 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
93 "Run parser and perform semantic analysis"),
94 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
95 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +000096 clEnumValN(ASTPrint, "ast-print",
97 "Build ASTs and then pretty-print them"),
98 clEnumValN(ASTDump, "ast-dump",
99 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000100 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000101 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000102 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000103 "Run parser, then build and print CFGs."),
104 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000105 "Run parser, then build and view CFGs with Graphviz."),
106 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000107 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000108 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000109 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000110 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000111 "Flag warnings of uses of unitialized variables."),
Ted Kremeneka4532552008-01-16 18:21:49 +0000112 clEnumValN(AnalysisGRConstants, "grconstants",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000113 "Perform path-sensitive constant propagation."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000114 clEnumValN(TestSerialization, "test-pickling",
115 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000117 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000118 clEnumValN(EmitBC, "emit-llvm-bc",
119 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000120 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000121 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000122 clEnumValN(RewriteTest, "rewrite-test",
123 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 clEnumValEnd));
125
Ted Kremenekccc76472007-12-19 19:47:59 +0000126
127static llvm::cl::opt<std::string>
128OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000129 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000130 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
131
Ted Kremenek41193e42007-09-26 19:42:19 +0000132static llvm::cl::opt<bool>
133VerifyDiagnostics("verify",
134 llvm::cl::desc("Verify emitted diagnostics and warnings."));
135
Reid Spencer5f016e22007-07-11 17:01:13 +0000136//===----------------------------------------------------------------------===//
137// Language Options
138//===----------------------------------------------------------------------===//
139
140enum LangKind {
141 langkind_unspecified,
142 langkind_c,
143 langkind_c_cpp,
144 langkind_cxx,
145 langkind_cxx_cpp,
146 langkind_objc,
147 langkind_objc_cpp,
148 langkind_objcxx,
149 langkind_objcxx_cpp
150};
151
152/* TODO: GCC also accepts:
153 c-header c++-header objective-c-header objective-c++-header
154 assembler assembler-with-cpp
155 ada, f77*, ratfor (!), f95, java, treelang
156 */
157static llvm::cl::opt<LangKind>
158BaseLang("x", llvm::cl::desc("Base language to compile"),
159 llvm::cl::init(langkind_unspecified),
160 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
161 clEnumValN(langkind_cxx, "c++", "C++"),
162 clEnumValN(langkind_objc, "objective-c", "Objective C"),
163 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
164 clEnumValN(langkind_c_cpp, "c-cpp-output",
165 "Preprocessed C"),
166 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
167 "Preprocessed C++"),
168 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
169 "Preprocessed Objective C"),
170 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
171 "Preprocessed Objective C++"),
172 clEnumValEnd));
173
174static llvm::cl::opt<bool>
175LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
176 llvm::cl::Hidden);
177static llvm::cl::opt<bool>
178LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
179 llvm::cl::Hidden);
180
Ted Kremenek8904f152007-12-05 23:49:08 +0000181/// InitializeBaseLanguage - Handle the -x foo options.
182static void InitializeBaseLanguage() {
183 if (LangObjC)
184 BaseLang = langkind_objc;
185 else if (LangObjCXX)
186 BaseLang = langkind_objcxx;
187}
188
189static LangKind GetLanguage(const std::string &Filename) {
190 if (BaseLang != langkind_unspecified)
191 return BaseLang;
192
193 std::string::size_type DotPos = Filename.rfind('.');
194
195 if (DotPos == std::string::npos) {
196 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000197 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 }
199
Ted Kremenek8904f152007-12-05 23:49:08 +0000200 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
201 // C header: .h
202 // C++ header: .hh or .H;
203 // assembler no preprocessing: .s
204 // assembler: .S
205 if (Ext == "c")
206 return langkind_c;
207 else if (Ext == "i")
208 return langkind_c_cpp;
209 else if (Ext == "ii")
210 return langkind_cxx_cpp;
211 else if (Ext == "m")
212 return langkind_objc;
213 else if (Ext == "mi")
214 return langkind_objc_cpp;
215 else if (Ext == "mm" || Ext == "M")
216 return langkind_objcxx;
217 else if (Ext == "mii")
218 return langkind_objcxx_cpp;
219 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
220 Ext == "c++" || Ext == "cp" || Ext == "cxx")
221 return langkind_cxx;
222 else
223 return langkind_c;
224}
225
226
227static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000228 // FIXME: implement -fpreprocessed mode.
229 bool NoPreprocess = false;
230
Ted Kremenek8904f152007-12-05 23:49:08 +0000231 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000232 default: assert(0 && "Unknown language kind!");
233 case langkind_c_cpp:
234 NoPreprocess = true;
235 // FALLTHROUGH
236 case langkind_c:
237 break;
238 case langkind_cxx_cpp:
239 NoPreprocess = true;
240 // FALLTHROUGH
241 case langkind_cxx:
242 Options.CPlusPlus = 1;
243 break;
244 case langkind_objc_cpp:
245 NoPreprocess = true;
246 // FALLTHROUGH
247 case langkind_objc:
248 Options.ObjC1 = Options.ObjC2 = 1;
249 break;
250 case langkind_objcxx_cpp:
251 NoPreprocess = true;
252 // FALLTHROUGH
253 case langkind_objcxx:
254 Options.ObjC1 = Options.ObjC2 = 1;
255 Options.CPlusPlus = 1;
256 break;
257 }
258}
259
260/// LangStds - Language standards we support.
261enum LangStds {
262 lang_unspecified,
263 lang_c89, lang_c94, lang_c99,
264 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000265 lang_cxx98, lang_gnucxx98,
266 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000267};
268
269static llvm::cl::opt<LangStds>
270LangStd("std", llvm::cl::desc("Language standard to compile for"),
271 llvm::cl::init(lang_unspecified),
272 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
273 clEnumValN(lang_c89, "c90", "ISO C 1990"),
274 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
275 clEnumValN(lang_c94, "iso9899:199409",
276 "ISO C 1990 with amendment 1"),
277 clEnumValN(lang_c99, "c99", "ISO C 1999"),
278// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
279 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
280// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
281 clEnumValN(lang_gnu89, "gnu89",
282 "ISO C 1990 with GNU extensions (default for C)"),
283 clEnumValN(lang_gnu99, "gnu99",
284 "ISO C 1999 with GNU extensions"),
285 clEnumValN(lang_gnu99, "gnu9x",
286 "ISO C 1999 with GNU extensions"),
287 clEnumValN(lang_cxx98, "c++98",
288 "ISO C++ 1998 with amendments"),
289 clEnumValN(lang_gnucxx98, "gnu++98",
290 "ISO C++ 1998 with amendments and GNU "
291 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000292 clEnumValN(lang_cxx0x, "c++0x",
293 "Upcoming ISO C++ 200x with amendments"),
294 clEnumValN(lang_gnucxx0x, "gnu++0x",
295 "Upcoming ISO C++ 200x with amendments and GNU "
296 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 clEnumValEnd));
298
299static llvm::cl::opt<bool>
300NoOperatorNames("fno-operator-names",
301 llvm::cl::desc("Do not treat C++ operator name keywords as "
302 "synonyms for operators"));
303
Anders Carlssonee98ac52007-10-15 02:50:23 +0000304static llvm::cl::opt<bool>
305PascalStrings("fpascal-strings",
306 llvm::cl::desc("Recognize and construct Pascal-style "
307 "string literals"));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000308
309static llvm::cl::opt<bool>
310WritableStrings("fwritable-strings",
311 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000312
313static llvm::cl::opt<bool>
314LaxVectorConversions("flax-vector-conversions",
315 llvm::cl::desc("Allow implicit conversions between vectors"
316 " with a different number of elements or "
317 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000318// FIXME: add:
319// -ansi
320// -trigraphs
321// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000322// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000323static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 if (LangStd == lang_unspecified) {
325 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000326 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 default: assert(0 && "Unknown base language");
328 case langkind_c:
329 case langkind_c_cpp:
330 case langkind_objc:
331 case langkind_objc_cpp:
332 LangStd = lang_gnu99;
333 break;
334 case langkind_cxx:
335 case langkind_cxx_cpp:
336 case langkind_objcxx:
337 case langkind_objcxx_cpp:
338 LangStd = lang_gnucxx98;
339 break;
340 }
341 }
342
343 switch (LangStd) {
344 default: assert(0 && "Unknown language standard!");
345
346 // Fall through from newer standards to older ones. This isn't really right.
347 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000348 case lang_gnucxx0x:
349 case lang_cxx0x:
350 Options.CPlusPlus0x = 1;
351 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 case lang_gnucxx98:
353 case lang_cxx98:
354 Options.CPlusPlus = 1;
355 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000356 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 // FALL THROUGH.
358 case lang_gnu99:
359 case lang_c99:
360 Options.Digraphs = 1;
361 Options.C99 = 1;
362 Options.HexFloats = 1;
363 // FALL THROUGH.
364 case lang_gnu89:
365 Options.BCPLComment = 1; // Only for C99/C++.
366 // FALL THROUGH.
367 case lang_c94:
368 case lang_c89:
369 break;
370 }
371
372 Options.Trigraphs = 1; // -trigraphs or -ansi
373 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000374 Options.PascalStrings = PascalStrings;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000375 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000376 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000377}
378
379//===----------------------------------------------------------------------===//
380// Our DiagnosticClient implementation
381//===----------------------------------------------------------------------===//
382
383// FIXME: Werror should take a list of things, -Werror=foo,bar
384static llvm::cl::opt<bool>
385WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
386
387static llvm::cl::opt<bool>
388WarnOnExtensions("pedantic", llvm::cl::init(false),
389 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
390
391static llvm::cl::opt<bool>
392ErrorOnExtensions("pedantic-errors",
393 llvm::cl::desc("Issue an error on uses of GCC extensions"));
394
395static llvm::cl::opt<bool>
396WarnUnusedMacros("Wunused_macros",
397 llvm::cl::desc("Warn for unused macros in the main translation unit"));
398
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000399static llvm::cl::opt<bool>
400WarnFloatEqual("Wfloat-equal",
401 llvm::cl::desc("Warn about equality comparisons of floating point values."));
402
Ted Kremenek73da5902007-12-17 17:50:07 +0000403static llvm::cl::opt<bool>
404WarnNoFormatNonLiteral("Wno-format-nonliteral",
405 llvm::cl::desc("Do not warn about non-literal format strings."));
406
Chris Lattner116a4b12008-01-23 17:19:46 +0000407static llvm::cl::opt<bool>
408WarnUndefMacros("Wundef",
409 llvm::cl::desc("Warn on use of undefined macros in #if's"));
410
411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412/// InitializeDiagnostics - Initialize the diagnostic object, based on the
413/// current command line option settings.
414static void InitializeDiagnostics(Diagnostic &Diags) {
415 Diags.setWarningsAsErrors(WarningsAsErrors);
416 Diags.setWarnOnExtensions(WarnOnExtensions);
417 Diags.setErrorOnExtensions(ErrorOnExtensions);
418
419 // Silence the "macro is not used" warning unless requested.
420 if (!WarnUnusedMacros)
421 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000422
423 // Silence "floating point comparison" warnings unless requested.
424 if (!WarnFloatEqual)
425 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000426
427 // Silence "format string is not a string literal" warnings if requested
428 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000429 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
430 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000431 if (!WarnUndefMacros)
432 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000433}
434
435//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000436// Target Triple Processing.
437//===----------------------------------------------------------------------===//
438
439static llvm::cl::opt<std::string>
440TargetTriple("triple",
441 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
442
443static llvm::cl::list<std::string>
444Archs("arch",
445 llvm::cl::desc("Specify target architecture (e.g. i686)."));
446
447namespace {
448 class TripleProcessor {
449 llvm::StringMap<char> TriplesProcessed;
450 std::vector<std::string>& triples;
451 public:
452 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
453
454 void addTriple(const std::string& t) {
455 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
456 TriplesProcessed.end()) {
457 triples.push_back(t);
458 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
459 }
460 }
461 };
462}
463
464static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000465 // Initialize base triple. If a -triple option has been specified, use
466 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000467 std::string Triple = TargetTriple;
468 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000469
470 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000471 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000472
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000473 if (firstDash == std::string::npos) {
474 fprintf(stderr,
475 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000476 Triple.c_str());
477 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000478 }
Ted Kremenekae360762007-12-03 22:06:55 +0000479
Chris Lattner6590d212007-12-12 05:01:48 +0000480 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000481
482 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000483 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
484 Triple.c_str());
485 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000486 }
Ted Kremenekae360762007-12-03 22:06:55 +0000487
488 // Create triple cacher.
489 TripleProcessor tp(triples);
490
491 // Add the primary triple to our set of triples if we are using the
492 // host-triple with no archs or using a specified target triple.
493 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000494 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000495
496 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
497 tp.addTriple(Archs[i] + "-" + suffix);
498}
499
500//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000501// Preprocessor Initialization
502//===----------------------------------------------------------------------===//
503
504// FIXME: Preprocessor builtins to support.
505// -A... - Play with #assertions
506// -undef - Undefine all predefined macros
507
508static llvm::cl::list<std::string>
509D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
510 llvm::cl::desc("Predefine the specified macro"));
511static llvm::cl::list<std::string>
512U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
513 llvm::cl::desc("Undefine the specified macro"));
514
Chris Lattner64299f82008-01-10 01:53:41 +0000515static llvm::cl::list<std::string>
516ImplicitIncludes("include", llvm::cl::value_desc("file"),
517 llvm::cl::desc("Include file before parsing"));
518
519
Reid Spencer5f016e22007-07-11 17:01:13 +0000520// Append a #define line to Buf for Macro. Macro should be of the form XXX,
521// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
522// "#define XXX Y z W". To get a #define with no value, use "XXX=".
523static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
524 const char *Command = "#define ") {
525 Buf.insert(Buf.end(), Command, Command+strlen(Command));
526 if (const char *Equal = strchr(Macro, '=')) {
527 // Turn the = into ' '.
528 Buf.insert(Buf.end(), Macro, Equal);
529 Buf.push_back(' ');
530 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
531 } else {
532 // Push "macroname 1".
533 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
534 Buf.push_back(' ');
535 Buf.push_back('1');
536 }
537 Buf.push_back('\n');
538}
539
Chris Lattner64299f82008-01-10 01:53:41 +0000540/// AddImplicitInclude - Add an implicit #include of the specified file to the
541/// predefines buffer.
542static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
543 const char *Inc = "#include \"";
544 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
545 Buf.insert(Buf.end(), File.begin(), File.end());
546 Buf.push_back('"');
547 Buf.push_back('\n');
548}
549
Reid Spencer5f016e22007-07-11 17:01:13 +0000550
Chris Lattner53b0dab2007-10-09 22:10:18 +0000551/// InitializePreprocessor - Initialize the preprocessor getting it and the
552/// environment ready to process a single file. This returns the file ID for the
553/// input file. If a failure happens, it returns 0.
554///
555static unsigned InitializePreprocessor(Preprocessor &PP,
556 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000557 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000558
Chris Lattnerdee73592007-12-15 20:48:40 +0000559 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000560
Chris Lattner53b0dab2007-10-09 22:10:18 +0000561 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000562 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000563 if (InFile != "-") {
564 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000565 if (File) SourceMgr.createMainFileID(File, SourceLocation());
566 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000567 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
568 return 0;
569 }
570 } else {
571 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000572 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
573 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000574 fprintf(stderr, "Error reading standard input! Empty?\n");
575 return 0;
576 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 }
578
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 // Add macros from the command line.
580 // FIXME: Should traverse the #define/#undef lists in parallel.
581 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000582 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000584 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
585
Chris Lattner64299f82008-01-10 01:53:41 +0000586 // FIXME: Read any files specified by -imacros.
587
588 // Add implicit #includes from -include.
589 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
590 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000591
592 // Null terminate PredefinedBuffer and add it.
593 PredefineBuffer.push_back(0);
594 PP.setPredefines(&PredefineBuffer[0]);
595
596 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000597 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000598}
599
600//===----------------------------------------------------------------------===//
601// Preprocessor include path information.
602//===----------------------------------------------------------------------===//
603
604// This tool exports a large number of command line options to control how the
605// preprocessor searches for header files. At root, however, the Preprocessor
606// object takes a very simple interface: a list of directories to search for
607//
608// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000609// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000610//
Chris Lattner64299f82008-01-10 01:53:41 +0000611// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000612
613static llvm::cl::opt<bool>
614nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
615
616// Various command line options. These four add directories to each chain.
617static llvm::cl::list<std::string>
618F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
619 llvm::cl::desc("Add directory to framework include search path"));
620static llvm::cl::list<std::string>
621I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
622 llvm::cl::desc("Add directory to include search path"));
623static llvm::cl::list<std::string>
624idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
625 llvm::cl::desc("Add directory to AFTER include search path"));
626static llvm::cl::list<std::string>
627iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
628 llvm::cl::desc("Add directory to QUOTE include search path"));
629static llvm::cl::list<std::string>
630isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
631 llvm::cl::desc("Add directory to SYSTEM include search path"));
632
633// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
634static llvm::cl::list<std::string>
635iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
636 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
637static llvm::cl::list<std::string>
638iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
639 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
640static llvm::cl::list<std::string>
641iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
642 llvm::cl::Prefix,
643 llvm::cl::desc("Set directory to include search path with prefix"));
644
Chris Lattner0c946412007-08-26 17:47:35 +0000645static llvm::cl::opt<std::string>
646isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
647 llvm::cl::desc("Set the system root directory (usually /)"));
648
Reid Spencer5f016e22007-07-11 17:01:13 +0000649// Finally, implement the code that groks the options above.
650enum IncludeDirGroup {
651 Quoted = 0,
652 Angled,
653 System,
654 After
655};
656
657static std::vector<DirectoryLookup> IncludeGroup[4];
658
659/// AddPath - Add the specified path to the specified group list.
660///
661static void AddPath(const std::string &Path, IncludeDirGroup Group,
662 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000663 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000664 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000665 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000666
Chris Lattnerd6655272007-12-17 05:59:27 +0000667 // Compute the actual path, taking into consideration -isysroot.
668 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000669
Chris Lattnerd6655272007-12-17 05:59:27 +0000670 // Handle isysroot.
671 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000672 // FIXME: Portability. This should be a sys::Path interface, this doesn't
673 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000674 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
675 MappedPath.append(isysroot.begin(), isysroot.end());
676 if (Path[0] != '/') // If in the system group, add a /.
677 MappedPath.push_back('/');
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 }
679
Chris Lattnerd6655272007-12-17 05:59:27 +0000680 MappedPath.append(Path.begin(), Path.end());
681
682 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000683 DirectoryLookup::DirType Type;
684 if (Group == Quoted || Group == Angled)
685 Type = DirectoryLookup::NormalHeaderDir;
686 else if (isCXXAware)
687 Type = DirectoryLookup::SystemHeaderDir;
688 else
689 Type = DirectoryLookup::ExternCSystemHeaderDir;
690
Chris Lattnerd6655272007-12-17 05:59:27 +0000691
692 // If the directory exists, add it.
693 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
694 &MappedPath[0]+
695 MappedPath.size())) {
696 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
697 isFramework));
698 return;
699 }
700
Chris Lattnerdf772332007-12-17 07:52:39 +0000701 // Check to see if this is an apple-style headermap (which are not allowed to
702 // be frameworks).
703 if (!isFramework) {
704 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
705 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000706 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
707 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000708 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
709 return;
710 }
Chris Lattner822da612007-12-17 06:36:45 +0000711 }
712 }
713
Chris Lattnerd6655272007-12-17 05:59:27 +0000714 if (Verbose)
715 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000716}
717
718/// RemoveDuplicates - If there are duplicate directory entries in the specified
719/// search list, remove the later (dead) ones.
720static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000721 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000722 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000723 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000725 if (SearchList[i].isNormalDir()) {
726 // If this isn't the first time we've seen this dir, remove it.
727 if (SeenDirs.insert(SearchList[i].getDir()))
728 continue;
729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 if (Verbose)
731 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
732 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000733 } else if (SearchList[i].isFramework()) {
734 // If this isn't the first time we've seen this framework dir, remove it.
735 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
736 continue;
737
738 if (Verbose)
739 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
740 SearchList[i].getFrameworkDir()->getName());
741
Chris Lattnerb94c7072007-12-17 06:44:29 +0000742 } else {
743 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
744 // If this isn't the first time we've seen this headermap, remove it.
745 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
746 continue;
747
748 if (Verbose)
749 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
750 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000752
753 // This is reached if the current entry is a duplicate.
754 SearchList.erase(SearchList.begin()+i);
755 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 }
757}
758
759/// InitializeIncludePaths - Process the -I options and set them in the
760/// HeaderSearch object.
761static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000762 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 // Handle -F... options.
764 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000765 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000766
767 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000768 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000769 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000770
771 // Handle -idirafter... options.
772 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000773 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000774
775 // Handle -iquote... options.
776 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000777 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000778
779 // Handle -isystem... options.
780 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000781 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000782
783 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
784 // parallel, processing the values in order of occurance to get the right
785 // prefixes.
786 {
787 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
788 unsigned iprefix_idx = 0;
789 unsigned iwithprefix_idx = 0;
790 unsigned iwithprefixbefore_idx = 0;
791 bool iprefix_done = iprefix_vals.empty();
792 bool iwithprefix_done = iwithprefix_vals.empty();
793 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
794 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
795 if (!iprefix_done &&
796 (iwithprefix_done ||
797 iprefix_vals.getPosition(iprefix_idx) <
798 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
799 (iwithprefixbefore_done ||
800 iprefix_vals.getPosition(iprefix_idx) <
801 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
802 Prefix = iprefix_vals[iprefix_idx];
803 ++iprefix_idx;
804 iprefix_done = iprefix_idx == iprefix_vals.size();
805 } else if (!iwithprefix_done &&
806 (iwithprefixbefore_done ||
807 iwithprefix_vals.getPosition(iwithprefix_idx) <
808 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
809 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000810 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 ++iwithprefix_idx;
812 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
813 } else {
814 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000815 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 ++iwithprefixbefore_idx;
817 iwithprefixbefore_done =
818 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
819 }
820 }
821 }
822
823 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
824 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
825
826 // FIXME: temporary hack: hard-coded paths.
827 // FIXME: get these from the target?
828 if (!nostdinc) {
829 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000830 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000831 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000832 false, Headers);
833 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
834 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000835 }
836
Chris Lattner822da612007-12-17 06:36:45 +0000837 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000838 // leopard
839 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000840 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000841 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000842 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000843 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
844 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000845 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000846
847 // tiger
848 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000849 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000850 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000851 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000852 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
853 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000854 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000855
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000856 // Ubuntu 7.10 - Gutsy Gibbon
857 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
858 false, false, false, Headers);
859
Chris Lattner822da612007-12-17 06:36:45 +0000860 AddPath("/usr/include", System, false, false, false, Headers);
861 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
862 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 }
864
865 // Now that we have collected all of the include paths, merge them all
866 // together and tell the preprocessor about them.
867
868 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
869 std::vector<DirectoryLookup> SearchList;
870 SearchList = IncludeGroup[Angled];
871 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
872 IncludeGroup[System].end());
873 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
874 IncludeGroup[After].end());
875 RemoveDuplicates(SearchList);
876 RemoveDuplicates(IncludeGroup[Quoted]);
877
878 // Prepend QUOTED list on the search list.
879 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
880 IncludeGroup[Quoted].end());
881
882
883 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
884 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
885 DontSearchCurDir);
886
887 // If verbose, print the list of directories that will be searched.
888 if (Verbose) {
889 fprintf(stderr, "#include \"...\" search starts here:\n");
890 unsigned QuotedIdx = IncludeGroup[Quoted].size();
891 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
892 if (i == QuotedIdx)
893 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000894 const char *Name = SearchList[i].getName();
895 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000896 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000897 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000898 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000899 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000900 else {
901 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000902 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000903 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000904 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 }
Chris Lattner80e17152007-12-15 23:11:06 +0000906 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 }
908}
909
910
Reid Spencer5f016e22007-07-11 17:01:13 +0000911//===----------------------------------------------------------------------===//
912// Basic Parser driver
913//===----------------------------------------------------------------------===//
914
Ted Kremenek95041a22007-12-19 22:51:13 +0000915static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000917 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000918
919 // Parsing the specified input file.
920 P.ParseTranslationUnit();
921 delete PA;
922}
923
924//===----------------------------------------------------------------------===//
925// Main driver
926//===----------------------------------------------------------------------===//
927
Ted Kremenekdb094a22007-12-05 18:27:04 +0000928/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
929/// action. These consumers can operate on both ASTs that are freshly
930/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000931static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000932 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremenekdb094a22007-12-05 18:27:04 +0000933 const LangOptions& LangOpts) {
934 switch (ProgAction) {
935 default:
936 return NULL;
937
938 case ASTPrint:
939 return CreateASTPrinter();
940
941 case ASTDump:
942 return CreateASTDumper();
943
944 case ASTView:
945 return CreateASTViewer();
946
947 case ParseCFGDump:
948 case ParseCFGView:
949 return CreateCFGDumper(ProgAction == ParseCFGView);
950
951 case AnalysisLiveVariables:
952 return CreateLiveVarAnalyzer();
953
954 case WarnDeadStores:
955 return CreateDeadStoreChecker(Diag);
956
957 case WarnUninitVals:
958 return CreateUnitValsChecker(Diag);
959
Ted Kremenekee985462008-01-16 18:18:48 +0000960 case AnalysisGRConstants:
961 return CreateGRConstants();
Ted Kremeneke603df42008-01-08 18:04:06 +0000962
Ted Kremenekdb094a22007-12-05 18:27:04 +0000963 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000964 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000965
966 case EmitLLVM:
967 return CreateLLVMEmitter(Diag, LangOpts);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000968
969 case EmitBC:
970 return CreateBCWriter(InFile, OutputFile, Diag, LangOpts);
971
Ted Kremenek3910c7c2007-12-19 17:25:59 +0000972 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000973 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +0000974 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000975
Ted Kremenekdb094a22007-12-05 18:27:04 +0000976 case RewriteTest:
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000977 return CreateCodeRewriterTest(InFile, Diag);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000978 }
979}
980
Reid Spencer5f016e22007-07-11 17:01:13 +0000981/// ProcessInputFile - Process a single input file with the specified state.
982///
Ted Kremenek7dcc9682007-12-19 22:32:34 +0000983static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +0000984 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000985
986 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000987 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000988
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 switch (ProgAction) {
990 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000991 Consumer = CreateASTConsumer(InFile,
992 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +0000993 PP.getFileManager(),
Ted Kremenekdb094a22007-12-05 18:27:04 +0000994 PP.getLangOptions());
995
996 if (!Consumer) {
997 fprintf(stderr, "Unexpected program action!\n");
998 return;
999 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001000
Ted Kremenekdb094a22007-12-05 18:27:04 +00001001 break;
1002
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001004 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001005 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001006 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001007 do {
1008 PP.Lex(Tok);
1009 PP.DumpToken(Tok, true);
1010 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001011 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001012 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 break;
1014 }
1015 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001016 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001018 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001019 do {
1020 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001021 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001022 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001023 break;
1024 }
1025
1026 case PrintPreprocessedInput: // -E mode.
Ted Kremenek95041a22007-12-19 22:51:13 +00001027 DoPrintPreprocessedInput(PP);
Chris Lattnerbd247762007-07-22 06:05:44 +00001028 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001029 break;
1030
1031 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001032 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001033 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 break;
1035
1036 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001037 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001038 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001039 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001040
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001041 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001042 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001043 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001044 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001045
1046 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001047 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001048 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001049
1050 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001051 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001052 }
1053
1054 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001055 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 PP.PrintStats();
1057 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001058 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001059 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001060 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001061 fprintf(stderr, "\n");
1062 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001063
1064 // For a multi-file compilation, some things are ok with nuking the source
1065 // manager tables, other require stable fileid/macroid's across multiple
1066 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001067 if (ClearSourceMgr)
1068 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001069}
1070
Ted Kremenek20e97482007-12-12 23:41:08 +00001071static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1072 FileManager& FileMgr) {
1073
1074 if (VerifyDiagnostics) {
1075 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1076 exit (1);
1077 }
1078
1079 llvm::sys::Path Filename(InFile);
1080
1081 if (!Filename.isValid()) {
1082 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1083 exit (1);
1084 }
1085
Ted Kremenekee533642007-12-20 19:47:16 +00001086 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001087
1088 if (!TU) {
1089 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1090 InFile.c_str());
1091 exit (1);
1092 }
1093
Ted Kremenek63ea8632007-12-19 19:27:38 +00001094 // Observe that we use the source file name stored in the deserialized
1095 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001096 llvm::OwningPtr<ASTConsumer>
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001097 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts()));
Ted Kremenek20e97482007-12-12 23:41:08 +00001098
1099 if (!Consumer) {
1100 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1101 exit (1);
1102 }
1103
Ted Kremenek95041a22007-12-19 22:51:13 +00001104 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001105
1106 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1107 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001108}
1109
1110
Reid Spencer5f016e22007-07-11 17:01:13 +00001111static llvm::cl::list<std::string>
1112InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1113
Ted Kremenek20e97482007-12-12 23:41:08 +00001114static bool isSerializedFile(const std::string& InFile) {
1115 if (InFile.size() < 4)
1116 return false;
1117
1118 const char* s = InFile.c_str()+InFile.size()-4;
1119
1120 return s[0] == '.' &&
1121 s[1] == 'a' &&
1122 s[2] == 's' &&
1123 s[3] == 't';
1124}
1125
Reid Spencer5f016e22007-07-11 17:01:13 +00001126
1127int main(int argc, char **argv) {
1128 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1129 llvm::sys::PrintStackTraceOnErrorSignal();
1130
1131 // If no input was specified, read from stdin.
1132 if (InputFilenames.empty())
1133 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001134
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 // Create a file manager object to provide access to and cache the filesystem.
1136 FileManager FileMgr;
1137
Ted Kremenek31e703b2007-12-11 23:28:38 +00001138 // Create the diagnostic client for reporting errors or for
1139 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001141 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001142 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001143 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 } else {
1145 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001146 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001147
1148 if (InputFilenames.size() != 1) {
1149 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001150 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 return 1;
1152 }
1153 }
1154
1155 // Configure our handling of diagnostics.
1156 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001157 InitializeDiagnostics(Diags);
1158
Chris Lattner4f037832007-12-05 23:24:17 +00001159 // -I- is a deprecated GCC feature, scan for it and reject it.
1160 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1161 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001162 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001163 I_dirs.erase(I_dirs.begin()+i);
1164 --i;
1165 }
1166 }
1167
Reid Spencer5f016e22007-07-11 17:01:13 +00001168 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001169 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001170
Ted Kremenek20e97482007-12-12 23:41:08 +00001171 if (isSerializedFile(InFile))
1172 ProcessSerializedFile(InFile,Diags,FileMgr);
1173 else {
1174 /// Create a SourceManager object. This tracks and owns all the file
1175 /// buffers allocated to a translation unit.
1176 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001177
Ted Kremenek20e97482007-12-12 23:41:08 +00001178 // Initialize language options, inferring file types from input filenames.
1179 LangOptions LangInfo;
1180 InitializeBaseLanguage();
1181 LangKind LK = GetLanguage(InFile);
1182 InitializeLangOptions(LangInfo, LK);
1183 InitializeLanguageStandard(LangInfo, LK);
1184
1185 // Process the -I options and set them in the HeaderInfo.
1186 HeaderSearch HeaderInfo(FileMgr);
1187 DiagClient->setHeaderSearch(HeaderInfo);
1188 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1189
1190 // Get information about the targets being compiled for. Note that this
1191 // pointer and the TargetInfoImpl objects are never deleted by this toy
1192 // driver.
1193 TargetInfo *Target;
1194
1195 // Create triples, and create the TargetInfo.
1196 std::vector<std::string> triples;
1197 CreateTargetTriples(triples);
1198 Target = TargetInfo::CreateTargetInfo(&triples[0],
1199 &triples[0]+triples.size(),
1200 &Diags);
1201
1202 if (Target == 0) {
1203 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1204 triples[0].c_str());
1205 fprintf(stderr, "Please use -triple or -arch.\n");
1206 exit(1);
1207 }
1208
1209 // Set up the preprocessor with these options.
1210 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1211
1212 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001213 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001214 continue;
1215
Ted Kremenek1036b682007-12-19 23:48:45 +00001216 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001217 HeaderInfo.ClearFileInfo();
1218
1219 if (Stats)
1220 SourceMgr.PrintStats();
1221 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001222 }
1223
1224 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1225
1226 if (NumDiagnostics)
1227 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1228 (NumDiagnostics == 1 ? "" : "s"));
1229
1230 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 FileMgr.PrintStats();
1232 fprintf(stderr, "\n");
1233 }
1234
Chris Lattner96f1a642007-07-21 05:40:53 +00001235 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001236}