blob: cdcbb34a51ca19b350de35ddb412d3ddf01bbcaf [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 Kremenek055c2752007-09-06 23:00:42 +000067 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000068 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000069 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000070 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000071 ParsePrintCallbacks, // Parse and print each callback.
72 ParseSyntaxOnly, // Parse and perform semantic analysis.
73 ParseNoop, // Parse with noop callbacks.
74 RunPreprocessorOnly, // Just lex, no output.
75 PrintPreprocessedInput, // -E mode.
76 DumpTokens // Token dump mode.
77};
78
79static llvm::cl::opt<ProgActions>
80ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
81 llvm::cl::init(ParseSyntaxOnly),
82 llvm::cl::values(
83 clEnumValN(RunPreprocessorOnly, "Eonly",
84 "Just run preprocessor, no output (for timings)"),
85 clEnumValN(PrintPreprocessedInput, "E",
86 "Run preprocessor, emit preprocessed file"),
87 clEnumValN(DumpTokens, "dumptokens",
88 "Run preprocessor, dump internal rep of tokens"),
89 clEnumValN(ParseNoop, "parse-noop",
90 "Run parser with noop callbacks (for timings)"),
91 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
92 "Run parser and perform semantic analysis"),
93 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
94 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +000095 clEnumValN(ASTPrint, "ast-print",
96 "Build ASTs and then pretty-print them"),
97 clEnumValN(ASTDump, "ast-dump",
98 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +000099 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000100 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000101 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000102 "Run parser, then build and print CFGs."),
103 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000104 "Run parser, then build and view CFGs with Graphviz."),
105 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000106 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000107 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000108 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000109 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000110 "Flag warnings of uses of unitialized variables."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000111 clEnumValN(TestSerialization, "test-pickling",
112 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000114 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000115 clEnumValN(EmitBC, "emit-llvm-bc",
116 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000117 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000118 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000119 clEnumValN(RewriteTest, "rewrite-test",
120 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 clEnumValEnd));
122
Ted Kremenekccc76472007-12-19 19:47:59 +0000123
124static llvm::cl::opt<std::string>
125OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000126 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000127 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
128
Ted Kremenek41193e42007-09-26 19:42:19 +0000129static llvm::cl::opt<bool>
130VerifyDiagnostics("verify",
131 llvm::cl::desc("Verify emitted diagnostics and warnings."));
132
Reid Spencer5f016e22007-07-11 17:01:13 +0000133//===----------------------------------------------------------------------===//
134// Language Options
135//===----------------------------------------------------------------------===//
136
137enum LangKind {
138 langkind_unspecified,
139 langkind_c,
140 langkind_c_cpp,
141 langkind_cxx,
142 langkind_cxx_cpp,
143 langkind_objc,
144 langkind_objc_cpp,
145 langkind_objcxx,
146 langkind_objcxx_cpp
147};
148
149/* TODO: GCC also accepts:
150 c-header c++-header objective-c-header objective-c++-header
151 assembler assembler-with-cpp
152 ada, f77*, ratfor (!), f95, java, treelang
153 */
154static llvm::cl::opt<LangKind>
155BaseLang("x", llvm::cl::desc("Base language to compile"),
156 llvm::cl::init(langkind_unspecified),
157 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
158 clEnumValN(langkind_cxx, "c++", "C++"),
159 clEnumValN(langkind_objc, "objective-c", "Objective C"),
160 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
161 clEnumValN(langkind_c_cpp, "c-cpp-output",
162 "Preprocessed C"),
163 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
164 "Preprocessed C++"),
165 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
166 "Preprocessed Objective C"),
167 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
168 "Preprocessed Objective C++"),
169 clEnumValEnd));
170
171static llvm::cl::opt<bool>
172LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
173 llvm::cl::Hidden);
174static llvm::cl::opt<bool>
175LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
176 llvm::cl::Hidden);
177
Ted Kremenek8904f152007-12-05 23:49:08 +0000178/// InitializeBaseLanguage - Handle the -x foo options.
179static void InitializeBaseLanguage() {
180 if (LangObjC)
181 BaseLang = langkind_objc;
182 else if (LangObjCXX)
183 BaseLang = langkind_objcxx;
184}
185
186static LangKind GetLanguage(const std::string &Filename) {
187 if (BaseLang != langkind_unspecified)
188 return BaseLang;
189
190 std::string::size_type DotPos = Filename.rfind('.');
191
192 if (DotPos == std::string::npos) {
193 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000194 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 }
196
Ted Kremenek8904f152007-12-05 23:49:08 +0000197 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
198 // C header: .h
199 // C++ header: .hh or .H;
200 // assembler no preprocessing: .s
201 // assembler: .S
202 if (Ext == "c")
203 return langkind_c;
204 else if (Ext == "i")
205 return langkind_c_cpp;
206 else if (Ext == "ii")
207 return langkind_cxx_cpp;
208 else if (Ext == "m")
209 return langkind_objc;
210 else if (Ext == "mi")
211 return langkind_objc_cpp;
212 else if (Ext == "mm" || Ext == "M")
213 return langkind_objcxx;
214 else if (Ext == "mii")
215 return langkind_objcxx_cpp;
216 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
217 Ext == "c++" || Ext == "cp" || Ext == "cxx")
218 return langkind_cxx;
219 else
220 return langkind_c;
221}
222
223
224static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000225 // FIXME: implement -fpreprocessed mode.
226 bool NoPreprocess = false;
227
Ted Kremenek8904f152007-12-05 23:49:08 +0000228 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000229 default: assert(0 && "Unknown language kind!");
230 case langkind_c_cpp:
231 NoPreprocess = true;
232 // FALLTHROUGH
233 case langkind_c:
234 break;
235 case langkind_cxx_cpp:
236 NoPreprocess = true;
237 // FALLTHROUGH
238 case langkind_cxx:
239 Options.CPlusPlus = 1;
240 break;
241 case langkind_objc_cpp:
242 NoPreprocess = true;
243 // FALLTHROUGH
244 case langkind_objc:
245 Options.ObjC1 = Options.ObjC2 = 1;
246 break;
247 case langkind_objcxx_cpp:
248 NoPreprocess = true;
249 // FALLTHROUGH
250 case langkind_objcxx:
251 Options.ObjC1 = Options.ObjC2 = 1;
252 Options.CPlusPlus = 1;
253 break;
254 }
255}
256
257/// LangStds - Language standards we support.
258enum LangStds {
259 lang_unspecified,
260 lang_c89, lang_c94, lang_c99,
261 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000262 lang_cxx98, lang_gnucxx98,
263 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000264};
265
266static llvm::cl::opt<LangStds>
267LangStd("std", llvm::cl::desc("Language standard to compile for"),
268 llvm::cl::init(lang_unspecified),
269 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
270 clEnumValN(lang_c89, "c90", "ISO C 1990"),
271 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
272 clEnumValN(lang_c94, "iso9899:199409",
273 "ISO C 1990 with amendment 1"),
274 clEnumValN(lang_c99, "c99", "ISO C 1999"),
275// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
276 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
277// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
278 clEnumValN(lang_gnu89, "gnu89",
279 "ISO C 1990 with GNU extensions (default for C)"),
280 clEnumValN(lang_gnu99, "gnu99",
281 "ISO C 1999 with GNU extensions"),
282 clEnumValN(lang_gnu99, "gnu9x",
283 "ISO C 1999 with GNU extensions"),
284 clEnumValN(lang_cxx98, "c++98",
285 "ISO C++ 1998 with amendments"),
286 clEnumValN(lang_gnucxx98, "gnu++98",
287 "ISO C++ 1998 with amendments and GNU "
288 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000289 clEnumValN(lang_cxx0x, "c++0x",
290 "Upcoming ISO C++ 200x with amendments"),
291 clEnumValN(lang_gnucxx0x, "gnu++0x",
292 "Upcoming ISO C++ 200x with amendments and GNU "
293 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 clEnumValEnd));
295
296static llvm::cl::opt<bool>
297NoOperatorNames("fno-operator-names",
298 llvm::cl::desc("Do not treat C++ operator name keywords as "
299 "synonyms for operators"));
300
Anders Carlssonee98ac52007-10-15 02:50:23 +0000301static llvm::cl::opt<bool>
302PascalStrings("fpascal-strings",
303 llvm::cl::desc("Recognize and construct Pascal-style "
304 "string literals"));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000305
306static llvm::cl::opt<bool>
307WritableStrings("fwritable-strings",
308 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000309
310static llvm::cl::opt<bool>
311LaxVectorConversions("flax-vector-conversions",
312 llvm::cl::desc("Allow implicit conversions between vectors"
313 " with a different number of elements or "
314 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000315// FIXME: add:
316// -ansi
317// -trigraphs
318// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000319// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000320static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000321 if (LangStd == lang_unspecified) {
322 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000323 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 default: assert(0 && "Unknown base language");
325 case langkind_c:
326 case langkind_c_cpp:
327 case langkind_objc:
328 case langkind_objc_cpp:
329 LangStd = lang_gnu99;
330 break;
331 case langkind_cxx:
332 case langkind_cxx_cpp:
333 case langkind_objcxx:
334 case langkind_objcxx_cpp:
335 LangStd = lang_gnucxx98;
336 break;
337 }
338 }
339
340 switch (LangStd) {
341 default: assert(0 && "Unknown language standard!");
342
343 // Fall through from newer standards to older ones. This isn't really right.
344 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000345 case lang_gnucxx0x:
346 case lang_cxx0x:
347 Options.CPlusPlus0x = 1;
348 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 case lang_gnucxx98:
350 case lang_cxx98:
351 Options.CPlusPlus = 1;
352 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000353 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 // FALL THROUGH.
355 case lang_gnu99:
356 case lang_c99:
357 Options.Digraphs = 1;
358 Options.C99 = 1;
359 Options.HexFloats = 1;
360 // FALL THROUGH.
361 case lang_gnu89:
362 Options.BCPLComment = 1; // Only for C99/C++.
363 // FALL THROUGH.
364 case lang_c94:
365 case lang_c89:
366 break;
367 }
368
369 Options.Trigraphs = 1; // -trigraphs or -ansi
370 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000371 Options.PascalStrings = PascalStrings;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000372 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000373 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000374}
375
376//===----------------------------------------------------------------------===//
377// Our DiagnosticClient implementation
378//===----------------------------------------------------------------------===//
379
380// FIXME: Werror should take a list of things, -Werror=foo,bar
381static llvm::cl::opt<bool>
382WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
383
384static llvm::cl::opt<bool>
385WarnOnExtensions("pedantic", llvm::cl::init(false),
386 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
387
388static llvm::cl::opt<bool>
389ErrorOnExtensions("pedantic-errors",
390 llvm::cl::desc("Issue an error on uses of GCC extensions"));
391
392static llvm::cl::opt<bool>
393WarnUnusedMacros("Wunused_macros",
394 llvm::cl::desc("Warn for unused macros in the main translation unit"));
395
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000396static llvm::cl::opt<bool>
397WarnFloatEqual("Wfloat-equal",
398 llvm::cl::desc("Warn about equality comparisons of floating point values."));
399
Ted Kremenek73da5902007-12-17 17:50:07 +0000400static llvm::cl::opt<bool>
401WarnNoFormatNonLiteral("Wno-format-nonliteral",
402 llvm::cl::desc("Do not warn about non-literal format strings."));
403
Reid Spencer5f016e22007-07-11 17:01:13 +0000404/// InitializeDiagnostics - Initialize the diagnostic object, based on the
405/// current command line option settings.
406static void InitializeDiagnostics(Diagnostic &Diags) {
407 Diags.setWarningsAsErrors(WarningsAsErrors);
408 Diags.setWarnOnExtensions(WarnOnExtensions);
409 Diags.setErrorOnExtensions(ErrorOnExtensions);
410
411 // Silence the "macro is not used" warning unless requested.
412 if (!WarnUnusedMacros)
413 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000414
415 // Silence "floating point comparison" warnings unless requested.
416 if (!WarnFloatEqual)
417 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000418
419 // Silence "format string is not a string literal" warnings if requested
420 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000421 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
422 diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000423
Reid Spencer5f016e22007-07-11 17:01:13 +0000424}
425
426//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000427// Target Triple Processing.
428//===----------------------------------------------------------------------===//
429
430static llvm::cl::opt<std::string>
431TargetTriple("triple",
432 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
433
434static llvm::cl::list<std::string>
435Archs("arch",
436 llvm::cl::desc("Specify target architecture (e.g. i686)."));
437
438namespace {
439 class TripleProcessor {
440 llvm::StringMap<char> TriplesProcessed;
441 std::vector<std::string>& triples;
442 public:
443 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
444
445 void addTriple(const std::string& t) {
446 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
447 TriplesProcessed.end()) {
448 triples.push_back(t);
449 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
450 }
451 }
452 };
453}
454
455static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000456 // Initialize base triple. If a -triple option has been specified, use
457 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000458 std::string Triple = TargetTriple;
459 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000460
461 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000462 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000463
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000464 if (firstDash == std::string::npos) {
465 fprintf(stderr,
466 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000467 Triple.c_str());
468 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000469 }
Ted Kremenekae360762007-12-03 22:06:55 +0000470
Chris Lattner6590d212007-12-12 05:01:48 +0000471 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000472
473 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000474 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
475 Triple.c_str());
476 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000477 }
Ted Kremenekae360762007-12-03 22:06:55 +0000478
479 // Create triple cacher.
480 TripleProcessor tp(triples);
481
482 // Add the primary triple to our set of triples if we are using the
483 // host-triple with no archs or using a specified target triple.
484 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000485 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000486
487 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
488 tp.addTriple(Archs[i] + "-" + suffix);
489}
490
491//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000492// Preprocessor Initialization
493//===----------------------------------------------------------------------===//
494
495// FIXME: Preprocessor builtins to support.
496// -A... - Play with #assertions
497// -undef - Undefine all predefined macros
498
499static llvm::cl::list<std::string>
500D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
501 llvm::cl::desc("Predefine the specified macro"));
502static llvm::cl::list<std::string>
503U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
504 llvm::cl::desc("Undefine the specified macro"));
505
506// Append a #define line to Buf for Macro. Macro should be of the form XXX,
507// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
508// "#define XXX Y z W". To get a #define with no value, use "XXX=".
509static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
510 const char *Command = "#define ") {
511 Buf.insert(Buf.end(), Command, Command+strlen(Command));
512 if (const char *Equal = strchr(Macro, '=')) {
513 // Turn the = into ' '.
514 Buf.insert(Buf.end(), Macro, Equal);
515 Buf.push_back(' ');
516 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
517 } else {
518 // Push "macroname 1".
519 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
520 Buf.push_back(' ');
521 Buf.push_back('1');
522 }
523 Buf.push_back('\n');
524}
525
Reid Spencer5f016e22007-07-11 17:01:13 +0000526
Chris Lattner53b0dab2007-10-09 22:10:18 +0000527/// InitializePreprocessor - Initialize the preprocessor getting it and the
528/// environment ready to process a single file. This returns the file ID for the
529/// input file. If a failure happens, it returns 0.
530///
531static unsigned InitializePreprocessor(Preprocessor &PP,
532 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000533 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000534
Chris Lattnerdee73592007-12-15 20:48:40 +0000535 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000536
Chris Lattner53b0dab2007-10-09 22:10:18 +0000537 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000538 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000539 if (InFile != "-") {
540 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000541 if (File) SourceMgr.createMainFileID(File, SourceLocation());
542 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000543 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
544 return 0;
545 }
546 } else {
547 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000548 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
549 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000550 fprintf(stderr, "Error reading standard input! Empty?\n");
551 return 0;
552 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 }
554
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 // Add macros from the command line.
556 // FIXME: Should traverse the #define/#undef lists in parallel.
557 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000558 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000560 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
561
562 // FIXME: Read any files specified by -imacros or -include.
563
564 // Null terminate PredefinedBuffer and add it.
565 PredefineBuffer.push_back(0);
566 PP.setPredefines(&PredefineBuffer[0]);
567
568 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000569 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000570}
571
572//===----------------------------------------------------------------------===//
573// Preprocessor include path information.
574//===----------------------------------------------------------------------===//
575
576// This tool exports a large number of command line options to control how the
577// preprocessor searches for header files. At root, however, the Preprocessor
578// object takes a very simple interface: a list of directories to search for
579//
580// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000581// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000582//
583// FIXME: -include,-imacros
584
585static llvm::cl::opt<bool>
586nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
587
588// Various command line options. These four add directories to each chain.
589static llvm::cl::list<std::string>
590F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
591 llvm::cl::desc("Add directory to framework include search path"));
592static llvm::cl::list<std::string>
593I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
594 llvm::cl::desc("Add directory to include search path"));
595static llvm::cl::list<std::string>
596idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
597 llvm::cl::desc("Add directory to AFTER include search path"));
598static llvm::cl::list<std::string>
599iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
600 llvm::cl::desc("Add directory to QUOTE include search path"));
601static llvm::cl::list<std::string>
602isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
603 llvm::cl::desc("Add directory to SYSTEM include search path"));
604
605// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
606static llvm::cl::list<std::string>
607iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
608 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
609static llvm::cl::list<std::string>
610iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
611 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
612static llvm::cl::list<std::string>
613iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
614 llvm::cl::Prefix,
615 llvm::cl::desc("Set directory to include search path with prefix"));
616
Chris Lattner0c946412007-08-26 17:47:35 +0000617static llvm::cl::opt<std::string>
618isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
619 llvm::cl::desc("Set the system root directory (usually /)"));
620
Reid Spencer5f016e22007-07-11 17:01:13 +0000621// Finally, implement the code that groks the options above.
622enum IncludeDirGroup {
623 Quoted = 0,
624 Angled,
625 System,
626 After
627};
628
629static std::vector<DirectoryLookup> IncludeGroup[4];
630
631/// AddPath - Add the specified path to the specified group list.
632///
633static void AddPath(const std::string &Path, IncludeDirGroup Group,
634 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000635 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000636 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000637 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000638
Chris Lattnerd6655272007-12-17 05:59:27 +0000639 // Compute the actual path, taking into consideration -isysroot.
640 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000641
Chris Lattnerd6655272007-12-17 05:59:27 +0000642 // Handle isysroot.
643 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000644 // FIXME: Portability. This should be a sys::Path interface, this doesn't
645 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000646 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
647 MappedPath.append(isysroot.begin(), isysroot.end());
648 if (Path[0] != '/') // If in the system group, add a /.
649 MappedPath.push_back('/');
Reid Spencer5f016e22007-07-11 17:01:13 +0000650 }
651
Chris Lattnerd6655272007-12-17 05:59:27 +0000652 MappedPath.append(Path.begin(), Path.end());
653
654 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000655 DirectoryLookup::DirType Type;
656 if (Group == Quoted || Group == Angled)
657 Type = DirectoryLookup::NormalHeaderDir;
658 else if (isCXXAware)
659 Type = DirectoryLookup::SystemHeaderDir;
660 else
661 Type = DirectoryLookup::ExternCSystemHeaderDir;
662
Chris Lattnerd6655272007-12-17 05:59:27 +0000663
664 // If the directory exists, add it.
665 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
666 &MappedPath[0]+
667 MappedPath.size())) {
668 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
669 isFramework));
670 return;
671 }
672
Chris Lattnerdf772332007-12-17 07:52:39 +0000673 // Check to see if this is an apple-style headermap (which are not allowed to
674 // be frameworks).
675 if (!isFramework) {
676 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
677 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000678 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
679 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000680 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
681 return;
682 }
Chris Lattner822da612007-12-17 06:36:45 +0000683 }
684 }
685
Chris Lattnerd6655272007-12-17 05:59:27 +0000686 if (Verbose)
687 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000688}
689
690/// RemoveDuplicates - If there are duplicate directory entries in the specified
691/// search list, remove the later (dead) ones.
692static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000693 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000694 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000695 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000697 if (SearchList[i].isNormalDir()) {
698 // If this isn't the first time we've seen this dir, remove it.
699 if (SeenDirs.insert(SearchList[i].getDir()))
700 continue;
701
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 if (Verbose)
703 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
704 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000705 } else if (SearchList[i].isFramework()) {
706 // If this isn't the first time we've seen this framework dir, remove it.
707 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
708 continue;
709
710 if (Verbose)
711 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
712 SearchList[i].getFrameworkDir()->getName());
713
Chris Lattnerb94c7072007-12-17 06:44:29 +0000714 } else {
715 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
716 // If this isn't the first time we've seen this headermap, remove it.
717 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
718 continue;
719
720 if (Verbose)
721 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
722 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000723 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000724
725 // This is reached if the current entry is a duplicate.
726 SearchList.erase(SearchList.begin()+i);
727 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 }
729}
730
731/// InitializeIncludePaths - Process the -I options and set them in the
732/// HeaderSearch object.
733static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000734 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 // Handle -F... options.
736 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000737 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000738
739 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000740 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000741 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000742
743 // Handle -idirafter... options.
744 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000745 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000746
747 // Handle -iquote... options.
748 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000749 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000750
751 // Handle -isystem... options.
752 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000753 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000754
755 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
756 // parallel, processing the values in order of occurance to get the right
757 // prefixes.
758 {
759 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
760 unsigned iprefix_idx = 0;
761 unsigned iwithprefix_idx = 0;
762 unsigned iwithprefixbefore_idx = 0;
763 bool iprefix_done = iprefix_vals.empty();
764 bool iwithprefix_done = iwithprefix_vals.empty();
765 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
766 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
767 if (!iprefix_done &&
768 (iwithprefix_done ||
769 iprefix_vals.getPosition(iprefix_idx) <
770 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
771 (iwithprefixbefore_done ||
772 iprefix_vals.getPosition(iprefix_idx) <
773 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
774 Prefix = iprefix_vals[iprefix_idx];
775 ++iprefix_idx;
776 iprefix_done = iprefix_idx == iprefix_vals.size();
777 } else if (!iwithprefix_done &&
778 (iwithprefixbefore_done ||
779 iwithprefix_vals.getPosition(iwithprefix_idx) <
780 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
781 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000782 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 ++iwithprefix_idx;
784 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
785 } else {
786 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000787 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 ++iwithprefixbefore_idx;
789 iwithprefixbefore_done =
790 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
791 }
792 }
793 }
794
795 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
796 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
797
798 // FIXME: temporary hack: hard-coded paths.
799 // FIXME: get these from the target?
800 if (!nostdinc) {
801 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000802 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000803 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000804 false, Headers);
805 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
806 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000807 }
808
Chris Lattner822da612007-12-17 06:36:45 +0000809 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 // leopard
811 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000812 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000814 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
816 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000817 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000818
819 // tiger
820 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000821 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000823 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000824 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
825 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000826 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000827
Chris Lattner822da612007-12-17 06:36:45 +0000828 AddPath("/usr/include", System, false, false, false, Headers);
829 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
830 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000831 }
832
833 // Now that we have collected all of the include paths, merge them all
834 // together and tell the preprocessor about them.
835
836 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
837 std::vector<DirectoryLookup> SearchList;
838 SearchList = IncludeGroup[Angled];
839 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
840 IncludeGroup[System].end());
841 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
842 IncludeGroup[After].end());
843 RemoveDuplicates(SearchList);
844 RemoveDuplicates(IncludeGroup[Quoted]);
845
846 // Prepend QUOTED list on the search list.
847 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
848 IncludeGroup[Quoted].end());
849
850
851 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
852 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
853 DontSearchCurDir);
854
855 // If verbose, print the list of directories that will be searched.
856 if (Verbose) {
857 fprintf(stderr, "#include \"...\" search starts here:\n");
858 unsigned QuotedIdx = IncludeGroup[Quoted].size();
859 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
860 if (i == QuotedIdx)
861 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000862 const char *Name = SearchList[i].getName();
863 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000864 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000865 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000866 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000867 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000868 else {
869 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000870 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000871 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000872 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 }
Chris Lattner80e17152007-12-15 23:11:06 +0000874 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 }
876}
877
878
Reid Spencer5f016e22007-07-11 17:01:13 +0000879//===----------------------------------------------------------------------===//
880// Basic Parser driver
881//===----------------------------------------------------------------------===//
882
Ted Kremenek95041a22007-12-19 22:51:13 +0000883static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000884 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000885 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000886
887 // Parsing the specified input file.
888 P.ParseTranslationUnit();
889 delete PA;
890}
891
892//===----------------------------------------------------------------------===//
893// Main driver
894//===----------------------------------------------------------------------===//
895
Ted Kremenekdb094a22007-12-05 18:27:04 +0000896/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
897/// action. These consumers can operate on both ASTs that are freshly
898/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000899static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000900 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremenekdb094a22007-12-05 18:27:04 +0000901 const LangOptions& LangOpts) {
902 switch (ProgAction) {
903 default:
904 return NULL;
905
906 case ASTPrint:
907 return CreateASTPrinter();
908
909 case ASTDump:
910 return CreateASTDumper();
911
912 case ASTView:
913 return CreateASTViewer();
914
915 case ParseCFGDump:
916 case ParseCFGView:
917 return CreateCFGDumper(ProgAction == ParseCFGView);
918
919 case AnalysisLiveVariables:
920 return CreateLiveVarAnalyzer();
921
922 case WarnDeadStores:
923 return CreateDeadStoreChecker(Diag);
924
925 case WarnUninitVals:
926 return CreateUnitValsChecker(Diag);
927
928 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000929 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000930
931 case EmitLLVM:
932 return CreateLLVMEmitter(Diag, LangOpts);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000933
934 case EmitBC:
935 return CreateBCWriter(InFile, OutputFile, Diag, LangOpts);
936
Ted Kremenek3910c7c2007-12-19 17:25:59 +0000937 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000938 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +0000939 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000940
Ted Kremenekdb094a22007-12-05 18:27:04 +0000941 case RewriteTest:
942 return CreateCodeRewriterTest(Diag);
943 }
944}
945
Reid Spencer5f016e22007-07-11 17:01:13 +0000946/// ProcessInputFile - Process a single input file with the specified state.
947///
Ted Kremenek7dcc9682007-12-19 22:32:34 +0000948static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +0000949 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000950
951 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000952 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000953
Reid Spencer5f016e22007-07-11 17:01:13 +0000954 switch (ProgAction) {
955 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000956 Consumer = CreateASTConsumer(InFile,
957 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +0000958 PP.getFileManager(),
Ted Kremenekdb094a22007-12-05 18:27:04 +0000959 PP.getLangOptions());
960
961 if (!Consumer) {
962 fprintf(stderr, "Unexpected program action!\n");
963 return;
964 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000965
Ted Kremenekdb094a22007-12-05 18:27:04 +0000966 break;
967
Reid Spencer5f016e22007-07-11 17:01:13 +0000968 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000969 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000971 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 do {
973 PP.Lex(Tok);
974 PP.DumpToken(Tok, true);
975 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000976 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000977 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 break;
979 }
980 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000981 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000982 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000983 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000984 do {
985 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000986 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000987 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 break;
989 }
990
991 case PrintPreprocessedInput: // -E mode.
Ted Kremenek95041a22007-12-19 22:51:13 +0000992 DoPrintPreprocessedInput(PP);
Chris Lattnerbd247762007-07-22 06:05:44 +0000993 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000994 break;
995
996 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +0000997 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +0000998 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000999 break;
1000
1001 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001002 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001003 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001004 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001005
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001006 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001007 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001008 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001009 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001010
1011 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001012 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001013 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001014
1015 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001016 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 }
1018
1019 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001020 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001021 PP.PrintStats();
1022 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001023 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001024 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001025 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001026 fprintf(stderr, "\n");
1027 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001028
1029 // For a multi-file compilation, some things are ok with nuking the source
1030 // manager tables, other require stable fileid/macroid's across multiple
1031 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001032 if (ClearSourceMgr)
1033 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001034}
1035
Ted Kremenek20e97482007-12-12 23:41:08 +00001036static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1037 FileManager& FileMgr) {
1038
1039 if (VerifyDiagnostics) {
1040 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1041 exit (1);
1042 }
1043
1044 llvm::sys::Path Filename(InFile);
1045
1046 if (!Filename.isValid()) {
1047 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1048 exit (1);
1049 }
1050
Ted Kremenekee533642007-12-20 19:47:16 +00001051 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001052
1053 if (!TU) {
1054 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1055 InFile.c_str());
1056 exit (1);
1057 }
1058
Ted Kremenek63ea8632007-12-19 19:27:38 +00001059 // Observe that we use the source file name stored in the deserialized
1060 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001061 llvm::OwningPtr<ASTConsumer>
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001062 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts()));
Ted Kremenek20e97482007-12-12 23:41:08 +00001063
1064 if (!Consumer) {
1065 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1066 exit (1);
1067 }
1068
Ted Kremenek95041a22007-12-19 22:51:13 +00001069 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001070
1071 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1072 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001073}
1074
1075
Reid Spencer5f016e22007-07-11 17:01:13 +00001076static llvm::cl::list<std::string>
1077InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1078
Ted Kremenek20e97482007-12-12 23:41:08 +00001079static bool isSerializedFile(const std::string& InFile) {
1080 if (InFile.size() < 4)
1081 return false;
1082
1083 const char* s = InFile.c_str()+InFile.size()-4;
1084
1085 return s[0] == '.' &&
1086 s[1] == 'a' &&
1087 s[2] == 's' &&
1088 s[3] == 't';
1089}
1090
Reid Spencer5f016e22007-07-11 17:01:13 +00001091
1092int main(int argc, char **argv) {
1093 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1094 llvm::sys::PrintStackTraceOnErrorSignal();
1095
1096 // If no input was specified, read from stdin.
1097 if (InputFilenames.empty())
1098 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001099
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 // Create a file manager object to provide access to and cache the filesystem.
1101 FileManager FileMgr;
1102
Ted Kremenek31e703b2007-12-11 23:28:38 +00001103 // Create the diagnostic client for reporting errors or for
1104 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001106 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001108 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 } else {
1110 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001111 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001112
1113 if (InputFilenames.size() != 1) {
1114 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001115 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001116 return 1;
1117 }
1118 }
1119
1120 // Configure our handling of diagnostics.
1121 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001122 InitializeDiagnostics(Diags);
1123
Chris Lattner4f037832007-12-05 23:24:17 +00001124 // -I- is a deprecated GCC feature, scan for it and reject it.
1125 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1126 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001127 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001128 I_dirs.erase(I_dirs.begin()+i);
1129 --i;
1130 }
1131 }
1132
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001134 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001135
Ted Kremenek20e97482007-12-12 23:41:08 +00001136 if (isSerializedFile(InFile))
1137 ProcessSerializedFile(InFile,Diags,FileMgr);
1138 else {
1139 /// Create a SourceManager object. This tracks and owns all the file
1140 /// buffers allocated to a translation unit.
1141 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001142
Ted Kremenek20e97482007-12-12 23:41:08 +00001143 // Initialize language options, inferring file types from input filenames.
1144 LangOptions LangInfo;
1145 InitializeBaseLanguage();
1146 LangKind LK = GetLanguage(InFile);
1147 InitializeLangOptions(LangInfo, LK);
1148 InitializeLanguageStandard(LangInfo, LK);
1149
1150 // Process the -I options and set them in the HeaderInfo.
1151 HeaderSearch HeaderInfo(FileMgr);
1152 DiagClient->setHeaderSearch(HeaderInfo);
1153 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1154
1155 // Get information about the targets being compiled for. Note that this
1156 // pointer and the TargetInfoImpl objects are never deleted by this toy
1157 // driver.
1158 TargetInfo *Target;
1159
1160 // Create triples, and create the TargetInfo.
1161 std::vector<std::string> triples;
1162 CreateTargetTriples(triples);
1163 Target = TargetInfo::CreateTargetInfo(&triples[0],
1164 &triples[0]+triples.size(),
1165 &Diags);
1166
1167 if (Target == 0) {
1168 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1169 triples[0].c_str());
1170 fprintf(stderr, "Please use -triple or -arch.\n");
1171 exit(1);
1172 }
1173
1174 // Set up the preprocessor with these options.
1175 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1176
1177 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001178 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001179 continue;
1180
Ted Kremenek1036b682007-12-19 23:48:45 +00001181 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001182 HeaderInfo.ClearFileInfo();
1183
1184 if (Stats)
1185 SourceMgr.PrintStats();
1186 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 }
1188
1189 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1190
1191 if (NumDiagnostics)
1192 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1193 (NumDiagnostics == 1 ? "" : "s"));
1194
1195 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 FileMgr.PrintStats();
1197 fprintf(stderr, "\n");
1198 }
1199
Chris Lattner96f1a642007-07-21 05:40:53 +00001200 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001201}