blob: 2f47e5199ca21f5cf0a426892331974c932ebbf9 [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 Lattner8ee3c032008-02-06 02:01:47 +000030#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000031#include "clang/Sema/ParseAST.h"
Chris Lattner556beb72007-09-15 22:56:56 +000032#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Parse/Parser.h"
34#include "clang/Lex/HeaderSearch.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000038#include "llvm/Module.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000040#include "llvm/Bitcode/ReaderWriter.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000044#include "llvm/Config/config.h"
Ted Kremenekee533642007-12-20 19:47:16 +000045#include "llvm/ADT/OwningPtr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000046#include <memory>
Chris Lattnere66b65c2008-02-06 01:42:25 +000047#include <fstream>
Reid Spencer5f016e22007-07-11 17:01:13 +000048using namespace clang;
49
50//===----------------------------------------------------------------------===//
51// Global options.
52//===----------------------------------------------------------------------===//
53
54static llvm::cl::opt<bool>
55Verbose("v", llvm::cl::desc("Enable verbose output"));
56static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000057Stats("print-stats",
58 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000059
60enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000061 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000062 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000063 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000064 SerializeAST, // Emit a .ast file.
Chris Lattner3b427b32007-10-11 00:18:28 +000065 ASTPrint, // Parse ASTs and print them.
66 ASTDump, // Parse ASTs and dump them.
67 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000068 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000069 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000070 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenekee985462008-01-16 18:18:48 +000071 AnalysisGRConstants, // Perform graph-reachability constant prop.
Ted Kremenek055c2752007-09-06 23:00:42 +000072 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000073 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000074 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000075 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000076 ParsePrintCallbacks, // Parse and print each callback.
77 ParseSyntaxOnly, // Parse and perform semantic analysis.
78 ParseNoop, // Parse with noop callbacks.
79 RunPreprocessorOnly, // Just lex, no output.
80 PrintPreprocessedInput, // -E mode.
81 DumpTokens // Token dump mode.
82};
83
84static llvm::cl::opt<ProgActions>
85ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
86 llvm::cl::init(ParseSyntaxOnly),
87 llvm::cl::values(
88 clEnumValN(RunPreprocessorOnly, "Eonly",
89 "Just run preprocessor, no output (for timings)"),
90 clEnumValN(PrintPreprocessedInput, "E",
91 "Run preprocessor, emit preprocessed file"),
92 clEnumValN(DumpTokens, "dumptokens",
93 "Run preprocessor, dump internal rep of tokens"),
94 clEnumValN(ParseNoop, "parse-noop",
95 "Run parser with noop callbacks (for timings)"),
96 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
97 "Run parser and perform semantic analysis"),
98 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
99 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000100 clEnumValN(ASTPrint, "ast-print",
101 "Build ASTs and then pretty-print them"),
102 clEnumValN(ASTDump, "ast-dump",
103 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000104 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000105 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000106 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000107 "Run parser, then build and print CFGs."),
108 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000109 "Run parser, then build and view CFGs with Graphviz."),
110 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000111 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000112 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000113 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000114 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000115 "Flag warnings of uses of unitialized variables."),
Ted Kremeneka4532552008-01-16 18:21:49 +0000116 clEnumValN(AnalysisGRConstants, "grconstants",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000117 "Perform path-sensitive constant propagation."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000118 clEnumValN(TestSerialization, "test-pickling",
119 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000121 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000122 clEnumValN(EmitBC, "emit-llvm-bc",
123 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000124 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000125 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000126 clEnumValN(RewriteTest, "rewrite-test",
127 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 clEnumValEnd));
129
Ted Kremenekccc76472007-12-19 19:47:59 +0000130
131static llvm::cl::opt<std::string>
132OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000133 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000134 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
135
Ted Kremenek41193e42007-09-26 19:42:19 +0000136static llvm::cl::opt<bool>
137VerifyDiagnostics("verify",
138 llvm::cl::desc("Verify emitted diagnostics and warnings."));
139
Reid Spencer5f016e22007-07-11 17:01:13 +0000140//===----------------------------------------------------------------------===//
141// Language Options
142//===----------------------------------------------------------------------===//
143
144enum LangKind {
145 langkind_unspecified,
146 langkind_c,
147 langkind_c_cpp,
148 langkind_cxx,
149 langkind_cxx_cpp,
150 langkind_objc,
151 langkind_objc_cpp,
152 langkind_objcxx,
153 langkind_objcxx_cpp
154};
155
156/* TODO: GCC also accepts:
157 c-header c++-header objective-c-header objective-c++-header
158 assembler assembler-with-cpp
159 ada, f77*, ratfor (!), f95, java, treelang
160 */
161static llvm::cl::opt<LangKind>
162BaseLang("x", llvm::cl::desc("Base language to compile"),
163 llvm::cl::init(langkind_unspecified),
164 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
165 clEnumValN(langkind_cxx, "c++", "C++"),
166 clEnumValN(langkind_objc, "objective-c", "Objective C"),
167 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
168 clEnumValN(langkind_c_cpp, "c-cpp-output",
169 "Preprocessed C"),
170 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
171 "Preprocessed C++"),
172 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
173 "Preprocessed Objective C"),
174 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
175 "Preprocessed Objective C++"),
176 clEnumValEnd));
177
178static llvm::cl::opt<bool>
179LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
180 llvm::cl::Hidden);
181static llvm::cl::opt<bool>
182LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
183 llvm::cl::Hidden);
184
Ted Kremenek8904f152007-12-05 23:49:08 +0000185/// InitializeBaseLanguage - Handle the -x foo options.
186static void InitializeBaseLanguage() {
187 if (LangObjC)
188 BaseLang = langkind_objc;
189 else if (LangObjCXX)
190 BaseLang = langkind_objcxx;
191}
192
193static LangKind GetLanguage(const std::string &Filename) {
194 if (BaseLang != langkind_unspecified)
195 return BaseLang;
196
197 std::string::size_type DotPos = Filename.rfind('.');
198
199 if (DotPos == std::string::npos) {
200 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000201 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000202 }
203
Ted Kremenek8904f152007-12-05 23:49:08 +0000204 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
205 // C header: .h
206 // C++ header: .hh or .H;
207 // assembler no preprocessing: .s
208 // assembler: .S
209 if (Ext == "c")
210 return langkind_c;
211 else if (Ext == "i")
212 return langkind_c_cpp;
213 else if (Ext == "ii")
214 return langkind_cxx_cpp;
215 else if (Ext == "m")
216 return langkind_objc;
217 else if (Ext == "mi")
218 return langkind_objc_cpp;
219 else if (Ext == "mm" || Ext == "M")
220 return langkind_objcxx;
221 else if (Ext == "mii")
222 return langkind_objcxx_cpp;
223 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
224 Ext == "c++" || Ext == "cp" || Ext == "cxx")
225 return langkind_cxx;
226 else
227 return langkind_c;
228}
229
230
231static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000232 // FIXME: implement -fpreprocessed mode.
233 bool NoPreprocess = false;
234
Ted Kremenek8904f152007-12-05 23:49:08 +0000235 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 default: assert(0 && "Unknown language kind!");
237 case langkind_c_cpp:
238 NoPreprocess = true;
239 // FALLTHROUGH
240 case langkind_c:
241 break;
242 case langkind_cxx_cpp:
243 NoPreprocess = true;
244 // FALLTHROUGH
245 case langkind_cxx:
246 Options.CPlusPlus = 1;
247 break;
248 case langkind_objc_cpp:
249 NoPreprocess = true;
250 // FALLTHROUGH
251 case langkind_objc:
252 Options.ObjC1 = Options.ObjC2 = 1;
253 break;
254 case langkind_objcxx_cpp:
255 NoPreprocess = true;
256 // FALLTHROUGH
257 case langkind_objcxx:
258 Options.ObjC1 = Options.ObjC2 = 1;
259 Options.CPlusPlus = 1;
260 break;
261 }
262}
263
264/// LangStds - Language standards we support.
265enum LangStds {
266 lang_unspecified,
267 lang_c89, lang_c94, lang_c99,
268 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000269 lang_cxx98, lang_gnucxx98,
270 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000271};
272
273static llvm::cl::opt<LangStds>
274LangStd("std", llvm::cl::desc("Language standard to compile for"),
275 llvm::cl::init(lang_unspecified),
276 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
277 clEnumValN(lang_c89, "c90", "ISO C 1990"),
278 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
279 clEnumValN(lang_c94, "iso9899:199409",
280 "ISO C 1990 with amendment 1"),
281 clEnumValN(lang_c99, "c99", "ISO C 1999"),
282// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
283 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
284// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
285 clEnumValN(lang_gnu89, "gnu89",
286 "ISO C 1990 with GNU extensions (default for C)"),
287 clEnumValN(lang_gnu99, "gnu99",
288 "ISO C 1999 with GNU extensions"),
289 clEnumValN(lang_gnu99, "gnu9x",
290 "ISO C 1999 with GNU extensions"),
291 clEnumValN(lang_cxx98, "c++98",
292 "ISO C++ 1998 with amendments"),
293 clEnumValN(lang_gnucxx98, "gnu++98",
294 "ISO C++ 1998 with amendments and GNU "
295 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000296 clEnumValN(lang_cxx0x, "c++0x",
297 "Upcoming ISO C++ 200x with amendments"),
298 clEnumValN(lang_gnucxx0x, "gnu++0x",
299 "Upcoming ISO C++ 200x with amendments and GNU "
300 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 clEnumValEnd));
302
303static llvm::cl::opt<bool>
304NoOperatorNames("fno-operator-names",
305 llvm::cl::desc("Do not treat C++ operator name keywords as "
306 "synonyms for operators"));
307
Anders Carlssonee98ac52007-10-15 02:50:23 +0000308static llvm::cl::opt<bool>
309PascalStrings("fpascal-strings",
310 llvm::cl::desc("Recognize and construct Pascal-style "
311 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000312
313static llvm::cl::opt<bool>
314MSExtensions("fms-extensions",
315 llvm::cl::desc("Accept some non-standard constructs used in "
316 "Microsoft header files. "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000317
318static llvm::cl::opt<bool>
319WritableStrings("fwritable-strings",
320 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000321
322static llvm::cl::opt<bool>
323LaxVectorConversions("flax-vector-conversions",
324 llvm::cl::desc("Allow implicit conversions between vectors"
325 " with a different number of elements or "
326 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000327// FIXME: add:
328// -ansi
329// -trigraphs
330// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000331// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000332static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 if (LangStd == lang_unspecified) {
334 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000335 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 default: assert(0 && "Unknown base language");
337 case langkind_c:
338 case langkind_c_cpp:
339 case langkind_objc:
340 case langkind_objc_cpp:
341 LangStd = lang_gnu99;
342 break;
343 case langkind_cxx:
344 case langkind_cxx_cpp:
345 case langkind_objcxx:
346 case langkind_objcxx_cpp:
347 LangStd = lang_gnucxx98;
348 break;
349 }
350 }
351
352 switch (LangStd) {
353 default: assert(0 && "Unknown language standard!");
354
355 // Fall through from newer standards to older ones. This isn't really right.
356 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000357 case lang_gnucxx0x:
358 case lang_cxx0x:
359 Options.CPlusPlus0x = 1;
360 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 case lang_gnucxx98:
362 case lang_cxx98:
363 Options.CPlusPlus = 1;
364 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000365 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 // FALL THROUGH.
367 case lang_gnu99:
368 case lang_c99:
369 Options.Digraphs = 1;
370 Options.C99 = 1;
371 Options.HexFloats = 1;
372 // FALL THROUGH.
373 case lang_gnu89:
374 Options.BCPLComment = 1; // Only for C99/C++.
375 // FALL THROUGH.
376 case lang_c94:
377 case lang_c89:
378 break;
379 }
380
381 Options.Trigraphs = 1; // -trigraphs or -ansi
382 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000383 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000384 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000385 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000386 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000387}
388
389//===----------------------------------------------------------------------===//
390// Our DiagnosticClient implementation
391//===----------------------------------------------------------------------===//
392
393// FIXME: Werror should take a list of things, -Werror=foo,bar
394static llvm::cl::opt<bool>
395WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
396
397static llvm::cl::opt<bool>
398WarnOnExtensions("pedantic", llvm::cl::init(false),
399 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
400
401static llvm::cl::opt<bool>
402ErrorOnExtensions("pedantic-errors",
403 llvm::cl::desc("Issue an error on uses of GCC extensions"));
404
405static llvm::cl::opt<bool>
406WarnUnusedMacros("Wunused_macros",
407 llvm::cl::desc("Warn for unused macros in the main translation unit"));
408
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000409static llvm::cl::opt<bool>
410WarnFloatEqual("Wfloat-equal",
411 llvm::cl::desc("Warn about equality comparisons of floating point values."));
412
Ted Kremenek73da5902007-12-17 17:50:07 +0000413static llvm::cl::opt<bool>
414WarnNoFormatNonLiteral("Wno-format-nonliteral",
415 llvm::cl::desc("Do not warn about non-literal format strings."));
416
Chris Lattner116a4b12008-01-23 17:19:46 +0000417static llvm::cl::opt<bool>
418WarnUndefMacros("Wundef",
419 llvm::cl::desc("Warn on use of undefined macros in #if's"));
420
421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422/// InitializeDiagnostics - Initialize the diagnostic object, based on the
423/// current command line option settings.
424static void InitializeDiagnostics(Diagnostic &Diags) {
425 Diags.setWarningsAsErrors(WarningsAsErrors);
426 Diags.setWarnOnExtensions(WarnOnExtensions);
427 Diags.setErrorOnExtensions(ErrorOnExtensions);
428
429 // Silence the "macro is not used" warning unless requested.
430 if (!WarnUnusedMacros)
431 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000432
433 // Silence "floating point comparison" warnings unless requested.
434 if (!WarnFloatEqual)
435 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000436
437 // Silence "format string is not a string literal" warnings if requested
438 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000439 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
440 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000441 if (!WarnUndefMacros)
442 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000443
444 if (MSExtensions) // MS allows unnamed struct/union fields.
445 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000446}
447
448//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000449// Target Triple Processing.
450//===----------------------------------------------------------------------===//
451
452static llvm::cl::opt<std::string>
453TargetTriple("triple",
454 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
455
456static llvm::cl::list<std::string>
457Archs("arch",
458 llvm::cl::desc("Specify target architecture (e.g. i686)."));
459
460namespace {
461 class TripleProcessor {
462 llvm::StringMap<char> TriplesProcessed;
463 std::vector<std::string>& triples;
464 public:
465 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
466
467 void addTriple(const std::string& t) {
468 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
469 TriplesProcessed.end()) {
470 triples.push_back(t);
471 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
472 }
473 }
474 };
475}
476
477static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000478 // Initialize base triple. If a -triple option has been specified, use
479 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000480 std::string Triple = TargetTriple;
481 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000482
483 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000484 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000485
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000486 if (firstDash == std::string::npos) {
487 fprintf(stderr,
488 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000489 Triple.c_str());
490 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000491 }
Ted Kremenekae360762007-12-03 22:06:55 +0000492
Chris Lattner6590d212007-12-12 05:01:48 +0000493 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000494
495 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000496 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
497 Triple.c_str());
498 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000499 }
Ted Kremenekae360762007-12-03 22:06:55 +0000500
501 // Create triple cacher.
502 TripleProcessor tp(triples);
503
504 // Add the primary triple to our set of triples if we are using the
505 // host-triple with no archs or using a specified target triple.
506 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000507 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000508
509 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
510 tp.addTriple(Archs[i] + "-" + suffix);
511}
512
513//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000514// Preprocessor Initialization
515//===----------------------------------------------------------------------===//
516
517// FIXME: Preprocessor builtins to support.
518// -A... - Play with #assertions
519// -undef - Undefine all predefined macros
520
521static llvm::cl::list<std::string>
522D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
523 llvm::cl::desc("Predefine the specified macro"));
524static llvm::cl::list<std::string>
525U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
526 llvm::cl::desc("Undefine the specified macro"));
527
Chris Lattner64299f82008-01-10 01:53:41 +0000528static llvm::cl::list<std::string>
529ImplicitIncludes("include", llvm::cl::value_desc("file"),
530 llvm::cl::desc("Include file before parsing"));
531
532
Reid Spencer5f016e22007-07-11 17:01:13 +0000533// Append a #define line to Buf for Macro. Macro should be of the form XXX,
534// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
535// "#define XXX Y z W". To get a #define with no value, use "XXX=".
536static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
537 const char *Command = "#define ") {
538 Buf.insert(Buf.end(), Command, Command+strlen(Command));
539 if (const char *Equal = strchr(Macro, '=')) {
540 // Turn the = into ' '.
541 Buf.insert(Buf.end(), Macro, Equal);
542 Buf.push_back(' ');
543 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
544 } else {
545 // Push "macroname 1".
546 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
547 Buf.push_back(' ');
548 Buf.push_back('1');
549 }
550 Buf.push_back('\n');
551}
552
Chris Lattner64299f82008-01-10 01:53:41 +0000553/// AddImplicitInclude - Add an implicit #include of the specified file to the
554/// predefines buffer.
555static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
556 const char *Inc = "#include \"";
557 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
558 Buf.insert(Buf.end(), File.begin(), File.end());
559 Buf.push_back('"');
560 Buf.push_back('\n');
561}
562
Reid Spencer5f016e22007-07-11 17:01:13 +0000563
Chris Lattner53b0dab2007-10-09 22:10:18 +0000564/// InitializePreprocessor - Initialize the preprocessor getting it and the
565/// environment ready to process a single file. This returns the file ID for the
566/// input file. If a failure happens, it returns 0.
567///
568static unsigned InitializePreprocessor(Preprocessor &PP,
569 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000570 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000571
Chris Lattnerdee73592007-12-15 20:48:40 +0000572 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000573
Chris Lattner53b0dab2007-10-09 22:10:18 +0000574 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000575 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000576 if (InFile != "-") {
577 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000578 if (File) SourceMgr.createMainFileID(File, SourceLocation());
579 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000580 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
581 return 0;
582 }
583 } else {
584 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000585 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
586 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000587 fprintf(stderr, "Error reading standard input! Empty?\n");
588 return 0;
589 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000590 }
591
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 // Add macros from the command line.
593 // FIXME: Should traverse the #define/#undef lists in parallel.
594 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000595 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000596 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000597 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
598
Chris Lattner64299f82008-01-10 01:53:41 +0000599 // FIXME: Read any files specified by -imacros.
600
601 // Add implicit #includes from -include.
602 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
603 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000604
605 // Null terminate PredefinedBuffer and add it.
606 PredefineBuffer.push_back(0);
607 PP.setPredefines(&PredefineBuffer[0]);
608
609 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000610 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000611}
612
613//===----------------------------------------------------------------------===//
614// Preprocessor include path information.
615//===----------------------------------------------------------------------===//
616
617// This tool exports a large number of command line options to control how the
618// preprocessor searches for header files. At root, however, the Preprocessor
619// object takes a very simple interface: a list of directories to search for
620//
621// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000622// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000623//
Chris Lattner64299f82008-01-10 01:53:41 +0000624// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000625
626static llvm::cl::opt<bool>
627nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
628
629// Various command line options. These four add directories to each chain.
630static llvm::cl::list<std::string>
631F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
632 llvm::cl::desc("Add directory to framework include search path"));
633static llvm::cl::list<std::string>
634I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
635 llvm::cl::desc("Add directory to include search path"));
636static llvm::cl::list<std::string>
637idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
638 llvm::cl::desc("Add directory to AFTER include search path"));
639static llvm::cl::list<std::string>
640iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
641 llvm::cl::desc("Add directory to QUOTE include search path"));
642static llvm::cl::list<std::string>
643isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
644 llvm::cl::desc("Add directory to SYSTEM include search path"));
645
646// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
647static llvm::cl::list<std::string>
648iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
649 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
650static llvm::cl::list<std::string>
651iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
652 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
653static llvm::cl::list<std::string>
654iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
655 llvm::cl::Prefix,
656 llvm::cl::desc("Set directory to include search path with prefix"));
657
Chris Lattner0c946412007-08-26 17:47:35 +0000658static llvm::cl::opt<std::string>
659isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
660 llvm::cl::desc("Set the system root directory (usually /)"));
661
Reid Spencer5f016e22007-07-11 17:01:13 +0000662// Finally, implement the code that groks the options above.
663enum IncludeDirGroup {
664 Quoted = 0,
665 Angled,
666 System,
667 After
668};
669
670static std::vector<DirectoryLookup> IncludeGroup[4];
671
672/// AddPath - Add the specified path to the specified group list.
673///
674static void AddPath(const std::string &Path, IncludeDirGroup Group,
675 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000676 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000677 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000678 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000679
Chris Lattnerd6655272007-12-17 05:59:27 +0000680 // Compute the actual path, taking into consideration -isysroot.
681 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000682
Chris Lattnerd6655272007-12-17 05:59:27 +0000683 // Handle isysroot.
684 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000685 // FIXME: Portability. This should be a sys::Path interface, this doesn't
686 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000687 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
688 MappedPath.append(isysroot.begin(), isysroot.end());
689 if (Path[0] != '/') // If in the system group, add a /.
690 MappedPath.push_back('/');
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 }
692
Chris Lattnerd6655272007-12-17 05:59:27 +0000693 MappedPath.append(Path.begin(), Path.end());
694
695 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 DirectoryLookup::DirType Type;
697 if (Group == Quoted || Group == Angled)
698 Type = DirectoryLookup::NormalHeaderDir;
699 else if (isCXXAware)
700 Type = DirectoryLookup::SystemHeaderDir;
701 else
702 Type = DirectoryLookup::ExternCSystemHeaderDir;
703
Chris Lattnerd6655272007-12-17 05:59:27 +0000704
705 // If the directory exists, add it.
706 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
707 &MappedPath[0]+
708 MappedPath.size())) {
709 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
710 isFramework));
711 return;
712 }
713
Chris Lattnerdf772332007-12-17 07:52:39 +0000714 // Check to see if this is an apple-style headermap (which are not allowed to
715 // be frameworks).
716 if (!isFramework) {
717 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
718 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000719 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
720 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000721 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
722 return;
723 }
Chris Lattner822da612007-12-17 06:36:45 +0000724 }
725 }
726
Chris Lattnerd6655272007-12-17 05:59:27 +0000727 if (Verbose)
728 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000729}
730
731/// RemoveDuplicates - If there are duplicate directory entries in the specified
732/// search list, remove the later (dead) ones.
733static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000734 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000735 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000736 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000738 if (SearchList[i].isNormalDir()) {
739 // If this isn't the first time we've seen this dir, remove it.
740 if (SeenDirs.insert(SearchList[i].getDir()))
741 continue;
742
Reid Spencer5f016e22007-07-11 17:01:13 +0000743 if (Verbose)
744 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
745 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000746 } else if (SearchList[i].isFramework()) {
747 // If this isn't the first time we've seen this framework dir, remove it.
748 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
749 continue;
750
751 if (Verbose)
752 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
753 SearchList[i].getFrameworkDir()->getName());
754
Chris Lattnerb94c7072007-12-17 06:44:29 +0000755 } else {
756 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
757 // If this isn't the first time we've seen this headermap, remove it.
758 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
759 continue;
760
761 if (Verbose)
762 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
763 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000765
766 // This is reached if the current entry is a duplicate.
767 SearchList.erase(SearchList.begin()+i);
768 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 }
770}
771
772/// InitializeIncludePaths - Process the -I options and set them in the
773/// HeaderSearch object.
774static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000775 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000776 // Handle -F... options.
777 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000778 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000779
780 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000781 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000782 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000783
784 // Handle -idirafter... options.
785 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000786 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000787
788 // Handle -iquote... options.
789 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000790 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000791
792 // Handle -isystem... options.
793 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000794 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000795
796 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
797 // parallel, processing the values in order of occurance to get the right
798 // prefixes.
799 {
800 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
801 unsigned iprefix_idx = 0;
802 unsigned iwithprefix_idx = 0;
803 unsigned iwithprefixbefore_idx = 0;
804 bool iprefix_done = iprefix_vals.empty();
805 bool iwithprefix_done = iwithprefix_vals.empty();
806 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
807 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
808 if (!iprefix_done &&
809 (iwithprefix_done ||
810 iprefix_vals.getPosition(iprefix_idx) <
811 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
812 (iwithprefixbefore_done ||
813 iprefix_vals.getPosition(iprefix_idx) <
814 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
815 Prefix = iprefix_vals[iprefix_idx];
816 ++iprefix_idx;
817 iprefix_done = iprefix_idx == iprefix_vals.size();
818 } else if (!iwithprefix_done &&
819 (iwithprefixbefore_done ||
820 iwithprefix_vals.getPosition(iwithprefix_idx) <
821 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
822 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000823 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000824 ++iwithprefix_idx;
825 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
826 } else {
827 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000828 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 ++iwithprefixbefore_idx;
830 iwithprefixbefore_done =
831 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
832 }
833 }
834 }
835
836 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
837 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
838
839 // FIXME: temporary hack: hard-coded paths.
840 // FIXME: get these from the target?
841 if (!nostdinc) {
842 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000843 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000844 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000845 false, Headers);
846 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
847 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000848 }
849
Chris Lattner822da612007-12-17 06:36:45 +0000850 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000851 // leopard
852 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000853 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000855 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000856 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
857 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000858 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000859
860 // tiger
861 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000862 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000864 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
866 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000867 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000868
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000869 // Ubuntu 7.10 - Gutsy Gibbon
870 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
871 false, false, false, Headers);
872
Chris Lattner822da612007-12-17 06:36:45 +0000873 AddPath("/usr/include", System, false, false, false, Headers);
874 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
875 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 }
877
878 // Now that we have collected all of the include paths, merge them all
879 // together and tell the preprocessor about them.
880
881 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
882 std::vector<DirectoryLookup> SearchList;
883 SearchList = IncludeGroup[Angled];
884 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
885 IncludeGroup[System].end());
886 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
887 IncludeGroup[After].end());
888 RemoveDuplicates(SearchList);
889 RemoveDuplicates(IncludeGroup[Quoted]);
890
891 // Prepend QUOTED list on the search list.
892 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
893 IncludeGroup[Quoted].end());
894
895
896 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
897 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
898 DontSearchCurDir);
899
900 // If verbose, print the list of directories that will be searched.
901 if (Verbose) {
902 fprintf(stderr, "#include \"...\" search starts here:\n");
903 unsigned QuotedIdx = IncludeGroup[Quoted].size();
904 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
905 if (i == QuotedIdx)
906 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000907 const char *Name = SearchList[i].getName();
908 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000909 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000910 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000911 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000912 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000913 else {
914 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000915 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000916 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000917 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000918 }
Chris Lattner80e17152007-12-15 23:11:06 +0000919 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000920 }
921}
922
923
Reid Spencer5f016e22007-07-11 17:01:13 +0000924//===----------------------------------------------------------------------===//
925// Basic Parser driver
926//===----------------------------------------------------------------------===//
927
Ted Kremenek95041a22007-12-19 22:51:13 +0000928static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000930 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000931
932 // Parsing the specified input file.
933 P.ParseTranslationUnit();
934 delete PA;
935}
936
937//===----------------------------------------------------------------------===//
938// Main driver
939//===----------------------------------------------------------------------===//
940
Ted Kremenekdb094a22007-12-05 18:27:04 +0000941/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
942/// action. These consumers can operate on both ASTs that are freshly
943/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000944static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000945 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +0000946 const LangOptions& LangOpts,
947 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +0000948 switch (ProgAction) {
949 default:
950 return NULL;
951
952 case ASTPrint:
953 return CreateASTPrinter();
954
955 case ASTDump:
956 return CreateASTDumper();
957
958 case ASTView:
959 return CreateASTViewer();
960
961 case ParseCFGDump:
962 case ParseCFGView:
963 return CreateCFGDumper(ProgAction == ParseCFGView);
964
965 case AnalysisLiveVariables:
966 return CreateLiveVarAnalyzer();
967
968 case WarnDeadStores:
969 return CreateDeadStoreChecker(Diag);
970
971 case WarnUninitVals:
972 return CreateUnitValsChecker(Diag);
973
Ted Kremenekee985462008-01-16 18:18:48 +0000974 case AnalysisGRConstants:
Ted Kremenek19227e32008-02-07 06:33:19 +0000975 return CreateGRConstants(Diag);
Ted Kremeneke603df42008-01-08 18:04:06 +0000976
Ted Kremenekdb094a22007-12-05 18:27:04 +0000977 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000978 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000979
980 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000981 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +0000982 DestModule = new llvm::Module(InFile);
983 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000984
Ted Kremenek3910c7c2007-12-19 17:25:59 +0000985 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000986 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +0000987 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000988
Ted Kremenekdb094a22007-12-05 18:27:04 +0000989 case RewriteTest:
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000990 return CreateCodeRewriterTest(InFile, Diag);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000991 }
992}
993
Reid Spencer5f016e22007-07-11 17:01:13 +0000994/// ProcessInputFile - Process a single input file with the specified state.
995///
Ted Kremenek7dcc9682007-12-19 22:32:34 +0000996static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +0000997 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000998
999 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001000 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001001 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001002
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 switch (ProgAction) {
1004 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001005 Consumer = CreateASTConsumer(InFile,
1006 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001007 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001008 PP.getLangOptions(),
1009 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001010
1011 if (!Consumer) {
1012 fprintf(stderr, "Unexpected program action!\n");
1013 return;
1014 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001015
Ted Kremenekdb094a22007-12-05 18:27:04 +00001016 break;
1017
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001019 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001021 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 do {
1023 PP.Lex(Tok);
1024 PP.DumpToken(Tok, true);
1025 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001026 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001027 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001028 break;
1029 }
1030 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001031 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001032 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001033 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 do {
1035 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001036 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001037 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 break;
1039 }
1040
1041 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001042 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001043 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001044 break;
1045
1046 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001047 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001048 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001049 break;
1050
1051 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001052 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001053 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001054 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001055
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001056 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001057 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001058 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001059 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001060
1061 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001062 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001063 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001064
1065 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001066 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001067 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001068
1069 // If running the code generator, finish up now.
1070 if (CodeGenModule) {
1071 std::ostream *Out;
1072 if (OutputFile == "-") {
1073 Out = llvm::cout.stream();
1074 } else if (!OutputFile.empty()) {
1075 Out = new std::ofstream(OutputFile.c_str(),
1076 std::ios_base::binary|std::ios_base::out);
1077 } else if (InFile == "-") {
1078 Out = llvm::cout.stream();
1079 } else {
1080 llvm::sys::Path Path(InFile);
1081 Path.eraseSuffix();
1082 if (ProgAction == EmitLLVM)
1083 Path.appendSuffix("ll");
1084 else if (ProgAction == EmitBC)
1085 Path.appendSuffix("bc");
1086 else
1087 assert(0 && "Unknown action");
1088 Out = new std::ofstream(Path.toString().c_str(),
1089 std::ios_base::binary|std::ios_base::out);
1090 }
1091
1092 if (ProgAction == EmitLLVM) {
1093 CodeGenModule->print(*Out);
1094 } else {
1095 assert(ProgAction == EmitBC);
1096 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1097 }
1098
1099 if (Out != llvm::cout.stream())
1100 delete Out;
1101 delete CodeGenModule;
1102 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001103
1104 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001105 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 PP.PrintStats();
1107 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001108 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001109 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001110 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 fprintf(stderr, "\n");
1112 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001113
1114 // For a multi-file compilation, some things are ok with nuking the source
1115 // manager tables, other require stable fileid/macroid's across multiple
1116 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001117 if (ClearSourceMgr)
1118 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001119}
1120
Ted Kremenek20e97482007-12-12 23:41:08 +00001121static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1122 FileManager& FileMgr) {
1123
1124 if (VerifyDiagnostics) {
1125 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1126 exit (1);
1127 }
1128
1129 llvm::sys::Path Filename(InFile);
1130
1131 if (!Filename.isValid()) {
1132 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1133 exit (1);
1134 }
1135
Ted Kremenekee533642007-12-20 19:47:16 +00001136 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001137
1138 if (!TU) {
1139 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1140 InFile.c_str());
1141 exit (1);
1142 }
1143
Ted Kremenek63ea8632007-12-19 19:27:38 +00001144 // Observe that we use the source file name stored in the deserialized
1145 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001146 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001147 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001148 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1149 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001150
1151 if (!Consumer) {
1152 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1153 exit (1);
1154 }
1155
Ted Kremenek95041a22007-12-19 22:51:13 +00001156 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001157
Chris Lattnere66b65c2008-02-06 01:42:25 +00001158 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001159 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1160 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001161}
1162
1163
Reid Spencer5f016e22007-07-11 17:01:13 +00001164static llvm::cl::list<std::string>
1165InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1166
Ted Kremenek20e97482007-12-12 23:41:08 +00001167static bool isSerializedFile(const std::string& InFile) {
1168 if (InFile.size() < 4)
1169 return false;
1170
1171 const char* s = InFile.c_str()+InFile.size()-4;
1172
1173 return s[0] == '.' &&
1174 s[1] == 'a' &&
1175 s[2] == 's' &&
1176 s[3] == 't';
1177}
1178
Reid Spencer5f016e22007-07-11 17:01:13 +00001179
1180int main(int argc, char **argv) {
1181 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1182 llvm::sys::PrintStackTraceOnErrorSignal();
1183
1184 // If no input was specified, read from stdin.
1185 if (InputFilenames.empty())
1186 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001187
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 // Create a file manager object to provide access to and cache the filesystem.
1189 FileManager FileMgr;
1190
Ted Kremenek31e703b2007-12-11 23:28:38 +00001191 // Create the diagnostic client for reporting errors or for
1192 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001194 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001196 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001197 } else {
1198 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001199 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001200
1201 if (InputFilenames.size() != 1) {
1202 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001203 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 return 1;
1205 }
1206 }
1207
1208 // Configure our handling of diagnostics.
1209 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001210 InitializeDiagnostics(Diags);
1211
Chris Lattner4f037832007-12-05 23:24:17 +00001212 // -I- is a deprecated GCC feature, scan for it and reject it.
1213 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1214 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001215 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001216 I_dirs.erase(I_dirs.begin()+i);
1217 --i;
1218 }
1219 }
1220
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001222 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001223
Ted Kremenek20e97482007-12-12 23:41:08 +00001224 if (isSerializedFile(InFile))
1225 ProcessSerializedFile(InFile,Diags,FileMgr);
1226 else {
1227 /// Create a SourceManager object. This tracks and owns all the file
1228 /// buffers allocated to a translation unit.
1229 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001230
Ted Kremenek20e97482007-12-12 23:41:08 +00001231 // Initialize language options, inferring file types from input filenames.
1232 LangOptions LangInfo;
1233 InitializeBaseLanguage();
1234 LangKind LK = GetLanguage(InFile);
1235 InitializeLangOptions(LangInfo, LK);
1236 InitializeLanguageStandard(LangInfo, LK);
1237
1238 // Process the -I options and set them in the HeaderInfo.
1239 HeaderSearch HeaderInfo(FileMgr);
1240 DiagClient->setHeaderSearch(HeaderInfo);
1241 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1242
1243 // Get information about the targets being compiled for. Note that this
1244 // pointer and the TargetInfoImpl objects are never deleted by this toy
1245 // driver.
1246 TargetInfo *Target;
1247
1248 // Create triples, and create the TargetInfo.
1249 std::vector<std::string> triples;
1250 CreateTargetTriples(triples);
1251 Target = TargetInfo::CreateTargetInfo(&triples[0],
1252 &triples[0]+triples.size(),
1253 &Diags);
1254
1255 if (Target == 0) {
1256 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1257 triples[0].c_str());
1258 fprintf(stderr, "Please use -triple or -arch.\n");
1259 exit(1);
1260 }
1261
1262 // Set up the preprocessor with these options.
1263 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1264
1265 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001266 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001267 continue;
1268
Ted Kremenek1036b682007-12-19 23:48:45 +00001269 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001270 HeaderInfo.ClearFileInfo();
1271
1272 if (Stats)
1273 SourceMgr.PrintStats();
1274 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 }
1276
1277 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1278
1279 if (NumDiagnostics)
1280 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1281 (NumDiagnostics == 1 ? "" : "s"));
1282
1283 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 FileMgr.PrintStats();
1285 fprintf(stderr, "\n");
1286 }
1287
Chris Lattner96f1a642007-07-21 05:40:53 +00001288 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001289}