blob: 91bd117200308d30e94429df2276db8197c2be70 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000029#include "clang/AST/TranslationUnit.h"
Chris Lattner556beb72007-09-15 22:56:56 +000030#include "clang/Sema/ASTStreamer.h"
31#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "clang/Parse/Parser.h"
33#include "clang/Lex/HeaderSearch.h"
34#include "clang/Basic/FileManager.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/TargetInfo.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000037#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/MemoryBuffer.h"
40#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000041#include "llvm/Config/config.h"
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>
53Stats("stats", llvm::cl::desc("Print performance metrics and statistics"));
54
55enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000056 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000057 EmitLLVM, // Emit a .ll file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000058 SerializeAST, // Emit a .ast file.
Chris Lattner3b427b32007-10-11 00:18:28 +000059 ASTPrint, // Parse ASTs and print them.
60 ASTDump, // Parse ASTs and dump them.
61 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000062 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000063 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000064 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek055c2752007-09-06 23:00:42 +000065 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000066 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000067 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000068 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000069 ParsePrintCallbacks, // Parse and print each callback.
70 ParseSyntaxOnly, // Parse and perform semantic analysis.
71 ParseNoop, // Parse with noop callbacks.
72 RunPreprocessorOnly, // Just lex, no output.
73 PrintPreprocessedInput, // -E mode.
74 DumpTokens // Token dump mode.
75};
76
77static llvm::cl::opt<ProgActions>
78ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
79 llvm::cl::init(ParseSyntaxOnly),
80 llvm::cl::values(
81 clEnumValN(RunPreprocessorOnly, "Eonly",
82 "Just run preprocessor, no output (for timings)"),
83 clEnumValN(PrintPreprocessedInput, "E",
84 "Run preprocessor, emit preprocessed file"),
85 clEnumValN(DumpTokens, "dumptokens",
86 "Run preprocessor, dump internal rep of tokens"),
87 clEnumValN(ParseNoop, "parse-noop",
88 "Run parser with noop callbacks (for timings)"),
89 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
90 "Run parser and perform semantic analysis"),
91 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
92 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +000093 clEnumValN(ASTPrint, "ast-print",
94 "Build ASTs and then pretty-print them"),
95 clEnumValN(ASTDump, "ast-dump",
96 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +000097 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +000098 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +000099 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000100 "Run parser, then build and print CFGs."),
101 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000102 "Run parser, then build and view CFGs with Graphviz."),
103 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000104 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000105 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000106 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000107 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000108 "Flag warnings of uses of unitialized variables."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000109 clEnumValN(TestSerialization, "test-pickling",
110 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000112 "Build ASTs then convert to LLVM, emit .ll file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000113 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000114 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000115 clEnumValN(RewriteTest, "rewrite-test",
116 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 clEnumValEnd));
118
Ted Kremenekccc76472007-12-19 19:47:59 +0000119
120static llvm::cl::opt<std::string>
121OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000122 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000123 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
124
Ted Kremenek41193e42007-09-26 19:42:19 +0000125static llvm::cl::opt<bool>
126VerifyDiagnostics("verify",
127 llvm::cl::desc("Verify emitted diagnostics and warnings."));
128
Reid Spencer5f016e22007-07-11 17:01:13 +0000129//===----------------------------------------------------------------------===//
130// Language Options
131//===----------------------------------------------------------------------===//
132
133enum LangKind {
134 langkind_unspecified,
135 langkind_c,
136 langkind_c_cpp,
137 langkind_cxx,
138 langkind_cxx_cpp,
139 langkind_objc,
140 langkind_objc_cpp,
141 langkind_objcxx,
142 langkind_objcxx_cpp
143};
144
145/* TODO: GCC also accepts:
146 c-header c++-header objective-c-header objective-c++-header
147 assembler assembler-with-cpp
148 ada, f77*, ratfor (!), f95, java, treelang
149 */
150static llvm::cl::opt<LangKind>
151BaseLang("x", llvm::cl::desc("Base language to compile"),
152 llvm::cl::init(langkind_unspecified),
153 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
154 clEnumValN(langkind_cxx, "c++", "C++"),
155 clEnumValN(langkind_objc, "objective-c", "Objective C"),
156 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
157 clEnumValN(langkind_c_cpp, "c-cpp-output",
158 "Preprocessed C"),
159 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
160 "Preprocessed C++"),
161 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
162 "Preprocessed Objective C"),
163 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
164 "Preprocessed Objective C++"),
165 clEnumValEnd));
166
167static llvm::cl::opt<bool>
168LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
169 llvm::cl::Hidden);
170static llvm::cl::opt<bool>
171LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
172 llvm::cl::Hidden);
173
Ted Kremenek8904f152007-12-05 23:49:08 +0000174/// InitializeBaseLanguage - Handle the -x foo options.
175static void InitializeBaseLanguage() {
176 if (LangObjC)
177 BaseLang = langkind_objc;
178 else if (LangObjCXX)
179 BaseLang = langkind_objcxx;
180}
181
182static LangKind GetLanguage(const std::string &Filename) {
183 if (BaseLang != langkind_unspecified)
184 return BaseLang;
185
186 std::string::size_type DotPos = Filename.rfind('.');
187
188 if (DotPos == std::string::npos) {
189 BaseLang = langkind_c; // Default to C if no extension.
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 }
191
Ted Kremenek8904f152007-12-05 23:49:08 +0000192 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
193 // C header: .h
194 // C++ header: .hh or .H;
195 // assembler no preprocessing: .s
196 // assembler: .S
197 if (Ext == "c")
198 return langkind_c;
199 else if (Ext == "i")
200 return langkind_c_cpp;
201 else if (Ext == "ii")
202 return langkind_cxx_cpp;
203 else if (Ext == "m")
204 return langkind_objc;
205 else if (Ext == "mi")
206 return langkind_objc_cpp;
207 else if (Ext == "mm" || Ext == "M")
208 return langkind_objcxx;
209 else if (Ext == "mii")
210 return langkind_objcxx_cpp;
211 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
212 Ext == "c++" || Ext == "cp" || Ext == "cxx")
213 return langkind_cxx;
214 else
215 return langkind_c;
216}
217
218
219static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000220 // FIXME: implement -fpreprocessed mode.
221 bool NoPreprocess = false;
222
Ted Kremenek8904f152007-12-05 23:49:08 +0000223 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000224 default: assert(0 && "Unknown language kind!");
225 case langkind_c_cpp:
226 NoPreprocess = true;
227 // FALLTHROUGH
228 case langkind_c:
229 break;
230 case langkind_cxx_cpp:
231 NoPreprocess = true;
232 // FALLTHROUGH
233 case langkind_cxx:
234 Options.CPlusPlus = 1;
235 break;
236 case langkind_objc_cpp:
237 NoPreprocess = true;
238 // FALLTHROUGH
239 case langkind_objc:
240 Options.ObjC1 = Options.ObjC2 = 1;
241 break;
242 case langkind_objcxx_cpp:
243 NoPreprocess = true;
244 // FALLTHROUGH
245 case langkind_objcxx:
246 Options.ObjC1 = Options.ObjC2 = 1;
247 Options.CPlusPlus = 1;
248 break;
249 }
250}
251
252/// LangStds - Language standards we support.
253enum LangStds {
254 lang_unspecified,
255 lang_c89, lang_c94, lang_c99,
256 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000257 lang_cxx98, lang_gnucxx98,
258 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000259};
260
261static llvm::cl::opt<LangStds>
262LangStd("std", llvm::cl::desc("Language standard to compile for"),
263 llvm::cl::init(lang_unspecified),
264 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
265 clEnumValN(lang_c89, "c90", "ISO C 1990"),
266 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
267 clEnumValN(lang_c94, "iso9899:199409",
268 "ISO C 1990 with amendment 1"),
269 clEnumValN(lang_c99, "c99", "ISO C 1999"),
270// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
271 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
272// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
273 clEnumValN(lang_gnu89, "gnu89",
274 "ISO C 1990 with GNU extensions (default for C)"),
275 clEnumValN(lang_gnu99, "gnu99",
276 "ISO C 1999 with GNU extensions"),
277 clEnumValN(lang_gnu99, "gnu9x",
278 "ISO C 1999 with GNU extensions"),
279 clEnumValN(lang_cxx98, "c++98",
280 "ISO C++ 1998 with amendments"),
281 clEnumValN(lang_gnucxx98, "gnu++98",
282 "ISO C++ 1998 with amendments and GNU "
283 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000284 clEnumValN(lang_cxx0x, "c++0x",
285 "Upcoming ISO C++ 200x with amendments"),
286 clEnumValN(lang_gnucxx0x, "gnu++0x",
287 "Upcoming ISO C++ 200x with amendments and GNU "
288 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 clEnumValEnd));
290
291static llvm::cl::opt<bool>
292NoOperatorNames("fno-operator-names",
293 llvm::cl::desc("Do not treat C++ operator name keywords as "
294 "synonyms for operators"));
295
Anders Carlssonee98ac52007-10-15 02:50:23 +0000296static llvm::cl::opt<bool>
297PascalStrings("fpascal-strings",
298 llvm::cl::desc("Recognize and construct Pascal-style "
299 "string literals"));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000300
301static llvm::cl::opt<bool>
302WritableStrings("fwritable-strings",
303 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000304
305static llvm::cl::opt<bool>
306LaxVectorConversions("flax-vector-conversions",
307 llvm::cl::desc("Allow implicit conversions between vectors"
308 " with a different number of elements or "
309 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000310// FIXME: add:
311// -ansi
312// -trigraphs
313// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000314// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000315static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 if (LangStd == lang_unspecified) {
317 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000318 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 default: assert(0 && "Unknown base language");
320 case langkind_c:
321 case langkind_c_cpp:
322 case langkind_objc:
323 case langkind_objc_cpp:
324 LangStd = lang_gnu99;
325 break;
326 case langkind_cxx:
327 case langkind_cxx_cpp:
328 case langkind_objcxx:
329 case langkind_objcxx_cpp:
330 LangStd = lang_gnucxx98;
331 break;
332 }
333 }
334
335 switch (LangStd) {
336 default: assert(0 && "Unknown language standard!");
337
338 // Fall through from newer standards to older ones. This isn't really right.
339 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000340 case lang_gnucxx0x:
341 case lang_cxx0x:
342 Options.CPlusPlus0x = 1;
343 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 case lang_gnucxx98:
345 case lang_cxx98:
346 Options.CPlusPlus = 1;
347 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000348 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 // FALL THROUGH.
350 case lang_gnu99:
351 case lang_c99:
352 Options.Digraphs = 1;
353 Options.C99 = 1;
354 Options.HexFloats = 1;
355 // FALL THROUGH.
356 case lang_gnu89:
357 Options.BCPLComment = 1; // Only for C99/C++.
358 // FALL THROUGH.
359 case lang_c94:
360 case lang_c89:
361 break;
362 }
363
364 Options.Trigraphs = 1; // -trigraphs or -ansi
365 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000366 Options.PascalStrings = PascalStrings;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000367 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000368 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000369}
370
371//===----------------------------------------------------------------------===//
372// Our DiagnosticClient implementation
373//===----------------------------------------------------------------------===//
374
375// FIXME: Werror should take a list of things, -Werror=foo,bar
376static llvm::cl::opt<bool>
377WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
378
379static llvm::cl::opt<bool>
380WarnOnExtensions("pedantic", llvm::cl::init(false),
381 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
382
383static llvm::cl::opt<bool>
384ErrorOnExtensions("pedantic-errors",
385 llvm::cl::desc("Issue an error on uses of GCC extensions"));
386
387static llvm::cl::opt<bool>
388WarnUnusedMacros("Wunused_macros",
389 llvm::cl::desc("Warn for unused macros in the main translation unit"));
390
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000391static llvm::cl::opt<bool>
392WarnFloatEqual("Wfloat-equal",
393 llvm::cl::desc("Warn about equality comparisons of floating point values."));
394
Ted Kremenek73da5902007-12-17 17:50:07 +0000395static llvm::cl::opt<bool>
396WarnNoFormatNonLiteral("Wno-format-nonliteral",
397 llvm::cl::desc("Do not warn about non-literal format strings."));
398
Reid Spencer5f016e22007-07-11 17:01:13 +0000399/// InitializeDiagnostics - Initialize the diagnostic object, based on the
400/// current command line option settings.
401static void InitializeDiagnostics(Diagnostic &Diags) {
402 Diags.setWarningsAsErrors(WarningsAsErrors);
403 Diags.setWarnOnExtensions(WarnOnExtensions);
404 Diags.setErrorOnExtensions(ErrorOnExtensions);
405
406 // Silence the "macro is not used" warning unless requested.
407 if (!WarnUnusedMacros)
408 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000409
410 // Silence "floating point comparison" warnings unless requested.
411 if (!WarnFloatEqual)
412 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000413
414 // Silence "format string is not a string literal" warnings if requested
415 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000416 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
417 diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000418
Reid Spencer5f016e22007-07-11 17:01:13 +0000419}
420
421//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000422// Target Triple Processing.
423//===----------------------------------------------------------------------===//
424
425static llvm::cl::opt<std::string>
426TargetTriple("triple",
427 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
428
429static llvm::cl::list<std::string>
430Archs("arch",
431 llvm::cl::desc("Specify target architecture (e.g. i686)."));
432
433namespace {
434 class TripleProcessor {
435 llvm::StringMap<char> TriplesProcessed;
436 std::vector<std::string>& triples;
437 public:
438 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
439
440 void addTriple(const std::string& t) {
441 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
442 TriplesProcessed.end()) {
443 triples.push_back(t);
444 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
445 }
446 }
447 };
448}
449
450static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000451 // Initialize base triple. If a -triple option has been specified, use
452 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000453 std::string Triple = TargetTriple;
454 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000455
456 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000457 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000458
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000459 if (firstDash == std::string::npos) {
460 fprintf(stderr,
461 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000462 Triple.c_str());
463 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000464 }
Ted Kremenekae360762007-12-03 22:06:55 +0000465
Chris Lattner6590d212007-12-12 05:01:48 +0000466 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000467
468 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000469 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
470 Triple.c_str());
471 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000472 }
Ted Kremenekae360762007-12-03 22:06:55 +0000473
474 // Create triple cacher.
475 TripleProcessor tp(triples);
476
477 // Add the primary triple to our set of triples if we are using the
478 // host-triple with no archs or using a specified target triple.
479 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000480 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000481
482 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
483 tp.addTriple(Archs[i] + "-" + suffix);
484}
485
486//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000487// Preprocessor Initialization
488//===----------------------------------------------------------------------===//
489
490// FIXME: Preprocessor builtins to support.
491// -A... - Play with #assertions
492// -undef - Undefine all predefined macros
493
494static llvm::cl::list<std::string>
495D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
496 llvm::cl::desc("Predefine the specified macro"));
497static llvm::cl::list<std::string>
498U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
499 llvm::cl::desc("Undefine the specified macro"));
500
501// Append a #define line to Buf for Macro. Macro should be of the form XXX,
502// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
503// "#define XXX Y z W". To get a #define with no value, use "XXX=".
504static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
505 const char *Command = "#define ") {
506 Buf.insert(Buf.end(), Command, Command+strlen(Command));
507 if (const char *Equal = strchr(Macro, '=')) {
508 // Turn the = into ' '.
509 Buf.insert(Buf.end(), Macro, Equal);
510 Buf.push_back(' ');
511 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
512 } else {
513 // Push "macroname 1".
514 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
515 Buf.push_back(' ');
516 Buf.push_back('1');
517 }
518 Buf.push_back('\n');
519}
520
Reid Spencer5f016e22007-07-11 17:01:13 +0000521
Chris Lattner53b0dab2007-10-09 22:10:18 +0000522/// InitializePreprocessor - Initialize the preprocessor getting it and the
523/// environment ready to process a single file. This returns the file ID for the
524/// input file. If a failure happens, it returns 0.
525///
526static unsigned InitializePreprocessor(Preprocessor &PP,
527 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000528 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000529
Chris Lattnerdee73592007-12-15 20:48:40 +0000530 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000531
Chris Lattner53b0dab2007-10-09 22:10:18 +0000532 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000533 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000534 if (InFile != "-") {
535 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000536 if (File) SourceMgr.createMainFileID(File, SourceLocation());
537 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000538 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
539 return 0;
540 }
541 } else {
542 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000543 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
544 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000545 fprintf(stderr, "Error reading standard input! Empty?\n");
546 return 0;
547 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 }
549
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 // Add macros from the command line.
551 // FIXME: Should traverse the #define/#undef lists in parallel.
552 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000553 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000554 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000555 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
556
557 // FIXME: Read any files specified by -imacros or -include.
558
559 // Null terminate PredefinedBuffer and add it.
560 PredefineBuffer.push_back(0);
561 PP.setPredefines(&PredefineBuffer[0]);
562
563 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000564 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000565}
566
567//===----------------------------------------------------------------------===//
568// Preprocessor include path information.
569//===----------------------------------------------------------------------===//
570
571// This tool exports a large number of command line options to control how the
572// preprocessor searches for header files. At root, however, the Preprocessor
573// object takes a very simple interface: a list of directories to search for
574//
575// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000576// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000577//
578// FIXME: -include,-imacros
579
580static llvm::cl::opt<bool>
581nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
582
583// Various command line options. These four add directories to each chain.
584static llvm::cl::list<std::string>
585F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
586 llvm::cl::desc("Add directory to framework include search path"));
587static llvm::cl::list<std::string>
588I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
589 llvm::cl::desc("Add directory to include search path"));
590static llvm::cl::list<std::string>
591idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
592 llvm::cl::desc("Add directory to AFTER include search path"));
593static llvm::cl::list<std::string>
594iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
595 llvm::cl::desc("Add directory to QUOTE include search path"));
596static llvm::cl::list<std::string>
597isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
598 llvm::cl::desc("Add directory to SYSTEM include search path"));
599
600// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
601static llvm::cl::list<std::string>
602iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
603 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
604static llvm::cl::list<std::string>
605iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
606 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
607static llvm::cl::list<std::string>
608iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
609 llvm::cl::Prefix,
610 llvm::cl::desc("Set directory to include search path with prefix"));
611
Chris Lattner0c946412007-08-26 17:47:35 +0000612static llvm::cl::opt<std::string>
613isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
614 llvm::cl::desc("Set the system root directory (usually /)"));
615
Reid Spencer5f016e22007-07-11 17:01:13 +0000616// Finally, implement the code that groks the options above.
617enum IncludeDirGroup {
618 Quoted = 0,
619 Angled,
620 System,
621 After
622};
623
624static std::vector<DirectoryLookup> IncludeGroup[4];
625
626/// AddPath - Add the specified path to the specified group list.
627///
628static void AddPath(const std::string &Path, IncludeDirGroup Group,
629 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000630 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000631 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000632 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000633
Chris Lattnerd6655272007-12-17 05:59:27 +0000634 // Compute the actual path, taking into consideration -isysroot.
635 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000636
Chris Lattnerd6655272007-12-17 05:59:27 +0000637 // Handle isysroot.
638 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000639 // FIXME: Portability. This should be a sys::Path interface, this doesn't
640 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000641 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
642 MappedPath.append(isysroot.begin(), isysroot.end());
643 if (Path[0] != '/') // If in the system group, add a /.
644 MappedPath.push_back('/');
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 }
646
Chris Lattnerd6655272007-12-17 05:59:27 +0000647 MappedPath.append(Path.begin(), Path.end());
648
649 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000650 DirectoryLookup::DirType Type;
651 if (Group == Quoted || Group == Angled)
652 Type = DirectoryLookup::NormalHeaderDir;
653 else if (isCXXAware)
654 Type = DirectoryLookup::SystemHeaderDir;
655 else
656 Type = DirectoryLookup::ExternCSystemHeaderDir;
657
Chris Lattnerd6655272007-12-17 05:59:27 +0000658
659 // If the directory exists, add it.
660 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
661 &MappedPath[0]+
662 MappedPath.size())) {
663 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
664 isFramework));
665 return;
666 }
667
Chris Lattnerdf772332007-12-17 07:52:39 +0000668 // Check to see if this is an apple-style headermap (which are not allowed to
669 // be frameworks).
670 if (!isFramework) {
671 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
672 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000673 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
674 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000675 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
676 return;
677 }
Chris Lattner822da612007-12-17 06:36:45 +0000678 }
679 }
680
Chris Lattnerd6655272007-12-17 05:59:27 +0000681 if (Verbose)
682 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000683}
684
685/// RemoveDuplicates - If there are duplicate directory entries in the specified
686/// search list, remove the later (dead) ones.
687static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000688 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000689 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000690 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000692 if (SearchList[i].isNormalDir()) {
693 // If this isn't the first time we've seen this dir, remove it.
694 if (SeenDirs.insert(SearchList[i].getDir()))
695 continue;
696
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 if (Verbose)
698 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
699 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000700 } else if (SearchList[i].isFramework()) {
701 // If this isn't the first time we've seen this framework dir, remove it.
702 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
703 continue;
704
705 if (Verbose)
706 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
707 SearchList[i].getFrameworkDir()->getName());
708
Chris Lattnerb94c7072007-12-17 06:44:29 +0000709 } else {
710 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
711 // If this isn't the first time we've seen this headermap, remove it.
712 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
713 continue;
714
715 if (Verbose)
716 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
717 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000719
720 // This is reached if the current entry is a duplicate.
721 SearchList.erase(SearchList.begin()+i);
722 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000723 }
724}
725
726/// InitializeIncludePaths - Process the -I options and set them in the
727/// HeaderSearch object.
728static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000729 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 // Handle -F... options.
731 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000732 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000733
734 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000735 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000736 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000737
738 // Handle -idirafter... options.
739 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000740 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000741
742 // Handle -iquote... options.
743 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000744 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000745
746 // Handle -isystem... options.
747 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000748 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000749
750 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
751 // parallel, processing the values in order of occurance to get the right
752 // prefixes.
753 {
754 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
755 unsigned iprefix_idx = 0;
756 unsigned iwithprefix_idx = 0;
757 unsigned iwithprefixbefore_idx = 0;
758 bool iprefix_done = iprefix_vals.empty();
759 bool iwithprefix_done = iwithprefix_vals.empty();
760 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
761 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
762 if (!iprefix_done &&
763 (iwithprefix_done ||
764 iprefix_vals.getPosition(iprefix_idx) <
765 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
766 (iwithprefixbefore_done ||
767 iprefix_vals.getPosition(iprefix_idx) <
768 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
769 Prefix = iprefix_vals[iprefix_idx];
770 ++iprefix_idx;
771 iprefix_done = iprefix_idx == iprefix_vals.size();
772 } else if (!iwithprefix_done &&
773 (iwithprefixbefore_done ||
774 iwithprefix_vals.getPosition(iwithprefix_idx) <
775 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
776 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000777 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 ++iwithprefix_idx;
779 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
780 } else {
781 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000782 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 ++iwithprefixbefore_idx;
784 iwithprefixbefore_done =
785 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
786 }
787 }
788 }
789
790 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
791 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
792
793 // FIXME: temporary hack: hard-coded paths.
794 // FIXME: get these from the target?
795 if (!nostdinc) {
796 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000797 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000799 false, Headers);
800 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
801 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000802 }
803
Chris Lattner822da612007-12-17 06:36:45 +0000804 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 // leopard
806 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000807 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000809 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
811 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000812 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000813
814 // tiger
815 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000816 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000818 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000819 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
820 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000821 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000822
Chris Lattner822da612007-12-17 06:36:45 +0000823 AddPath("/usr/include", System, false, false, false, Headers);
824 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
825 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000826 }
827
828 // Now that we have collected all of the include paths, merge them all
829 // together and tell the preprocessor about them.
830
831 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
832 std::vector<DirectoryLookup> SearchList;
833 SearchList = IncludeGroup[Angled];
834 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
835 IncludeGroup[System].end());
836 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
837 IncludeGroup[After].end());
838 RemoveDuplicates(SearchList);
839 RemoveDuplicates(IncludeGroup[Quoted]);
840
841 // Prepend QUOTED list on the search list.
842 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
843 IncludeGroup[Quoted].end());
844
845
846 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
847 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
848 DontSearchCurDir);
849
850 // If verbose, print the list of directories that will be searched.
851 if (Verbose) {
852 fprintf(stderr, "#include \"...\" search starts here:\n");
853 unsigned QuotedIdx = IncludeGroup[Quoted].size();
854 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
855 if (i == QuotedIdx)
856 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000857 const char *Name = SearchList[i].getName();
858 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000859 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000860 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000861 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000862 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000863 else {
864 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000865 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000866 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000867 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 }
Chris Lattner80e17152007-12-15 23:11:06 +0000869 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000870 }
871}
872
873
Reid Spencer5f016e22007-07-11 17:01:13 +0000874//===----------------------------------------------------------------------===//
875// Basic Parser driver
876//===----------------------------------------------------------------------===//
877
Ted Kremenek95041a22007-12-19 22:51:13 +0000878static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000880 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000881
882 // Parsing the specified input file.
883 P.ParseTranslationUnit();
884 delete PA;
885}
886
887//===----------------------------------------------------------------------===//
888// Main driver
889//===----------------------------------------------------------------------===//
890
Ted Kremenekdb094a22007-12-05 18:27:04 +0000891/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
892/// action. These consumers can operate on both ASTs that are freshly
893/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000894static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000895 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremenekdb094a22007-12-05 18:27:04 +0000896 const LangOptions& LangOpts) {
897 switch (ProgAction) {
898 default:
899 return NULL;
900
901 case ASTPrint:
902 return CreateASTPrinter();
903
904 case ASTDump:
905 return CreateASTDumper();
906
907 case ASTView:
908 return CreateASTViewer();
909
910 case ParseCFGDump:
911 case ParseCFGView:
912 return CreateCFGDumper(ProgAction == ParseCFGView);
913
914 case AnalysisLiveVariables:
915 return CreateLiveVarAnalyzer();
916
917 case WarnDeadStores:
918 return CreateDeadStoreChecker(Diag);
919
920 case WarnUninitVals:
921 return CreateUnitValsChecker(Diag);
922
923 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000924 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000925
926 case EmitLLVM:
927 return CreateLLVMEmitter(Diag, LangOpts);
928
Ted Kremenek3910c7c2007-12-19 17:25:59 +0000929 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000930 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +0000931 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000932
Ted Kremenekdb094a22007-12-05 18:27:04 +0000933 case RewriteTest:
934 return CreateCodeRewriterTest(Diag);
935 }
936}
937
Reid Spencer5f016e22007-07-11 17:01:13 +0000938/// ProcessInputFile - Process a single input file with the specified state.
939///
Ted Kremenek7dcc9682007-12-19 22:32:34 +0000940static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +0000941 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000942
943 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000944 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000945
Reid Spencer5f016e22007-07-11 17:01:13 +0000946 switch (ProgAction) {
947 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000948 Consumer = CreateASTConsumer(InFile,
949 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +0000950 PP.getFileManager(),
Ted Kremenekdb094a22007-12-05 18:27:04 +0000951 PP.getLangOptions());
952
953 if (!Consumer) {
954 fprintf(stderr, "Unexpected program action!\n");
955 return;
956 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000957
Ted Kremenekdb094a22007-12-05 18:27:04 +0000958 break;
959
Reid Spencer5f016e22007-07-11 17:01:13 +0000960 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000961 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000962 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000963 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 do {
965 PP.Lex(Tok);
966 PP.DumpToken(Tok, true);
967 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000968 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000969 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 break;
971 }
972 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000973 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000975 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 do {
977 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000978 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000979 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 break;
981 }
982
983 case PrintPreprocessedInput: // -E mode.
Ted Kremenek95041a22007-12-19 22:51:13 +0000984 DoPrintPreprocessedInput(PP);
Chris Lattnerbd247762007-07-22 06:05:44 +0000985 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000986 break;
987
988 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +0000989 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +0000990 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000991 break;
992
993 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +0000994 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +0000995 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000996 break;
Ted Kremenek44579782007-09-25 18:37:20 +0000997
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000998 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000999 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001000 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001001 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001002
1003 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001004 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001005 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001006
1007 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001008 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001009 }
1010
1011 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001012 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 PP.PrintStats();
1014 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001015 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001016 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001017 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 fprintf(stderr, "\n");
1019 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001020
1021 // For a multi-file compilation, some things are ok with nuking the source
1022 // manager tables, other require stable fileid/macroid's across multiple
1023 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001024 if (ClearSourceMgr)
1025 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001026}
1027
Ted Kremenek20e97482007-12-12 23:41:08 +00001028static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1029 FileManager& FileMgr) {
1030
1031 if (VerifyDiagnostics) {
1032 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1033 exit (1);
1034 }
1035
1036 llvm::sys::Path Filename(InFile);
1037
1038 if (!Filename.isValid()) {
1039 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1040 exit (1);
1041 }
1042
Ted Kremenekee533642007-12-20 19:47:16 +00001043 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001044
1045 if (!TU) {
1046 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1047 InFile.c_str());
1048 exit (1);
1049 }
1050
Ted Kremenek63ea8632007-12-19 19:27:38 +00001051 // Observe that we use the source file name stored in the deserialized
1052 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001053 llvm::OwningPtr<ASTConsumer>
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001054 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts()));
Ted Kremenek20e97482007-12-12 23:41:08 +00001055
1056 if (!Consumer) {
1057 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1058 exit (1);
1059 }
1060
Ted Kremenek95041a22007-12-19 22:51:13 +00001061 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001062
1063 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1064 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001065}
1066
1067
Reid Spencer5f016e22007-07-11 17:01:13 +00001068static llvm::cl::list<std::string>
1069InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1070
Ted Kremenek20e97482007-12-12 23:41:08 +00001071static bool isSerializedFile(const std::string& InFile) {
1072 if (InFile.size() < 4)
1073 return false;
1074
1075 const char* s = InFile.c_str()+InFile.size()-4;
1076
1077 return s[0] == '.' &&
1078 s[1] == 'a' &&
1079 s[2] == 's' &&
1080 s[3] == 't';
1081}
1082
Reid Spencer5f016e22007-07-11 17:01:13 +00001083
1084int main(int argc, char **argv) {
1085 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1086 llvm::sys::PrintStackTraceOnErrorSignal();
1087
1088 // If no input was specified, read from stdin.
1089 if (InputFilenames.empty())
1090 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001091
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 // Create a file manager object to provide access to and cache the filesystem.
1093 FileManager FileMgr;
1094
Ted Kremenek31e703b2007-12-11 23:28:38 +00001095 // Create the diagnostic client for reporting errors or for
1096 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001098 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001100 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 } else {
1102 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001103 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001104
1105 if (InputFilenames.size() != 1) {
1106 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001107 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 return 1;
1109 }
1110 }
1111
1112 // Configure our handling of diagnostics.
1113 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001114 InitializeDiagnostics(Diags);
1115
Chris Lattner4f037832007-12-05 23:24:17 +00001116 // -I- is a deprecated GCC feature, scan for it and reject it.
1117 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1118 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001119 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001120 I_dirs.erase(I_dirs.begin()+i);
1121 --i;
1122 }
1123 }
1124
Reid Spencer5f016e22007-07-11 17:01:13 +00001125 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001126 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001127
Ted Kremenek20e97482007-12-12 23:41:08 +00001128 if (isSerializedFile(InFile))
1129 ProcessSerializedFile(InFile,Diags,FileMgr);
1130 else {
1131 /// Create a SourceManager object. This tracks and owns all the file
1132 /// buffers allocated to a translation unit.
1133 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001134
Ted Kremenek20e97482007-12-12 23:41:08 +00001135 // Initialize language options, inferring file types from input filenames.
1136 LangOptions LangInfo;
1137 InitializeBaseLanguage();
1138 LangKind LK = GetLanguage(InFile);
1139 InitializeLangOptions(LangInfo, LK);
1140 InitializeLanguageStandard(LangInfo, LK);
1141
1142 // Process the -I options and set them in the HeaderInfo.
1143 HeaderSearch HeaderInfo(FileMgr);
1144 DiagClient->setHeaderSearch(HeaderInfo);
1145 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1146
1147 // Get information about the targets being compiled for. Note that this
1148 // pointer and the TargetInfoImpl objects are never deleted by this toy
1149 // driver.
1150 TargetInfo *Target;
1151
1152 // Create triples, and create the TargetInfo.
1153 std::vector<std::string> triples;
1154 CreateTargetTriples(triples);
1155 Target = TargetInfo::CreateTargetInfo(&triples[0],
1156 &triples[0]+triples.size(),
1157 &Diags);
1158
1159 if (Target == 0) {
1160 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1161 triples[0].c_str());
1162 fprintf(stderr, "Please use -triple or -arch.\n");
1163 exit(1);
1164 }
1165
1166 // Set up the preprocessor with these options.
1167 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1168
1169 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001170 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001171 continue;
1172
Ted Kremenek1036b682007-12-19 23:48:45 +00001173 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001174 HeaderInfo.ClearFileInfo();
1175
1176 if (Stats)
1177 SourceMgr.PrintStats();
1178 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001179 }
1180
1181 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1182
1183 if (NumDiagnostics)
1184 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1185 (NumDiagnostics == 1 ? "" : "s"));
1186
1187 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 FileMgr.PrintStats();
1189 fprintf(stderr, "\n");
1190 }
1191
Chris Lattner96f1a642007-07-21 05:40:53 +00001192 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001193}