blob: 26cbd4863fbbb63b54cc5186b50219012c21baac [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 Kremeneke603df42008-01-08 18:04:06 +000067 AnalysisGRConstProp, // 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 Kremeneke603df42008-01-08 18:04:06 +0000112 clEnumValN(AnalysisGRConstProp, "gr-const-prop",
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
Reid Spencer5f016e22007-07-11 17:01:13 +0000407/// InitializeDiagnostics - Initialize the diagnostic object, based on the
408/// current command line option settings.
409static void InitializeDiagnostics(Diagnostic &Diags) {
410 Diags.setWarningsAsErrors(WarningsAsErrors);
411 Diags.setWarnOnExtensions(WarnOnExtensions);
412 Diags.setErrorOnExtensions(ErrorOnExtensions);
413
414 // Silence the "macro is not used" warning unless requested.
415 if (!WarnUnusedMacros)
416 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000417
418 // Silence "floating point comparison" warnings unless requested.
419 if (!WarnFloatEqual)
420 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000421
422 // Silence "format string is not a string literal" warnings if requested
423 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000424 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
425 diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000426
Reid Spencer5f016e22007-07-11 17:01:13 +0000427}
428
429//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000430// Target Triple Processing.
431//===----------------------------------------------------------------------===//
432
433static llvm::cl::opt<std::string>
434TargetTriple("triple",
435 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
436
437static llvm::cl::list<std::string>
438Archs("arch",
439 llvm::cl::desc("Specify target architecture (e.g. i686)."));
440
441namespace {
442 class TripleProcessor {
443 llvm::StringMap<char> TriplesProcessed;
444 std::vector<std::string>& triples;
445 public:
446 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
447
448 void addTriple(const std::string& t) {
449 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
450 TriplesProcessed.end()) {
451 triples.push_back(t);
452 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
453 }
454 }
455 };
456}
457
458static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000459 // Initialize base triple. If a -triple option has been specified, use
460 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000461 std::string Triple = TargetTriple;
462 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000463
464 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000465 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000466
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000467 if (firstDash == std::string::npos) {
468 fprintf(stderr,
469 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000470 Triple.c_str());
471 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000472 }
Ted Kremenekae360762007-12-03 22:06:55 +0000473
Chris Lattner6590d212007-12-12 05:01:48 +0000474 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000475
476 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000477 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
478 Triple.c_str());
479 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000480 }
Ted Kremenekae360762007-12-03 22:06:55 +0000481
482 // Create triple cacher.
483 TripleProcessor tp(triples);
484
485 // Add the primary triple to our set of triples if we are using the
486 // host-triple with no archs or using a specified target triple.
487 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000488 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000489
490 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
491 tp.addTriple(Archs[i] + "-" + suffix);
492}
493
494//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000495// Preprocessor Initialization
496//===----------------------------------------------------------------------===//
497
498// FIXME: Preprocessor builtins to support.
499// -A... - Play with #assertions
500// -undef - Undefine all predefined macros
501
502static llvm::cl::list<std::string>
503D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
504 llvm::cl::desc("Predefine the specified macro"));
505static llvm::cl::list<std::string>
506U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
507 llvm::cl::desc("Undefine the specified macro"));
508
Chris Lattner64299f82008-01-10 01:53:41 +0000509static llvm::cl::list<std::string>
510ImplicitIncludes("include", llvm::cl::value_desc("file"),
511 llvm::cl::desc("Include file before parsing"));
512
513
Reid Spencer5f016e22007-07-11 17:01:13 +0000514// Append a #define line to Buf for Macro. Macro should be of the form XXX,
515// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
516// "#define XXX Y z W". To get a #define with no value, use "XXX=".
517static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
518 const char *Command = "#define ") {
519 Buf.insert(Buf.end(), Command, Command+strlen(Command));
520 if (const char *Equal = strchr(Macro, '=')) {
521 // Turn the = into ' '.
522 Buf.insert(Buf.end(), Macro, Equal);
523 Buf.push_back(' ');
524 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
525 } else {
526 // Push "macroname 1".
527 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
528 Buf.push_back(' ');
529 Buf.push_back('1');
530 }
531 Buf.push_back('\n');
532}
533
Chris Lattner64299f82008-01-10 01:53:41 +0000534/// AddImplicitInclude - Add an implicit #include of the specified file to the
535/// predefines buffer.
536static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
537 const char *Inc = "#include \"";
538 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
539 Buf.insert(Buf.end(), File.begin(), File.end());
540 Buf.push_back('"');
541 Buf.push_back('\n');
542}
543
Reid Spencer5f016e22007-07-11 17:01:13 +0000544
Chris Lattner53b0dab2007-10-09 22:10:18 +0000545/// InitializePreprocessor - Initialize the preprocessor getting it and the
546/// environment ready to process a single file. This returns the file ID for the
547/// input file. If a failure happens, it returns 0.
548///
549static unsigned InitializePreprocessor(Preprocessor &PP,
550 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000551 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000552
Chris Lattnerdee73592007-12-15 20:48:40 +0000553 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000554
Chris Lattner53b0dab2007-10-09 22:10:18 +0000555 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000556 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000557 if (InFile != "-") {
558 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000559 if (File) SourceMgr.createMainFileID(File, SourceLocation());
560 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000561 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
562 return 0;
563 }
564 } else {
565 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000566 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
567 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000568 fprintf(stderr, "Error reading standard input! Empty?\n");
569 return 0;
570 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 }
572
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 // Add macros from the command line.
574 // FIXME: Should traverse the #define/#undef lists in parallel.
575 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000576 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000578 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
579
Chris Lattner64299f82008-01-10 01:53:41 +0000580 // FIXME: Read any files specified by -imacros.
581
582 // Add implicit #includes from -include.
583 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
584 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000585
586 // Null terminate PredefinedBuffer and add it.
587 PredefineBuffer.push_back(0);
588 PP.setPredefines(&PredefineBuffer[0]);
589
590 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000591 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000592}
593
594//===----------------------------------------------------------------------===//
595// Preprocessor include path information.
596//===----------------------------------------------------------------------===//
597
598// This tool exports a large number of command line options to control how the
599// preprocessor searches for header files. At root, however, the Preprocessor
600// object takes a very simple interface: a list of directories to search for
601//
602// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000603// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000604//
Chris Lattner64299f82008-01-10 01:53:41 +0000605// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000606
607static llvm::cl::opt<bool>
608nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
609
610// Various command line options. These four add directories to each chain.
611static llvm::cl::list<std::string>
612F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
613 llvm::cl::desc("Add directory to framework include search path"));
614static llvm::cl::list<std::string>
615I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
616 llvm::cl::desc("Add directory to include search path"));
617static llvm::cl::list<std::string>
618idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
619 llvm::cl::desc("Add directory to AFTER include search path"));
620static llvm::cl::list<std::string>
621iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
622 llvm::cl::desc("Add directory to QUOTE include search path"));
623static llvm::cl::list<std::string>
624isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
625 llvm::cl::desc("Add directory to SYSTEM include search path"));
626
627// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
628static llvm::cl::list<std::string>
629iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
630 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
631static llvm::cl::list<std::string>
632iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
633 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
634static llvm::cl::list<std::string>
635iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
636 llvm::cl::Prefix,
637 llvm::cl::desc("Set directory to include search path with prefix"));
638
Chris Lattner0c946412007-08-26 17:47:35 +0000639static llvm::cl::opt<std::string>
640isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
641 llvm::cl::desc("Set the system root directory (usually /)"));
642
Reid Spencer5f016e22007-07-11 17:01:13 +0000643// Finally, implement the code that groks the options above.
644enum IncludeDirGroup {
645 Quoted = 0,
646 Angled,
647 System,
648 After
649};
650
651static std::vector<DirectoryLookup> IncludeGroup[4];
652
653/// AddPath - Add the specified path to the specified group list.
654///
655static void AddPath(const std::string &Path, IncludeDirGroup Group,
656 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000657 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000658 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000659 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000660
Chris Lattnerd6655272007-12-17 05:59:27 +0000661 // Compute the actual path, taking into consideration -isysroot.
662 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000663
Chris Lattnerd6655272007-12-17 05:59:27 +0000664 // Handle isysroot.
665 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000666 // FIXME: Portability. This should be a sys::Path interface, this doesn't
667 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000668 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
669 MappedPath.append(isysroot.begin(), isysroot.end());
670 if (Path[0] != '/') // If in the system group, add a /.
671 MappedPath.push_back('/');
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 }
673
Chris Lattnerd6655272007-12-17 05:59:27 +0000674 MappedPath.append(Path.begin(), Path.end());
675
676 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 DirectoryLookup::DirType Type;
678 if (Group == Quoted || Group == Angled)
679 Type = DirectoryLookup::NormalHeaderDir;
680 else if (isCXXAware)
681 Type = DirectoryLookup::SystemHeaderDir;
682 else
683 Type = DirectoryLookup::ExternCSystemHeaderDir;
684
Chris Lattnerd6655272007-12-17 05:59:27 +0000685
686 // If the directory exists, add it.
687 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
688 &MappedPath[0]+
689 MappedPath.size())) {
690 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
691 isFramework));
692 return;
693 }
694
Chris Lattnerdf772332007-12-17 07:52:39 +0000695 // Check to see if this is an apple-style headermap (which are not allowed to
696 // be frameworks).
697 if (!isFramework) {
698 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
699 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000700 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
701 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000702 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
703 return;
704 }
Chris Lattner822da612007-12-17 06:36:45 +0000705 }
706 }
707
Chris Lattnerd6655272007-12-17 05:59:27 +0000708 if (Verbose)
709 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000710}
711
712/// RemoveDuplicates - If there are duplicate directory entries in the specified
713/// search list, remove the later (dead) ones.
714static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000715 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000716 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000717 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000719 if (SearchList[i].isNormalDir()) {
720 // If this isn't the first time we've seen this dir, remove it.
721 if (SeenDirs.insert(SearchList[i].getDir()))
722 continue;
723
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 if (Verbose)
725 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
726 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000727 } else if (SearchList[i].isFramework()) {
728 // If this isn't the first time we've seen this framework dir, remove it.
729 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
730 continue;
731
732 if (Verbose)
733 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
734 SearchList[i].getFrameworkDir()->getName());
735
Chris Lattnerb94c7072007-12-17 06:44:29 +0000736 } else {
737 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
738 // If this isn't the first time we've seen this headermap, remove it.
739 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
740 continue;
741
742 if (Verbose)
743 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
744 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000746
747 // This is reached if the current entry is a duplicate.
748 SearchList.erase(SearchList.begin()+i);
749 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 }
751}
752
753/// InitializeIncludePaths - Process the -I options and set them in the
754/// HeaderSearch object.
755static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000756 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 // Handle -F... options.
758 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000759 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000760
761 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000762 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000763 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000764
765 // Handle -idirafter... options.
766 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000767 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000768
769 // Handle -iquote... options.
770 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000771 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000772
773 // Handle -isystem... options.
774 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000775 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000776
777 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
778 // parallel, processing the values in order of occurance to get the right
779 // prefixes.
780 {
781 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
782 unsigned iprefix_idx = 0;
783 unsigned iwithprefix_idx = 0;
784 unsigned iwithprefixbefore_idx = 0;
785 bool iprefix_done = iprefix_vals.empty();
786 bool iwithprefix_done = iwithprefix_vals.empty();
787 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
788 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
789 if (!iprefix_done &&
790 (iwithprefix_done ||
791 iprefix_vals.getPosition(iprefix_idx) <
792 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
793 (iwithprefixbefore_done ||
794 iprefix_vals.getPosition(iprefix_idx) <
795 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
796 Prefix = iprefix_vals[iprefix_idx];
797 ++iprefix_idx;
798 iprefix_done = iprefix_idx == iprefix_vals.size();
799 } else if (!iwithprefix_done &&
800 (iwithprefixbefore_done ||
801 iwithprefix_vals.getPosition(iwithprefix_idx) <
802 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
803 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000804 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 ++iwithprefix_idx;
806 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
807 } else {
808 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000809 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 ++iwithprefixbefore_idx;
811 iwithprefixbefore_done =
812 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
813 }
814 }
815 }
816
817 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
818 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
819
820 // FIXME: temporary hack: hard-coded paths.
821 // FIXME: get these from the target?
822 if (!nostdinc) {
823 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000824 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000825 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000826 false, Headers);
827 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
828 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 }
830
Chris Lattner822da612007-12-17 06:36:45 +0000831 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000832 // leopard
833 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000834 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000835 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000836 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
838 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000839 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000840
841 // tiger
842 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000843 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000844 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000845 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000846 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
847 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000848 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000849
Chris Lattner822da612007-12-17 06:36:45 +0000850 AddPath("/usr/include", System, false, false, false, Headers);
851 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
852 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000853 }
854
855 // Now that we have collected all of the include paths, merge them all
856 // together and tell the preprocessor about them.
857
858 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
859 std::vector<DirectoryLookup> SearchList;
860 SearchList = IncludeGroup[Angled];
861 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
862 IncludeGroup[System].end());
863 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
864 IncludeGroup[After].end());
865 RemoveDuplicates(SearchList);
866 RemoveDuplicates(IncludeGroup[Quoted]);
867
868 // Prepend QUOTED list on the search list.
869 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
870 IncludeGroup[Quoted].end());
871
872
873 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
874 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
875 DontSearchCurDir);
876
877 // If verbose, print the list of directories that will be searched.
878 if (Verbose) {
879 fprintf(stderr, "#include \"...\" search starts here:\n");
880 unsigned QuotedIdx = IncludeGroup[Quoted].size();
881 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
882 if (i == QuotedIdx)
883 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000884 const char *Name = SearchList[i].getName();
885 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000886 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000887 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000888 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000889 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000890 else {
891 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000892 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000893 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000894 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 }
Chris Lattner80e17152007-12-15 23:11:06 +0000896 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 }
898}
899
900
Reid Spencer5f016e22007-07-11 17:01:13 +0000901//===----------------------------------------------------------------------===//
902// Basic Parser driver
903//===----------------------------------------------------------------------===//
904
Ted Kremenek95041a22007-12-19 22:51:13 +0000905static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000907 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000908
909 // Parsing the specified input file.
910 P.ParseTranslationUnit();
911 delete PA;
912}
913
914//===----------------------------------------------------------------------===//
915// Main driver
916//===----------------------------------------------------------------------===//
917
Ted Kremenekdb094a22007-12-05 18:27:04 +0000918/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
919/// action. These consumers can operate on both ASTs that are freshly
920/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000921static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000922 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremenekdb094a22007-12-05 18:27:04 +0000923 const LangOptions& LangOpts) {
924 switch (ProgAction) {
925 default:
926 return NULL;
927
928 case ASTPrint:
929 return CreateASTPrinter();
930
931 case ASTDump:
932 return CreateASTDumper();
933
934 case ASTView:
935 return CreateASTViewer();
936
937 case ParseCFGDump:
938 case ParseCFGView:
939 return CreateCFGDumper(ProgAction == ParseCFGView);
940
941 case AnalysisLiveVariables:
942 return CreateLiveVarAnalyzer();
943
944 case WarnDeadStores:
945 return CreateDeadStoreChecker(Diag);
946
947 case WarnUninitVals:
948 return CreateUnitValsChecker(Diag);
949
Ted Kremeneke603df42008-01-08 18:04:06 +0000950 case AnalysisGRConstProp:
951 return CreateGRConstProp();
952
Ted Kremenekdb094a22007-12-05 18:27:04 +0000953 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000954 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000955
956 case EmitLLVM:
957 return CreateLLVMEmitter(Diag, LangOpts);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000958
959 case EmitBC:
960 return CreateBCWriter(InFile, OutputFile, Diag, LangOpts);
961
Ted Kremenek3910c7c2007-12-19 17:25:59 +0000962 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000963 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +0000964 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000965
Ted Kremenekdb094a22007-12-05 18:27:04 +0000966 case RewriteTest:
967 return CreateCodeRewriterTest(Diag);
968 }
969}
970
Reid Spencer5f016e22007-07-11 17:01:13 +0000971/// ProcessInputFile - Process a single input file with the specified state.
972///
Ted Kremenek7dcc9682007-12-19 22:32:34 +0000973static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +0000974 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000975
976 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000977 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000978
Reid Spencer5f016e22007-07-11 17:01:13 +0000979 switch (ProgAction) {
980 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000981 Consumer = CreateASTConsumer(InFile,
982 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +0000983 PP.getFileManager(),
Ted Kremenekdb094a22007-12-05 18:27:04 +0000984 PP.getLangOptions());
985
986 if (!Consumer) {
987 fprintf(stderr, "Unexpected program action!\n");
988 return;
989 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000990
Ted Kremenekdb094a22007-12-05 18:27:04 +0000991 break;
992
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000994 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000995 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000996 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 do {
998 PP.Lex(Tok);
999 PP.DumpToken(Tok, true);
1000 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001001 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001002 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 break;
1004 }
1005 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001006 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001007 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001008 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001009 do {
1010 PP.Lex(Tok);
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
1016 case PrintPreprocessedInput: // -E mode.
Ted Kremenek95041a22007-12-19 22:51:13 +00001017 DoPrintPreprocessedInput(PP);
Chris Lattnerbd247762007-07-22 06:05:44 +00001018 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001019 break;
1020
1021 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001022 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001023 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 break;
1025
1026 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001027 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001028 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001029 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001030
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001031 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001032 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001033 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001034 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001035
1036 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001037 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001038 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001039
1040 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001041 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 }
1043
1044 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001045 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001046 PP.PrintStats();
1047 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001048 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001049 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001050 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 fprintf(stderr, "\n");
1052 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001053
1054 // For a multi-file compilation, some things are ok with nuking the source
1055 // manager tables, other require stable fileid/macroid's across multiple
1056 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001057 if (ClearSourceMgr)
1058 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001059}
1060
Ted Kremenek20e97482007-12-12 23:41:08 +00001061static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1062 FileManager& FileMgr) {
1063
1064 if (VerifyDiagnostics) {
1065 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1066 exit (1);
1067 }
1068
1069 llvm::sys::Path Filename(InFile);
1070
1071 if (!Filename.isValid()) {
1072 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1073 exit (1);
1074 }
1075
Ted Kremenekee533642007-12-20 19:47:16 +00001076 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001077
1078 if (!TU) {
1079 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1080 InFile.c_str());
1081 exit (1);
1082 }
1083
Ted Kremenek63ea8632007-12-19 19:27:38 +00001084 // Observe that we use the source file name stored in the deserialized
1085 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001086 llvm::OwningPtr<ASTConsumer>
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001087 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts()));
Ted Kremenek20e97482007-12-12 23:41:08 +00001088
1089 if (!Consumer) {
1090 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1091 exit (1);
1092 }
1093
Ted Kremenek95041a22007-12-19 22:51:13 +00001094 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001095
1096 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1097 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001098}
1099
1100
Reid Spencer5f016e22007-07-11 17:01:13 +00001101static llvm::cl::list<std::string>
1102InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1103
Ted Kremenek20e97482007-12-12 23:41:08 +00001104static bool isSerializedFile(const std::string& InFile) {
1105 if (InFile.size() < 4)
1106 return false;
1107
1108 const char* s = InFile.c_str()+InFile.size()-4;
1109
1110 return s[0] == '.' &&
1111 s[1] == 'a' &&
1112 s[2] == 's' &&
1113 s[3] == 't';
1114}
1115
Reid Spencer5f016e22007-07-11 17:01:13 +00001116
1117int main(int argc, char **argv) {
1118 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1119 llvm::sys::PrintStackTraceOnErrorSignal();
1120
1121 // If no input was specified, read from stdin.
1122 if (InputFilenames.empty())
1123 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001124
Reid Spencer5f016e22007-07-11 17:01:13 +00001125 // Create a file manager object to provide access to and cache the filesystem.
1126 FileManager FileMgr;
1127
Ted Kremenek31e703b2007-12-11 23:28:38 +00001128 // Create the diagnostic client for reporting errors or for
1129 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001131 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001133 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 } else {
1135 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001136 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001137
1138 if (InputFilenames.size() != 1) {
1139 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001140 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 return 1;
1142 }
1143 }
1144
1145 // Configure our handling of diagnostics.
1146 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001147 InitializeDiagnostics(Diags);
1148
Chris Lattner4f037832007-12-05 23:24:17 +00001149 // -I- is a deprecated GCC feature, scan for it and reject it.
1150 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1151 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001152 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001153 I_dirs.erase(I_dirs.begin()+i);
1154 --i;
1155 }
1156 }
1157
Reid Spencer5f016e22007-07-11 17:01:13 +00001158 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001159 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001160
Ted Kremenek20e97482007-12-12 23:41:08 +00001161 if (isSerializedFile(InFile))
1162 ProcessSerializedFile(InFile,Diags,FileMgr);
1163 else {
1164 /// Create a SourceManager object. This tracks and owns all the file
1165 /// buffers allocated to a translation unit.
1166 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001167
Ted Kremenek20e97482007-12-12 23:41:08 +00001168 // Initialize language options, inferring file types from input filenames.
1169 LangOptions LangInfo;
1170 InitializeBaseLanguage();
1171 LangKind LK = GetLanguage(InFile);
1172 InitializeLangOptions(LangInfo, LK);
1173 InitializeLanguageStandard(LangInfo, LK);
1174
1175 // Process the -I options and set them in the HeaderInfo.
1176 HeaderSearch HeaderInfo(FileMgr);
1177 DiagClient->setHeaderSearch(HeaderInfo);
1178 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1179
1180 // Get information about the targets being compiled for. Note that this
1181 // pointer and the TargetInfoImpl objects are never deleted by this toy
1182 // driver.
1183 TargetInfo *Target;
1184
1185 // Create triples, and create the TargetInfo.
1186 std::vector<std::string> triples;
1187 CreateTargetTriples(triples);
1188 Target = TargetInfo::CreateTargetInfo(&triples[0],
1189 &triples[0]+triples.size(),
1190 &Diags);
1191
1192 if (Target == 0) {
1193 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1194 triples[0].c_str());
1195 fprintf(stderr, "Please use -triple or -arch.\n");
1196 exit(1);
1197 }
1198
1199 // Set up the preprocessor with these options.
1200 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1201
1202 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001203 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001204 continue;
1205
Ted Kremenek1036b682007-12-19 23:48:45 +00001206 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001207 HeaderInfo.ClearFileInfo();
1208
1209 if (Stats)
1210 SourceMgr.PrintStats();
1211 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 }
1213
1214 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1215
1216 if (NumDiagnostics)
1217 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1218 (NumDiagnostics == 1 ? "" : "s"));
1219
1220 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 FileMgr.PrintStats();
1222 fprintf(stderr, "\n");
1223 }
1224
Chris Lattner96f1a642007-07-21 05:40:53 +00001225 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001226}