blob: fa0c9fc43fc28002fcd2609505f2038bffe05fcf [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 Kremenekd55fe522008-02-15 00:35:38 +000071 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
72 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek055c2752007-09-06 23:00:42 +000073 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000074 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000075 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000076 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000077 ParsePrintCallbacks, // Parse and print each callback.
78 ParseSyntaxOnly, // Parse and perform semantic analysis.
79 ParseNoop, // Parse with noop callbacks.
80 RunPreprocessorOnly, // Just lex, no output.
81 PrintPreprocessedInput, // -E mode.
82 DumpTokens // Token dump mode.
83};
84
85static llvm::cl::opt<ProgActions>
86ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
87 llvm::cl::init(ParseSyntaxOnly),
88 llvm::cl::values(
89 clEnumValN(RunPreprocessorOnly, "Eonly",
90 "Just run preprocessor, no output (for timings)"),
91 clEnumValN(PrintPreprocessedInput, "E",
92 "Run preprocessor, emit preprocessed file"),
93 clEnumValN(DumpTokens, "dumptokens",
94 "Run preprocessor, dump internal rep of tokens"),
95 clEnumValN(ParseNoop, "parse-noop",
96 "Run parser with noop callbacks (for timings)"),
97 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
98 "Run parser and perform semantic analysis"),
99 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
100 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000101 clEnumValN(ASTPrint, "ast-print",
102 "Build ASTs and then pretty-print them"),
103 clEnumValN(ASTDump, "ast-dump",
104 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000105 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000106 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000107 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000108 "Run parser, then build and print CFGs."),
109 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000110 "Run parser, then build and view CFGs with Graphviz."),
111 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000112 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000113 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000114 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000115 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000116 "Flag warnings of uses of unitialized variables."),
Ted Kremeneke01c9872008-02-14 22:36:46 +0000117 clEnumValN(AnalysisGRSimpleVals, "grsimple",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000118 "Perform path-sensitive constant propagation."),
Ted Kremenekd55fe522008-02-15 00:35:38 +0000119 clEnumValN(AnalysisGRSimpleValsView, "grsimple-view",
120 "View results of path-sensitive constant propagation."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000121 clEnumValN(TestSerialization, "test-pickling",
122 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000124 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000125 clEnumValN(EmitBC, "emit-llvm-bc",
126 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000127 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000128 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000129 clEnumValN(RewriteTest, "rewrite-test",
130 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 clEnumValEnd));
132
Ted Kremenekccc76472007-12-19 19:47:59 +0000133
134static llvm::cl::opt<std::string>
135OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000136 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000137 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
138
Ted Kremenek41193e42007-09-26 19:42:19 +0000139static llvm::cl::opt<bool>
140VerifyDiagnostics("verify",
141 llvm::cl::desc("Verify emitted diagnostics and warnings."));
142
Reid Spencer5f016e22007-07-11 17:01:13 +0000143//===----------------------------------------------------------------------===//
144// Language Options
145//===----------------------------------------------------------------------===//
146
147enum LangKind {
148 langkind_unspecified,
149 langkind_c,
150 langkind_c_cpp,
151 langkind_cxx,
152 langkind_cxx_cpp,
153 langkind_objc,
154 langkind_objc_cpp,
155 langkind_objcxx,
156 langkind_objcxx_cpp
157};
158
159/* TODO: GCC also accepts:
160 c-header c++-header objective-c-header objective-c++-header
161 assembler assembler-with-cpp
162 ada, f77*, ratfor (!), f95, java, treelang
163 */
164static llvm::cl::opt<LangKind>
165BaseLang("x", llvm::cl::desc("Base language to compile"),
166 llvm::cl::init(langkind_unspecified),
167 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
168 clEnumValN(langkind_cxx, "c++", "C++"),
169 clEnumValN(langkind_objc, "objective-c", "Objective C"),
170 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
171 clEnumValN(langkind_c_cpp, "c-cpp-output",
172 "Preprocessed C"),
173 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
174 "Preprocessed C++"),
175 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
176 "Preprocessed Objective C"),
177 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
178 "Preprocessed Objective C++"),
179 clEnumValEnd));
180
181static llvm::cl::opt<bool>
182LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
183 llvm::cl::Hidden);
184static llvm::cl::opt<bool>
185LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
186 llvm::cl::Hidden);
187
Ted Kremenek8904f152007-12-05 23:49:08 +0000188/// InitializeBaseLanguage - Handle the -x foo options.
189static void InitializeBaseLanguage() {
190 if (LangObjC)
191 BaseLang = langkind_objc;
192 else if (LangObjCXX)
193 BaseLang = langkind_objcxx;
194}
195
196static LangKind GetLanguage(const std::string &Filename) {
197 if (BaseLang != langkind_unspecified)
198 return BaseLang;
199
200 std::string::size_type DotPos = Filename.rfind('.');
201
202 if (DotPos == std::string::npos) {
203 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000204 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 }
206
Ted Kremenek8904f152007-12-05 23:49:08 +0000207 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
208 // C header: .h
209 // C++ header: .hh or .H;
210 // assembler no preprocessing: .s
211 // assembler: .S
212 if (Ext == "c")
213 return langkind_c;
214 else if (Ext == "i")
215 return langkind_c_cpp;
216 else if (Ext == "ii")
217 return langkind_cxx_cpp;
218 else if (Ext == "m")
219 return langkind_objc;
220 else if (Ext == "mi")
221 return langkind_objc_cpp;
222 else if (Ext == "mm" || Ext == "M")
223 return langkind_objcxx;
224 else if (Ext == "mii")
225 return langkind_objcxx_cpp;
226 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
227 Ext == "c++" || Ext == "cp" || Ext == "cxx")
228 return langkind_cxx;
229 else
230 return langkind_c;
231}
232
233
234static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 // FIXME: implement -fpreprocessed mode.
236 bool NoPreprocess = false;
237
Ted Kremenek8904f152007-12-05 23:49:08 +0000238 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 default: assert(0 && "Unknown language kind!");
240 case langkind_c_cpp:
241 NoPreprocess = true;
242 // FALLTHROUGH
243 case langkind_c:
244 break;
245 case langkind_cxx_cpp:
246 NoPreprocess = true;
247 // FALLTHROUGH
248 case langkind_cxx:
249 Options.CPlusPlus = 1;
250 break;
251 case langkind_objc_cpp:
252 NoPreprocess = true;
253 // FALLTHROUGH
254 case langkind_objc:
255 Options.ObjC1 = Options.ObjC2 = 1;
256 break;
257 case langkind_objcxx_cpp:
258 NoPreprocess = true;
259 // FALLTHROUGH
260 case langkind_objcxx:
261 Options.ObjC1 = Options.ObjC2 = 1;
262 Options.CPlusPlus = 1;
263 break;
264 }
265}
266
267/// LangStds - Language standards we support.
268enum LangStds {
269 lang_unspecified,
270 lang_c89, lang_c94, lang_c99,
271 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000272 lang_cxx98, lang_gnucxx98,
273 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000274};
275
276static llvm::cl::opt<LangStds>
277LangStd("std", llvm::cl::desc("Language standard to compile for"),
278 llvm::cl::init(lang_unspecified),
279 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
280 clEnumValN(lang_c89, "c90", "ISO C 1990"),
281 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
282 clEnumValN(lang_c94, "iso9899:199409",
283 "ISO C 1990 with amendment 1"),
284 clEnumValN(lang_c99, "c99", "ISO C 1999"),
285// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
286 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
287// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
288 clEnumValN(lang_gnu89, "gnu89",
289 "ISO C 1990 with GNU extensions (default for C)"),
290 clEnumValN(lang_gnu99, "gnu99",
291 "ISO C 1999 with GNU extensions"),
292 clEnumValN(lang_gnu99, "gnu9x",
293 "ISO C 1999 with GNU extensions"),
294 clEnumValN(lang_cxx98, "c++98",
295 "ISO C++ 1998 with amendments"),
296 clEnumValN(lang_gnucxx98, "gnu++98",
297 "ISO C++ 1998 with amendments and GNU "
298 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000299 clEnumValN(lang_cxx0x, "c++0x",
300 "Upcoming ISO C++ 200x with amendments"),
301 clEnumValN(lang_gnucxx0x, "gnu++0x",
302 "Upcoming ISO C++ 200x with amendments and GNU "
303 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 clEnumValEnd));
305
306static llvm::cl::opt<bool>
307NoOperatorNames("fno-operator-names",
308 llvm::cl::desc("Do not treat C++ operator name keywords as "
309 "synonyms for operators"));
310
Anders Carlssonee98ac52007-10-15 02:50:23 +0000311static llvm::cl::opt<bool>
312PascalStrings("fpascal-strings",
313 llvm::cl::desc("Recognize and construct Pascal-style "
314 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000315
316static llvm::cl::opt<bool>
317MSExtensions("fms-extensions",
318 llvm::cl::desc("Accept some non-standard constructs used in "
319 "Microsoft header files. "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000320
321static llvm::cl::opt<bool>
322WritableStrings("fwritable-strings",
323 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000324
325static llvm::cl::opt<bool>
326LaxVectorConversions("flax-vector-conversions",
327 llvm::cl::desc("Allow implicit conversions between vectors"
328 " with a different number of elements or "
329 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000330// FIXME: add:
331// -ansi
332// -trigraphs
333// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000334// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000335static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 if (LangStd == lang_unspecified) {
337 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000338 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 default: assert(0 && "Unknown base language");
340 case langkind_c:
341 case langkind_c_cpp:
342 case langkind_objc:
343 case langkind_objc_cpp:
344 LangStd = lang_gnu99;
345 break;
346 case langkind_cxx:
347 case langkind_cxx_cpp:
348 case langkind_objcxx:
349 case langkind_objcxx_cpp:
350 LangStd = lang_gnucxx98;
351 break;
352 }
353 }
354
355 switch (LangStd) {
356 default: assert(0 && "Unknown language standard!");
357
358 // Fall through from newer standards to older ones. This isn't really right.
359 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000360 case lang_gnucxx0x:
361 case lang_cxx0x:
362 Options.CPlusPlus0x = 1;
363 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 case lang_gnucxx98:
365 case lang_cxx98:
366 Options.CPlusPlus = 1;
367 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000368 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 // FALL THROUGH.
370 case lang_gnu99:
371 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 Options.C99 = 1;
373 Options.HexFloats = 1;
374 // FALL THROUGH.
375 case lang_gnu89:
376 Options.BCPLComment = 1; // Only for C99/C++.
377 // FALL THROUGH.
378 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000379 Options.Digraphs = 1; // C94, C99, C++.
380 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 case lang_c89:
382 break;
383 }
384
385 Options.Trigraphs = 1; // -trigraphs or -ansi
386 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000387 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000388 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000389 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000390 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000391}
392
393//===----------------------------------------------------------------------===//
394// Our DiagnosticClient implementation
395//===----------------------------------------------------------------------===//
396
397// FIXME: Werror should take a list of things, -Werror=foo,bar
398static llvm::cl::opt<bool>
399WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
400
401static llvm::cl::opt<bool>
402WarnOnExtensions("pedantic", llvm::cl::init(false),
403 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
404
405static llvm::cl::opt<bool>
406ErrorOnExtensions("pedantic-errors",
407 llvm::cl::desc("Issue an error on uses of GCC extensions"));
408
409static llvm::cl::opt<bool>
410WarnUnusedMacros("Wunused_macros",
411 llvm::cl::desc("Warn for unused macros in the main translation unit"));
412
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000413static llvm::cl::opt<bool>
414WarnFloatEqual("Wfloat-equal",
415 llvm::cl::desc("Warn about equality comparisons of floating point values."));
416
Ted Kremenek73da5902007-12-17 17:50:07 +0000417static llvm::cl::opt<bool>
418WarnNoFormatNonLiteral("Wno-format-nonliteral",
419 llvm::cl::desc("Do not warn about non-literal format strings."));
420
Chris Lattner116a4b12008-01-23 17:19:46 +0000421static llvm::cl::opt<bool>
422WarnUndefMacros("Wundef",
423 llvm::cl::desc("Warn on use of undefined macros in #if's"));
424
425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426/// InitializeDiagnostics - Initialize the diagnostic object, based on the
427/// current command line option settings.
428static void InitializeDiagnostics(Diagnostic &Diags) {
429 Diags.setWarningsAsErrors(WarningsAsErrors);
430 Diags.setWarnOnExtensions(WarnOnExtensions);
431 Diags.setErrorOnExtensions(ErrorOnExtensions);
432
433 // Silence the "macro is not used" warning unless requested.
434 if (!WarnUnusedMacros)
435 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000436
437 // Silence "floating point comparison" warnings unless requested.
438 if (!WarnFloatEqual)
439 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000440
441 // Silence "format string is not a string literal" warnings if requested
442 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000443 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
444 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000445 if (!WarnUndefMacros)
446 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000447
448 if (MSExtensions) // MS allows unnamed struct/union fields.
449 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000450}
451
452//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000453// Analysis-specific options.
454//===----------------------------------------------------------------------===//
455
456static llvm::cl::opt<std::string>
457AnalyzeSpecificFunction("analyze-function",
458 llvm::cl::desc("Run analysis on specific function."));
459
460//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000461// Target Triple Processing.
462//===----------------------------------------------------------------------===//
463
464static llvm::cl::opt<std::string>
465TargetTriple("triple",
466 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
467
468static llvm::cl::list<std::string>
469Archs("arch",
470 llvm::cl::desc("Specify target architecture (e.g. i686)."));
471
472namespace {
473 class TripleProcessor {
474 llvm::StringMap<char> TriplesProcessed;
475 std::vector<std::string>& triples;
476 public:
477 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
478
479 void addTriple(const std::string& t) {
480 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
481 TriplesProcessed.end()) {
482 triples.push_back(t);
483 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
484 }
485 }
486 };
487}
488
489static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000490 // Initialize base triple. If a -triple option has been specified, use
491 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000492 std::string Triple = TargetTriple;
493 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000494
495 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000496 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000497
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000498 if (firstDash == std::string::npos) {
499 fprintf(stderr,
500 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000501 Triple.c_str());
502 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000503 }
Ted Kremenekae360762007-12-03 22:06:55 +0000504
Chris Lattner6590d212007-12-12 05:01:48 +0000505 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000506
507 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000508 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
509 Triple.c_str());
510 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000511 }
Ted Kremenekae360762007-12-03 22:06:55 +0000512
513 // Create triple cacher.
514 TripleProcessor tp(triples);
515
516 // Add the primary triple to our set of triples if we are using the
517 // host-triple with no archs or using a specified target triple.
518 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000519 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000520
521 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
522 tp.addTriple(Archs[i] + "-" + suffix);
523}
524
525//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000526// Preprocessor Initialization
527//===----------------------------------------------------------------------===//
528
529// FIXME: Preprocessor builtins to support.
530// -A... - Play with #assertions
531// -undef - Undefine all predefined macros
532
533static llvm::cl::list<std::string>
534D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
535 llvm::cl::desc("Predefine the specified macro"));
536static llvm::cl::list<std::string>
537U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
538 llvm::cl::desc("Undefine the specified macro"));
539
Chris Lattner64299f82008-01-10 01:53:41 +0000540static llvm::cl::list<std::string>
541ImplicitIncludes("include", llvm::cl::value_desc("file"),
542 llvm::cl::desc("Include file before parsing"));
543
544
Reid Spencer5f016e22007-07-11 17:01:13 +0000545// Append a #define line to Buf for Macro. Macro should be of the form XXX,
546// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
547// "#define XXX Y z W". To get a #define with no value, use "XXX=".
548static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
549 const char *Command = "#define ") {
550 Buf.insert(Buf.end(), Command, Command+strlen(Command));
551 if (const char *Equal = strchr(Macro, '=')) {
552 // Turn the = into ' '.
553 Buf.insert(Buf.end(), Macro, Equal);
554 Buf.push_back(' ');
555 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
556 } else {
557 // Push "macroname 1".
558 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
559 Buf.push_back(' ');
560 Buf.push_back('1');
561 }
562 Buf.push_back('\n');
563}
564
Chris Lattner64299f82008-01-10 01:53:41 +0000565/// AddImplicitInclude - Add an implicit #include of the specified file to the
566/// predefines buffer.
567static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
568 const char *Inc = "#include \"";
569 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
570 Buf.insert(Buf.end(), File.begin(), File.end());
571 Buf.push_back('"');
572 Buf.push_back('\n');
573}
574
Reid Spencer5f016e22007-07-11 17:01:13 +0000575
Chris Lattner53b0dab2007-10-09 22:10:18 +0000576/// InitializePreprocessor - Initialize the preprocessor getting it and the
577/// environment ready to process a single file. This returns the file ID for the
578/// input file. If a failure happens, it returns 0.
579///
580static unsigned InitializePreprocessor(Preprocessor &PP,
581 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000582 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000583
Chris Lattnerdee73592007-12-15 20:48:40 +0000584 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000585
Chris Lattner53b0dab2007-10-09 22:10:18 +0000586 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000587 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000588 if (InFile != "-") {
589 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000590 if (File) SourceMgr.createMainFileID(File, SourceLocation());
591 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000592 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
593 return 0;
594 }
595 } else {
596 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000597 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
598 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000599 fprintf(stderr, "Error reading standard input! Empty?\n");
600 return 0;
601 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 }
603
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 // Add macros from the command line.
605 // FIXME: Should traverse the #define/#undef lists in parallel.
606 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000607 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000609 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
610
Chris Lattner64299f82008-01-10 01:53:41 +0000611 // FIXME: Read any files specified by -imacros.
612
613 // Add implicit #includes from -include.
614 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
615 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000616
617 // Null terminate PredefinedBuffer and add it.
618 PredefineBuffer.push_back(0);
619 PP.setPredefines(&PredefineBuffer[0]);
620
621 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000622 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000623}
624
625//===----------------------------------------------------------------------===//
626// Preprocessor include path information.
627//===----------------------------------------------------------------------===//
628
629// This tool exports a large number of command line options to control how the
630// preprocessor searches for header files. At root, however, the Preprocessor
631// object takes a very simple interface: a list of directories to search for
632//
633// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000634// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000635//
Chris Lattner64299f82008-01-10 01:53:41 +0000636// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000637
638static llvm::cl::opt<bool>
639nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
640
641// Various command line options. These four add directories to each chain.
642static llvm::cl::list<std::string>
643F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
644 llvm::cl::desc("Add directory to framework include search path"));
645static llvm::cl::list<std::string>
646I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
647 llvm::cl::desc("Add directory to include search path"));
648static llvm::cl::list<std::string>
649idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
650 llvm::cl::desc("Add directory to AFTER include search path"));
651static llvm::cl::list<std::string>
652iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
653 llvm::cl::desc("Add directory to QUOTE include search path"));
654static llvm::cl::list<std::string>
655isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
656 llvm::cl::desc("Add directory to SYSTEM include search path"));
657
658// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
659static llvm::cl::list<std::string>
660iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
661 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
662static llvm::cl::list<std::string>
663iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
664 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
665static llvm::cl::list<std::string>
666iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
667 llvm::cl::Prefix,
668 llvm::cl::desc("Set directory to include search path with prefix"));
669
Chris Lattner0c946412007-08-26 17:47:35 +0000670static llvm::cl::opt<std::string>
671isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
672 llvm::cl::desc("Set the system root directory (usually /)"));
673
Reid Spencer5f016e22007-07-11 17:01:13 +0000674// Finally, implement the code that groks the options above.
675enum IncludeDirGroup {
676 Quoted = 0,
677 Angled,
678 System,
679 After
680};
681
682static std::vector<DirectoryLookup> IncludeGroup[4];
683
684/// AddPath - Add the specified path to the specified group list.
685///
686static void AddPath(const std::string &Path, IncludeDirGroup Group,
687 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000688 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000689 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000690 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000691
Chris Lattnerd6655272007-12-17 05:59:27 +0000692 // Compute the actual path, taking into consideration -isysroot.
693 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000694
Chris Lattnerd6655272007-12-17 05:59:27 +0000695 // Handle isysroot.
696 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000697 // FIXME: Portability. This should be a sys::Path interface, this doesn't
698 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000699 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
700 MappedPath.append(isysroot.begin(), isysroot.end());
701 if (Path[0] != '/') // If in the system group, add a /.
702 MappedPath.push_back('/');
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 }
704
Chris Lattnerd6655272007-12-17 05:59:27 +0000705 MappedPath.append(Path.begin(), Path.end());
706
707 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000708 DirectoryLookup::DirType Type;
709 if (Group == Quoted || Group == Angled)
710 Type = DirectoryLookup::NormalHeaderDir;
711 else if (isCXXAware)
712 Type = DirectoryLookup::SystemHeaderDir;
713 else
714 Type = DirectoryLookup::ExternCSystemHeaderDir;
715
Chris Lattnerd6655272007-12-17 05:59:27 +0000716
717 // If the directory exists, add it.
718 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
719 &MappedPath[0]+
720 MappedPath.size())) {
721 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
722 isFramework));
723 return;
724 }
725
Chris Lattnerdf772332007-12-17 07:52:39 +0000726 // Check to see if this is an apple-style headermap (which are not allowed to
727 // be frameworks).
728 if (!isFramework) {
729 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
730 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000731 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
732 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000733 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
734 return;
735 }
Chris Lattner822da612007-12-17 06:36:45 +0000736 }
737 }
738
Chris Lattnerd6655272007-12-17 05:59:27 +0000739 if (Verbose)
740 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000741}
742
743/// RemoveDuplicates - If there are duplicate directory entries in the specified
744/// search list, remove the later (dead) ones.
745static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000746 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000747 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000748 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000750 if (SearchList[i].isNormalDir()) {
751 // If this isn't the first time we've seen this dir, remove it.
752 if (SeenDirs.insert(SearchList[i].getDir()))
753 continue;
754
Reid Spencer5f016e22007-07-11 17:01:13 +0000755 if (Verbose)
756 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
757 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000758 } else if (SearchList[i].isFramework()) {
759 // If this isn't the first time we've seen this framework dir, remove it.
760 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
761 continue;
762
763 if (Verbose)
764 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
765 SearchList[i].getFrameworkDir()->getName());
766
Chris Lattnerb94c7072007-12-17 06:44:29 +0000767 } else {
768 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
769 // If this isn't the first time we've seen this headermap, remove it.
770 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
771 continue;
772
773 if (Verbose)
774 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
775 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000776 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000777
778 // This is reached if the current entry is a duplicate.
779 SearchList.erase(SearchList.begin()+i);
780 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000781 }
782}
783
784/// InitializeIncludePaths - Process the -I options and set them in the
785/// HeaderSearch object.
786static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000787 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 // Handle -F... options.
789 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000790 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000791
792 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000793 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000794 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000795
796 // Handle -idirafter... options.
797 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000798 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000799
800 // Handle -iquote... options.
801 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000802 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000803
804 // Handle -isystem... options.
805 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000806 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000807
808 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
809 // parallel, processing the values in order of occurance to get the right
810 // prefixes.
811 {
812 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
813 unsigned iprefix_idx = 0;
814 unsigned iwithprefix_idx = 0;
815 unsigned iwithprefixbefore_idx = 0;
816 bool iprefix_done = iprefix_vals.empty();
817 bool iwithprefix_done = iwithprefix_vals.empty();
818 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
819 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
820 if (!iprefix_done &&
821 (iwithprefix_done ||
822 iprefix_vals.getPosition(iprefix_idx) <
823 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
824 (iwithprefixbefore_done ||
825 iprefix_vals.getPosition(iprefix_idx) <
826 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
827 Prefix = iprefix_vals[iprefix_idx];
828 ++iprefix_idx;
829 iprefix_done = iprefix_idx == iprefix_vals.size();
830 } else if (!iwithprefix_done &&
831 (iwithprefixbefore_done ||
832 iwithprefix_vals.getPosition(iwithprefix_idx) <
833 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
834 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000835 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000836 ++iwithprefix_idx;
837 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
838 } else {
839 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000840 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000841 ++iwithprefixbefore_idx;
842 iwithprefixbefore_done =
843 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
844 }
845 }
846 }
847
848 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
849 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
850
851 // FIXME: temporary hack: hard-coded paths.
852 // FIXME: get these from the target?
853 if (!nostdinc) {
854 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000855 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000856 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000857 false, Headers);
858 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
859 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000860
861 // Ubuntu 7.10 - Gutsy Gibbon
862 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
863 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
864 false, Headers);
865 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
866 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000867 }
868
Chris Lattner822da612007-12-17 06:36:45 +0000869 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000870 // leopard
871 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000872 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000874 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
876 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000877 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000878
879 // tiger
880 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000881 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000882 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000883 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000884 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
885 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000886 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000887
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000888 // Ubuntu 7.10 - Gutsy Gibbon
889 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
890 false, false, false, Headers);
891
Chris Lattner822da612007-12-17 06:36:45 +0000892 AddPath("/usr/include", System, false, false, false, Headers);
893 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
894 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 }
896
897 // Now that we have collected all of the include paths, merge them all
898 // together and tell the preprocessor about them.
899
900 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
901 std::vector<DirectoryLookup> SearchList;
902 SearchList = IncludeGroup[Angled];
903 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
904 IncludeGroup[System].end());
905 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
906 IncludeGroup[After].end());
907 RemoveDuplicates(SearchList);
908 RemoveDuplicates(IncludeGroup[Quoted]);
909
910 // Prepend QUOTED list on the search list.
911 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
912 IncludeGroup[Quoted].end());
913
914
915 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
916 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
917 DontSearchCurDir);
918
919 // If verbose, print the list of directories that will be searched.
920 if (Verbose) {
921 fprintf(stderr, "#include \"...\" search starts here:\n");
922 unsigned QuotedIdx = IncludeGroup[Quoted].size();
923 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
924 if (i == QuotedIdx)
925 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000926 const char *Name = SearchList[i].getName();
927 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000928 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000929 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000930 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000931 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000932 else {
933 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000934 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000935 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000936 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000937 }
Chris Lattner80e17152007-12-15 23:11:06 +0000938 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000939 }
940}
941
942
Reid Spencer5f016e22007-07-11 17:01:13 +0000943//===----------------------------------------------------------------------===//
944// Basic Parser driver
945//===----------------------------------------------------------------------===//
946
Ted Kremenek95041a22007-12-19 22:51:13 +0000947static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000948 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000949 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000950
951 // Parsing the specified input file.
952 P.ParseTranslationUnit();
953 delete PA;
954}
955
956//===----------------------------------------------------------------------===//
957// Main driver
958//===----------------------------------------------------------------------===//
959
Ted Kremenekdb094a22007-12-05 18:27:04 +0000960/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
961/// action. These consumers can operate on both ASTs that are freshly
962/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000963static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000964 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +0000965 const LangOptions& LangOpts,
966 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +0000967 switch (ProgAction) {
968 default:
969 return NULL;
970
971 case ASTPrint:
972 return CreateASTPrinter();
973
974 case ASTDump:
975 return CreateASTDumper();
976
977 case ASTView:
978 return CreateASTViewer();
979
980 case ParseCFGDump:
981 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +0000982 return CreateCFGDumper(ProgAction == ParseCFGView,
983 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000984
985 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +0000986 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000987
988 case WarnDeadStores:
989 return CreateDeadStoreChecker(Diag);
990
991 case WarnUninitVals:
992 return CreateUnitValsChecker(Diag);
993
Ted Kremeneke01c9872008-02-14 22:36:46 +0000994 case AnalysisGRSimpleVals:
Ted Kremenekcb330932008-02-18 21:21:23 +0000995 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction);
Ted Kremeneke603df42008-01-08 18:04:06 +0000996
Ted Kremenekd55fe522008-02-15 00:35:38 +0000997 case AnalysisGRSimpleValsView:
Ted Kremenekcb330932008-02-18 21:21:23 +0000998 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, true);
Ted Kremenekd55fe522008-02-15 00:35:38 +0000999
Ted Kremenekdb094a22007-12-05 18:27:04 +00001000 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001001 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001002
1003 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001004 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001005 DestModule = new llvm::Module(InFile);
1006 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001007
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001008 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001009 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001010 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001011
Ted Kremenekdb094a22007-12-05 18:27:04 +00001012 case RewriteTest:
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +00001013 return CreateCodeRewriterTest(InFile, Diag);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001014 }
1015}
1016
Reid Spencer5f016e22007-07-11 17:01:13 +00001017/// ProcessInputFile - Process a single input file with the specified state.
1018///
Ted Kremenek7dcc9682007-12-19 22:32:34 +00001019static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +00001020 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001021
1022 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001023 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001024 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001025
Reid Spencer5f016e22007-07-11 17:01:13 +00001026 switch (ProgAction) {
1027 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001028 Consumer = CreateASTConsumer(InFile,
1029 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001030 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001031 PP.getLangOptions(),
1032 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001033
1034 if (!Consumer) {
1035 fprintf(stderr, "Unexpected program action!\n");
1036 return;
1037 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001038
Ted Kremenekdb094a22007-12-05 18:27:04 +00001039 break;
1040
Reid Spencer5f016e22007-07-11 17:01:13 +00001041 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001042 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001043 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001044 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 do {
1046 PP.Lex(Tok);
1047 PP.DumpToken(Tok, true);
1048 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001049 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001050 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 break;
1052 }
1053 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001054 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001056 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001057 do {
1058 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001059 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001060 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001061 break;
1062 }
1063
1064 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001065 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001066 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001067 break;
1068
1069 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001070 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001071 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001072 break;
1073
1074 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001075 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001076 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001077 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001078
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001079 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001080 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001081 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001082 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001083
1084 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001085 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001086 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001087
1088 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001089 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001091
1092 // If running the code generator, finish up now.
1093 if (CodeGenModule) {
1094 std::ostream *Out;
1095 if (OutputFile == "-") {
1096 Out = llvm::cout.stream();
1097 } else if (!OutputFile.empty()) {
1098 Out = new std::ofstream(OutputFile.c_str(),
1099 std::ios_base::binary|std::ios_base::out);
1100 } else if (InFile == "-") {
1101 Out = llvm::cout.stream();
1102 } else {
1103 llvm::sys::Path Path(InFile);
1104 Path.eraseSuffix();
1105 if (ProgAction == EmitLLVM)
1106 Path.appendSuffix("ll");
1107 else if (ProgAction == EmitBC)
1108 Path.appendSuffix("bc");
1109 else
1110 assert(0 && "Unknown action");
1111 Out = new std::ofstream(Path.toString().c_str(),
1112 std::ios_base::binary|std::ios_base::out);
1113 }
1114
1115 if (ProgAction == EmitLLVM) {
1116 CodeGenModule->print(*Out);
1117 } else {
1118 assert(ProgAction == EmitBC);
1119 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1120 }
1121
1122 if (Out != llvm::cout.stream())
1123 delete Out;
1124 delete CodeGenModule;
1125 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001126
1127 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001128 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 PP.PrintStats();
1130 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001131 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001132 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001133 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 fprintf(stderr, "\n");
1135 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001136
1137 // For a multi-file compilation, some things are ok with nuking the source
1138 // manager tables, other require stable fileid/macroid's across multiple
1139 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001140 if (ClearSourceMgr)
1141 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001142}
1143
Ted Kremenek20e97482007-12-12 23:41:08 +00001144static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1145 FileManager& FileMgr) {
1146
1147 if (VerifyDiagnostics) {
1148 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1149 exit (1);
1150 }
1151
1152 llvm::sys::Path Filename(InFile);
1153
1154 if (!Filename.isValid()) {
1155 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1156 exit (1);
1157 }
1158
Ted Kremenekee533642007-12-20 19:47:16 +00001159 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001160
1161 if (!TU) {
1162 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1163 InFile.c_str());
1164 exit (1);
1165 }
1166
Ted Kremenek63ea8632007-12-19 19:27:38 +00001167 // Observe that we use the source file name stored in the deserialized
1168 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001169 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001170 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001171 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1172 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001173
1174 if (!Consumer) {
1175 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1176 exit (1);
1177 }
1178
Ted Kremenek95041a22007-12-19 22:51:13 +00001179 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001180
Chris Lattnere66b65c2008-02-06 01:42:25 +00001181 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001182 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1183 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001184}
1185
1186
Reid Spencer5f016e22007-07-11 17:01:13 +00001187static llvm::cl::list<std::string>
1188InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1189
Ted Kremenek20e97482007-12-12 23:41:08 +00001190static bool isSerializedFile(const std::string& InFile) {
1191 if (InFile.size() < 4)
1192 return false;
1193
1194 const char* s = InFile.c_str()+InFile.size()-4;
1195
1196 return s[0] == '.' &&
1197 s[1] == 'a' &&
1198 s[2] == 's' &&
1199 s[3] == 't';
1200}
1201
Reid Spencer5f016e22007-07-11 17:01:13 +00001202
1203int main(int argc, char **argv) {
1204 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1205 llvm::sys::PrintStackTraceOnErrorSignal();
1206
1207 // If no input was specified, read from stdin.
1208 if (InputFilenames.empty())
1209 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001210
Reid Spencer5f016e22007-07-11 17:01:13 +00001211 // Create a file manager object to provide access to and cache the filesystem.
1212 FileManager FileMgr;
1213
Ted Kremenek31e703b2007-12-11 23:28:38 +00001214 // Create the diagnostic client for reporting errors or for
1215 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001217 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001219 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 } else {
1221 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001222 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001223
1224 if (InputFilenames.size() != 1) {
1225 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001226 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 return 1;
1228 }
1229 }
1230
1231 // Configure our handling of diagnostics.
1232 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001233 InitializeDiagnostics(Diags);
1234
Chris Lattner4f037832007-12-05 23:24:17 +00001235 // -I- is a deprecated GCC feature, scan for it and reject it.
1236 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1237 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001238 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001239 I_dirs.erase(I_dirs.begin()+i);
1240 --i;
1241 }
1242 }
1243
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001245 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001246
Ted Kremenek20e97482007-12-12 23:41:08 +00001247 if (isSerializedFile(InFile))
1248 ProcessSerializedFile(InFile,Diags,FileMgr);
1249 else {
1250 /// Create a SourceManager object. This tracks and owns all the file
1251 /// buffers allocated to a translation unit.
1252 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001253
Ted Kremenek20e97482007-12-12 23:41:08 +00001254 // Initialize language options, inferring file types from input filenames.
1255 LangOptions LangInfo;
1256 InitializeBaseLanguage();
1257 LangKind LK = GetLanguage(InFile);
1258 InitializeLangOptions(LangInfo, LK);
1259 InitializeLanguageStandard(LangInfo, LK);
1260
1261 // Process the -I options and set them in the HeaderInfo.
1262 HeaderSearch HeaderInfo(FileMgr);
1263 DiagClient->setHeaderSearch(HeaderInfo);
1264 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1265
1266 // Get information about the targets being compiled for. Note that this
1267 // pointer and the TargetInfoImpl objects are never deleted by this toy
1268 // driver.
1269 TargetInfo *Target;
1270
1271 // Create triples, and create the TargetInfo.
1272 std::vector<std::string> triples;
1273 CreateTargetTriples(triples);
1274 Target = TargetInfo::CreateTargetInfo(&triples[0],
1275 &triples[0]+triples.size(),
1276 &Diags);
1277
1278 if (Target == 0) {
1279 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1280 triples[0].c_str());
1281 fprintf(stderr, "Please use -triple or -arch.\n");
1282 exit(1);
1283 }
1284
1285 // Set up the preprocessor with these options.
1286 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1287
1288 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001289 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001290 continue;
1291
Ted Kremenek1036b682007-12-19 23:48:45 +00001292 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001293 HeaderInfo.ClearFileInfo();
1294
1295 if (Stats)
1296 SourceMgr.PrintStats();
1297 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 }
1299
1300 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1301
1302 if (NumDiagnostics)
1303 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1304 (NumDiagnostics == 1 ? "" : "s"));
1305
1306 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 FileMgr.PrintStats();
1308 fprintf(stderr, "\n");
1309 }
1310
Chris Lattner96f1a642007-07-21 05:40:53 +00001311 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001312}