blob: f3b8765ea8377026013624106bd88888dd0a5621 [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"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000046#include "llvm/System/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047#include <memory>
Chris Lattnere66b65c2008-02-06 01:42:25 +000048#include <fstream>
Reid Spencer5f016e22007-07-11 17:01:13 +000049using namespace clang;
50
51//===----------------------------------------------------------------------===//
52// Global options.
53//===----------------------------------------------------------------------===//
54
55static llvm::cl::opt<bool>
56Verbose("v", llvm::cl::desc("Enable verbose output"));
57static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000058Stats("print-stats",
59 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000060
61enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000062 RewriteTest, // Rewriter testing stuff.
Ted Kremenek13e479b2008-03-19 07:53:42 +000063 HTMLTest, // HTML displayer testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000064 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000065 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000066 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000067 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000068 ASTPrint, // Parse ASTs and print them.
69 ASTDump, // Parse ASTs and dump them.
70 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000071 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000072 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000073 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenekd55fe522008-02-15 00:35:38 +000074 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
75 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek2fff37e2008-03-06 00:08:09 +000076 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremenek055c2752007-09-06 23:00:42 +000077 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000078 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000079 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000080 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000081 ParsePrintCallbacks, // Parse and print each callback.
82 ParseSyntaxOnly, // Parse and perform semantic analysis.
83 ParseNoop, // Parse with noop callbacks.
84 RunPreprocessorOnly, // Just lex, no output.
85 PrintPreprocessedInput, // -E mode.
86 DumpTokens // Token dump mode.
87};
88
89static llvm::cl::opt<ProgActions>
90ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
91 llvm::cl::init(ParseSyntaxOnly),
92 llvm::cl::values(
93 clEnumValN(RunPreprocessorOnly, "Eonly",
94 "Just run preprocessor, no output (for timings)"),
95 clEnumValN(PrintPreprocessedInput, "E",
96 "Run preprocessor, emit preprocessed file"),
97 clEnumValN(DumpTokens, "dumptokens",
98 "Run preprocessor, dump internal rep of tokens"),
99 clEnumValN(ParseNoop, "parse-noop",
100 "Run parser with noop callbacks (for timings)"),
101 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
102 "Run parser and perform semantic analysis"),
103 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
104 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000105 clEnumValN(EmitHTML, "emit-html",
106 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000107 clEnumValN(ASTPrint, "ast-print",
108 "Build ASTs and then pretty-print them"),
109 clEnumValN(ASTDump, "ast-dump",
110 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000111 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000112 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000113 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000114 "Run parser, then build and print CFGs."),
115 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000116 "Run parser, then build and view CFGs with Graphviz."),
117 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000118 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000119 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000120 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000121 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000122 "Flag warnings of uses of unitialized variables."),
Ted Kremeneke01c9872008-02-14 22:36:46 +0000123 clEnumValN(AnalysisGRSimpleVals, "grsimple",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000124 "Perform path-sensitive constant propagation."),
Ted Kremenekd55fe522008-02-15 00:35:38 +0000125 clEnumValN(AnalysisGRSimpleValsView, "grsimple-view",
126 "View results of path-sensitive constant propagation."),
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000127 clEnumValN(CheckerCFRef, "check-cfref",
128 "Run the Core Foundation reference count checker."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000129 clEnumValN(TestSerialization, "test-pickling",
Chris Lattnerf3dabbd2008-03-09 05:25:01 +0000130 "Run prototype serialization code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000132 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000133 clEnumValN(EmitBC, "emit-llvm-bc",
134 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000135 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000136 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000137 clEnumValN(RewriteTest, "rewrite-test",
138 "Playground for the code rewriter"),
Ted Kremenek13e479b2008-03-19 07:53:42 +0000139 clEnumValN(HTMLTest, "html-test",
140 "Playground for the HTML displayer"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 clEnumValEnd));
142
Ted Kremenekccc76472007-12-19 19:47:59 +0000143
144static llvm::cl::opt<std::string>
145OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000146 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000147 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
148
Ted Kremenek41193e42007-09-26 19:42:19 +0000149static llvm::cl::opt<bool>
150VerifyDiagnostics("verify",
151 llvm::cl::desc("Verify emitted diagnostics and warnings."));
152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153//===----------------------------------------------------------------------===//
154// Language Options
155//===----------------------------------------------------------------------===//
156
157enum LangKind {
158 langkind_unspecified,
159 langkind_c,
160 langkind_c_cpp,
161 langkind_cxx,
162 langkind_cxx_cpp,
163 langkind_objc,
164 langkind_objc_cpp,
165 langkind_objcxx,
166 langkind_objcxx_cpp
167};
168
169/* TODO: GCC also accepts:
170 c-header c++-header objective-c-header objective-c++-header
171 assembler assembler-with-cpp
172 ada, f77*, ratfor (!), f95, java, treelang
173 */
174static llvm::cl::opt<LangKind>
175BaseLang("x", llvm::cl::desc("Base language to compile"),
176 llvm::cl::init(langkind_unspecified),
177 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
178 clEnumValN(langkind_cxx, "c++", "C++"),
179 clEnumValN(langkind_objc, "objective-c", "Objective C"),
180 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
181 clEnumValN(langkind_c_cpp, "c-cpp-output",
182 "Preprocessed C"),
183 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
184 "Preprocessed C++"),
185 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
186 "Preprocessed Objective C"),
187 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
188 "Preprocessed Objective C++"),
189 clEnumValEnd));
190
191static llvm::cl::opt<bool>
192LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
193 llvm::cl::Hidden);
194static llvm::cl::opt<bool>
195LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
196 llvm::cl::Hidden);
197
Ted Kremenek8904f152007-12-05 23:49:08 +0000198/// InitializeBaseLanguage - Handle the -x foo options.
199static void InitializeBaseLanguage() {
200 if (LangObjC)
201 BaseLang = langkind_objc;
202 else if (LangObjCXX)
203 BaseLang = langkind_objcxx;
204}
205
206static LangKind GetLanguage(const std::string &Filename) {
207 if (BaseLang != langkind_unspecified)
208 return BaseLang;
209
210 std::string::size_type DotPos = Filename.rfind('.');
211
212 if (DotPos == std::string::npos) {
213 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000214 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000215 }
216
Ted Kremenek8904f152007-12-05 23:49:08 +0000217 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
218 // C header: .h
219 // C++ header: .hh or .H;
220 // assembler no preprocessing: .s
221 // assembler: .S
222 if (Ext == "c")
223 return langkind_c;
224 else if (Ext == "i")
225 return langkind_c_cpp;
226 else if (Ext == "ii")
227 return langkind_cxx_cpp;
228 else if (Ext == "m")
229 return langkind_objc;
230 else if (Ext == "mi")
231 return langkind_objc_cpp;
232 else if (Ext == "mm" || Ext == "M")
233 return langkind_objcxx;
234 else if (Ext == "mii")
235 return langkind_objcxx_cpp;
236 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
237 Ext == "c++" || Ext == "cp" || Ext == "cxx")
238 return langkind_cxx;
239 else
240 return langkind_c;
241}
242
243
244static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 // FIXME: implement -fpreprocessed mode.
246 bool NoPreprocess = false;
247
Ted Kremenek8904f152007-12-05 23:49:08 +0000248 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 default: assert(0 && "Unknown language kind!");
250 case langkind_c_cpp:
251 NoPreprocess = true;
252 // FALLTHROUGH
253 case langkind_c:
254 break;
255 case langkind_cxx_cpp:
256 NoPreprocess = true;
257 // FALLTHROUGH
258 case langkind_cxx:
259 Options.CPlusPlus = 1;
260 break;
261 case langkind_objc_cpp:
262 NoPreprocess = true;
263 // FALLTHROUGH
264 case langkind_objc:
265 Options.ObjC1 = Options.ObjC2 = 1;
266 break;
267 case langkind_objcxx_cpp:
268 NoPreprocess = true;
269 // FALLTHROUGH
270 case langkind_objcxx:
271 Options.ObjC1 = Options.ObjC2 = 1;
272 Options.CPlusPlus = 1;
273 break;
274 }
275}
276
277/// LangStds - Language standards we support.
278enum LangStds {
279 lang_unspecified,
280 lang_c89, lang_c94, lang_c99,
281 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000282 lang_cxx98, lang_gnucxx98,
283 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000284};
285
286static llvm::cl::opt<LangStds>
287LangStd("std", llvm::cl::desc("Language standard to compile for"),
288 llvm::cl::init(lang_unspecified),
289 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
290 clEnumValN(lang_c89, "c90", "ISO C 1990"),
291 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
292 clEnumValN(lang_c94, "iso9899:199409",
293 "ISO C 1990 with amendment 1"),
294 clEnumValN(lang_c99, "c99", "ISO C 1999"),
295// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
296 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
297// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
298 clEnumValN(lang_gnu89, "gnu89",
299 "ISO C 1990 with GNU extensions (default for C)"),
300 clEnumValN(lang_gnu99, "gnu99",
301 "ISO C 1999 with GNU extensions"),
302 clEnumValN(lang_gnu99, "gnu9x",
303 "ISO C 1999 with GNU extensions"),
304 clEnumValN(lang_cxx98, "c++98",
305 "ISO C++ 1998 with amendments"),
306 clEnumValN(lang_gnucxx98, "gnu++98",
307 "ISO C++ 1998 with amendments and GNU "
308 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000309 clEnumValN(lang_cxx0x, "c++0x",
310 "Upcoming ISO C++ 200x with amendments"),
311 clEnumValN(lang_gnucxx0x, "gnu++0x",
312 "Upcoming ISO C++ 200x with amendments and GNU "
313 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 clEnumValEnd));
315
316static llvm::cl::opt<bool>
317NoOperatorNames("fno-operator-names",
318 llvm::cl::desc("Do not treat C++ operator name keywords as "
319 "synonyms for operators"));
320
Anders Carlssonee98ac52007-10-15 02:50:23 +0000321static llvm::cl::opt<bool>
322PascalStrings("fpascal-strings",
323 llvm::cl::desc("Recognize and construct Pascal-style "
324 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000325
326static llvm::cl::opt<bool>
327MSExtensions("fms-extensions",
328 llvm::cl::desc("Accept some non-standard constructs used in "
329 "Microsoft header files. "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000330
331static llvm::cl::opt<bool>
332WritableStrings("fwritable-strings",
333 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000334
335static llvm::cl::opt<bool>
336LaxVectorConversions("flax-vector-conversions",
337 llvm::cl::desc("Allow implicit conversions between vectors"
338 " with a different number of elements or "
339 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000340// FIXME: add:
341// -ansi
342// -trigraphs
343// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000344// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000345static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 if (LangStd == lang_unspecified) {
347 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000348 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 default: assert(0 && "Unknown base language");
350 case langkind_c:
351 case langkind_c_cpp:
352 case langkind_objc:
353 case langkind_objc_cpp:
354 LangStd = lang_gnu99;
355 break;
356 case langkind_cxx:
357 case langkind_cxx_cpp:
358 case langkind_objcxx:
359 case langkind_objcxx_cpp:
360 LangStd = lang_gnucxx98;
361 break;
362 }
363 }
364
365 switch (LangStd) {
366 default: assert(0 && "Unknown language standard!");
367
368 // Fall through from newer standards to older ones. This isn't really right.
369 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000370 case lang_gnucxx0x:
371 case lang_cxx0x:
372 Options.CPlusPlus0x = 1;
373 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 case lang_gnucxx98:
375 case lang_cxx98:
376 Options.CPlusPlus = 1;
377 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000378 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 // FALL THROUGH.
380 case lang_gnu99:
381 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 Options.C99 = 1;
383 Options.HexFloats = 1;
384 // FALL THROUGH.
385 case lang_gnu89:
386 Options.BCPLComment = 1; // Only for C99/C++.
387 // FALL THROUGH.
388 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000389 Options.Digraphs = 1; // C94, C99, C++.
390 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 case lang_c89:
392 break;
393 }
394
395 Options.Trigraphs = 1; // -trigraphs or -ansi
396 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000397 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000398 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000399 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000400 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000401}
402
403//===----------------------------------------------------------------------===//
404// Our DiagnosticClient implementation
405//===----------------------------------------------------------------------===//
406
407// FIXME: Werror should take a list of things, -Werror=foo,bar
408static llvm::cl::opt<bool>
409WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
410
411static llvm::cl::opt<bool>
412WarnOnExtensions("pedantic", llvm::cl::init(false),
413 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
414
415static llvm::cl::opt<bool>
416ErrorOnExtensions("pedantic-errors",
417 llvm::cl::desc("Issue an error on uses of GCC extensions"));
418
419static llvm::cl::opt<bool>
420WarnUnusedMacros("Wunused_macros",
421 llvm::cl::desc("Warn for unused macros in the main translation unit"));
422
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000423static llvm::cl::opt<bool>
424WarnFloatEqual("Wfloat-equal",
425 llvm::cl::desc("Warn about equality comparisons of floating point values."));
426
Ted Kremenek73da5902007-12-17 17:50:07 +0000427static llvm::cl::opt<bool>
428WarnNoFormatNonLiteral("Wno-format-nonliteral",
429 llvm::cl::desc("Do not warn about non-literal format strings."));
430
Chris Lattner116a4b12008-01-23 17:19:46 +0000431static llvm::cl::opt<bool>
432WarnUndefMacros("Wundef",
433 llvm::cl::desc("Warn on use of undefined macros in #if's"));
434
435
Reid Spencer5f016e22007-07-11 17:01:13 +0000436/// InitializeDiagnostics - Initialize the diagnostic object, based on the
437/// current command line option settings.
438static void InitializeDiagnostics(Diagnostic &Diags) {
439 Diags.setWarningsAsErrors(WarningsAsErrors);
440 Diags.setWarnOnExtensions(WarnOnExtensions);
441 Diags.setErrorOnExtensions(ErrorOnExtensions);
442
443 // Silence the "macro is not used" warning unless requested.
444 if (!WarnUnusedMacros)
445 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000446
447 // Silence "floating point comparison" warnings unless requested.
448 if (!WarnFloatEqual)
449 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000450
451 // Silence "format string is not a string literal" warnings if requested
452 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000453 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
454 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000455 if (!WarnUndefMacros)
456 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000457
458 if (MSExtensions) // MS allows unnamed struct/union fields.
459 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000460}
461
462//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000463// Analysis-specific options.
464//===----------------------------------------------------------------------===//
465
466static llvm::cl::opt<std::string>
467AnalyzeSpecificFunction("analyze-function",
468 llvm::cl::desc("Run analysis on specific function."));
469
Ted Kremenekffe0f432008-03-07 22:58:01 +0000470static llvm::cl::opt<bool>
471TrimGraph("trim-path-graph",
472 llvm::cl::desc("Only show error-related paths in the analysis graph."));
473
474
Ted Kremenekcb330932008-02-18 21:21:23 +0000475//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000476// Target Triple Processing.
477//===----------------------------------------------------------------------===//
478
479static llvm::cl::opt<std::string>
480TargetTriple("triple",
481 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
482
Chris Lattner42e67372008-03-05 01:18:20 +0000483static llvm::cl::opt<std::string>
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000484Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)."));
Ted Kremenekae360762007-12-03 22:06:55 +0000485
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000486static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000487 // Initialize base triple. If a -triple option has been specified, use
488 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000489 std::string Triple = TargetTriple;
490 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000491
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000492 // If -arch foo was specified, remove the architecture from the triple we have
493 // so far and replace it with the specified one.
494 if (Arch.empty())
495 return Triple;
496
Ted Kremenekae360762007-12-03 22:06:55 +0000497 // Decompose the base triple into "arch" and suffix.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000498 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000499
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000500 if (FirstDashIdx == std::string::npos) {
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000501 fprintf(stderr,
502 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000503 Triple.c_str());
504 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000505 }
Ted Kremenekae360762007-12-03 22:06:55 +0000506
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000507 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenekae360762007-12-03 22:06:55 +0000508}
509
510//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000511// Preprocessor Initialization
512//===----------------------------------------------------------------------===//
513
514// FIXME: Preprocessor builtins to support.
515// -A... - Play with #assertions
516// -undef - Undefine all predefined macros
517
518static llvm::cl::list<std::string>
519D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
520 llvm::cl::desc("Predefine the specified macro"));
521static llvm::cl::list<std::string>
522U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
523 llvm::cl::desc("Undefine the specified macro"));
524
Chris Lattner64299f82008-01-10 01:53:41 +0000525static llvm::cl::list<std::string>
526ImplicitIncludes("include", llvm::cl::value_desc("file"),
527 llvm::cl::desc("Include file before parsing"));
528
529
Reid Spencer5f016e22007-07-11 17:01:13 +0000530// Append a #define line to Buf for Macro. Macro should be of the form XXX,
531// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
532// "#define XXX Y z W". To get a #define with no value, use "XXX=".
533static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
534 const char *Command = "#define ") {
535 Buf.insert(Buf.end(), Command, Command+strlen(Command));
536 if (const char *Equal = strchr(Macro, '=')) {
537 // Turn the = into ' '.
538 Buf.insert(Buf.end(), Macro, Equal);
539 Buf.push_back(' ');
540 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
541 } else {
542 // Push "macroname 1".
543 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
544 Buf.push_back(' ');
545 Buf.push_back('1');
546 }
547 Buf.push_back('\n');
548}
549
Chris Lattner64299f82008-01-10 01:53:41 +0000550/// AddImplicitInclude - Add an implicit #include of the specified file to the
551/// predefines buffer.
552static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
553 const char *Inc = "#include \"";
554 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
555 Buf.insert(Buf.end(), File.begin(), File.end());
556 Buf.push_back('"');
557 Buf.push_back('\n');
558}
559
Reid Spencer5f016e22007-07-11 17:01:13 +0000560
Chris Lattner53b0dab2007-10-09 22:10:18 +0000561/// InitializePreprocessor - Initialize the preprocessor getting it and the
562/// environment ready to process a single file. This returns the file ID for the
563/// input file. If a failure happens, it returns 0.
564///
565static unsigned InitializePreprocessor(Preprocessor &PP,
566 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000567 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000568
Chris Lattnerdee73592007-12-15 20:48:40 +0000569 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000570
Chris Lattner53b0dab2007-10-09 22:10:18 +0000571 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000572 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000573 if (InFile != "-") {
574 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000575 if (File) SourceMgr.createMainFileID(File, SourceLocation());
576 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000577 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
578 return 0;
579 }
580 } else {
581 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000582 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
583 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000584 fprintf(stderr, "Error reading standard input! Empty?\n");
585 return 0;
586 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 }
588
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 // Add macros from the command line.
590 // FIXME: Should traverse the #define/#undef lists in parallel.
591 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000592 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000594 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
595
Chris Lattner64299f82008-01-10 01:53:41 +0000596 // FIXME: Read any files specified by -imacros.
597
598 // Add implicit #includes from -include.
599 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
600 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000601
602 // Null terminate PredefinedBuffer and add it.
603 PredefineBuffer.push_back(0);
604 PP.setPredefines(&PredefineBuffer[0]);
605
606 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000607 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000608}
609
610//===----------------------------------------------------------------------===//
611// Preprocessor include path information.
612//===----------------------------------------------------------------------===//
613
614// This tool exports a large number of command line options to control how the
615// preprocessor searches for header files. At root, however, the Preprocessor
616// object takes a very simple interface: a list of directories to search for
617//
618// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000619// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000620//
Chris Lattner64299f82008-01-10 01:53:41 +0000621// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000622
623static llvm::cl::opt<bool>
624nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
625
626// Various command line options. These four add directories to each chain.
627static llvm::cl::list<std::string>
628F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
629 llvm::cl::desc("Add directory to framework include search path"));
630static llvm::cl::list<std::string>
631I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
632 llvm::cl::desc("Add directory to include search path"));
633static llvm::cl::list<std::string>
634idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
635 llvm::cl::desc("Add directory to AFTER include search path"));
636static llvm::cl::list<std::string>
637iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
638 llvm::cl::desc("Add directory to QUOTE include search path"));
639static llvm::cl::list<std::string>
640isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
641 llvm::cl::desc("Add directory to SYSTEM include search path"));
642
643// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
644static llvm::cl::list<std::string>
645iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
646 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
647static llvm::cl::list<std::string>
648iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
649 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
650static llvm::cl::list<std::string>
651iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
652 llvm::cl::Prefix,
653 llvm::cl::desc("Set directory to include search path with prefix"));
654
Chris Lattner0c946412007-08-26 17:47:35 +0000655static llvm::cl::opt<std::string>
656isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
657 llvm::cl::desc("Set the system root directory (usually /)"));
658
Reid Spencer5f016e22007-07-11 17:01:13 +0000659// Finally, implement the code that groks the options above.
660enum IncludeDirGroup {
661 Quoted = 0,
662 Angled,
663 System,
664 After
665};
666
667static std::vector<DirectoryLookup> IncludeGroup[4];
668
669/// AddPath - Add the specified path to the specified group list.
670///
671static void AddPath(const std::string &Path, IncludeDirGroup Group,
672 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000673 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000674 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000675 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000676
Chris Lattnerd6655272007-12-17 05:59:27 +0000677 // Compute the actual path, taking into consideration -isysroot.
678 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000679
Chris Lattnerd6655272007-12-17 05:59:27 +0000680 // Handle isysroot.
681 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000682 // FIXME: Portability. This should be a sys::Path interface, this doesn't
683 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000684 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
685 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000686 }
687
Chris Lattnerd6655272007-12-17 05:59:27 +0000688 MappedPath.append(Path.begin(), Path.end());
689
690 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 DirectoryLookup::DirType Type;
692 if (Group == Quoted || Group == Angled)
693 Type = DirectoryLookup::NormalHeaderDir;
694 else if (isCXXAware)
695 Type = DirectoryLookup::SystemHeaderDir;
696 else
697 Type = DirectoryLookup::ExternCSystemHeaderDir;
698
Chris Lattnerd6655272007-12-17 05:59:27 +0000699
700 // If the directory exists, add it.
701 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
702 &MappedPath[0]+
703 MappedPath.size())) {
704 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
705 isFramework));
706 return;
707 }
708
Chris Lattnerdf772332007-12-17 07:52:39 +0000709 // Check to see if this is an apple-style headermap (which are not allowed to
710 // be frameworks).
711 if (!isFramework) {
712 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
713 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000714 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
715 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000716 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
717 return;
718 }
Chris Lattner822da612007-12-17 06:36:45 +0000719 }
720 }
721
Chris Lattnerd6655272007-12-17 05:59:27 +0000722 if (Verbose)
723 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000724}
725
726/// RemoveDuplicates - If there are duplicate directory entries in the specified
727/// search list, remove the later (dead) ones.
728static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000729 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000730 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000731 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000733 if (SearchList[i].isNormalDir()) {
734 // If this isn't the first time we've seen this dir, remove it.
735 if (SeenDirs.insert(SearchList[i].getDir()))
736 continue;
737
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 if (Verbose)
739 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
740 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000741 } else if (SearchList[i].isFramework()) {
742 // If this isn't the first time we've seen this framework dir, remove it.
743 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
744 continue;
745
746 if (Verbose)
747 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
748 SearchList[i].getFrameworkDir()->getName());
749
Chris Lattnerb94c7072007-12-17 06:44:29 +0000750 } else {
751 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
752 // If this isn't the first time we've seen this headermap, remove it.
753 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
754 continue;
755
756 if (Verbose)
757 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
758 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000760
761 // This is reached if the current entry is a duplicate.
762 SearchList.erase(SearchList.begin()+i);
763 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 }
765}
766
Chris Lattner5f9eae52008-03-01 08:07:28 +0000767// AddEnvVarPaths - Add a list of paths from an environment variable to a
768// header search list.
769//
770static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
771 const char* at = getenv(Name);
772 if (!at)
773 return;
774
775 const char* delim = strchr(at, llvm::sys::PathSeparator);
776 while (delim != 0) {
777 if (delim-at == 0)
778 AddPath(".", Angled, false, true, false, Headers);
779 else
780 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
781 true, false, Headers);
782 at = delim + 1;
783 delim = strchr(at, llvm::sys::PathSeparator);
784 }
785 if (*at == 0)
786 AddPath(".", Angled, false, true, false, Headers);
787 else
788 AddPath(at, Angled, false, true, false, Headers);
789}
790
Reid Spencer5f016e22007-07-11 17:01:13 +0000791/// InitializeIncludePaths - Process the -I options and set them in the
792/// HeaderSearch object.
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000793static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
794 FileManager &FM, const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000795 // Handle -F... options.
796 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000797 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000798
799 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000800 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000801 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000802
803 // Handle -idirafter... options.
804 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000805 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000806
807 // Handle -iquote... options.
808 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000809 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000810
811 // Handle -isystem... options.
812 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000813 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000814
815 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
816 // parallel, processing the values in order of occurance to get the right
817 // prefixes.
818 {
819 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
820 unsigned iprefix_idx = 0;
821 unsigned iwithprefix_idx = 0;
822 unsigned iwithprefixbefore_idx = 0;
823 bool iprefix_done = iprefix_vals.empty();
824 bool iwithprefix_done = iwithprefix_vals.empty();
825 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
826 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
827 if (!iprefix_done &&
828 (iwithprefix_done ||
829 iprefix_vals.getPosition(iprefix_idx) <
830 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
831 (iwithprefixbefore_done ||
832 iprefix_vals.getPosition(iprefix_idx) <
833 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
834 Prefix = iprefix_vals[iprefix_idx];
835 ++iprefix_idx;
836 iprefix_done = iprefix_idx == iprefix_vals.size();
837 } else if (!iwithprefix_done &&
838 (iwithprefixbefore_done ||
839 iwithprefix_vals.getPosition(iwithprefix_idx) <
840 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
841 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000842 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000843 ++iwithprefix_idx;
844 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
845 } else {
846 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000847 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000848 ++iwithprefixbefore_idx;
849 iwithprefixbefore_done =
850 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
851 }
852 }
853 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000854
855 AddEnvVarPaths("CPATH", Headers);
856 if (Lang.CPlusPlus && Lang.ObjC1)
857 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
858 else if (Lang.CPlusPlus)
859 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
860 else if (Lang.ObjC1)
861 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
862 else
863 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
864
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000865 // Add the clang headers, which are relative to the clang driver.
866 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000867 llvm::sys::Path::GetMainExecutable(Argv0,
868 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000869 if (!MainExecutablePath.isEmpty()) {
870 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
871 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
872 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
873 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
874 }
875
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 // FIXME: temporary hack: hard-coded paths.
877 // FIXME: get these from the target?
878 if (!nostdinc) {
879 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000880 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000882 false, Headers);
883 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
884 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000885
886 // Ubuntu 7.10 - Gutsy Gibbon
887 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
888 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
889 false, Headers);
890 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
891 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 }
893
Chris Lattner822da612007-12-17 06:36:45 +0000894 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 // leopard
896 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000897 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000899 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000900 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
901 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000902 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000903
904 // tiger
905 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000906 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000908 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
910 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000911 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000912
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000913 // Ubuntu 7.10 - Gutsy Gibbon
914 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +0000915 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000916
Chris Lattner822da612007-12-17 06:36:45 +0000917 AddPath("/usr/include", System, false, false, false, Headers);
918 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
919 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000920 }
921
922 // Now that we have collected all of the include paths, merge them all
923 // together and tell the preprocessor about them.
924
925 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
926 std::vector<DirectoryLookup> SearchList;
927 SearchList = IncludeGroup[Angled];
928 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
929 IncludeGroup[System].end());
930 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
931 IncludeGroup[After].end());
932 RemoveDuplicates(SearchList);
933 RemoveDuplicates(IncludeGroup[Quoted]);
934
935 // Prepend QUOTED list on the search list.
936 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
937 IncludeGroup[Quoted].end());
938
939
940 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
941 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
942 DontSearchCurDir);
943
944 // If verbose, print the list of directories that will be searched.
945 if (Verbose) {
946 fprintf(stderr, "#include \"...\" search starts here:\n");
947 unsigned QuotedIdx = IncludeGroup[Quoted].size();
948 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
949 if (i == QuotedIdx)
950 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000951 const char *Name = SearchList[i].getName();
952 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000953 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000954 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000955 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000956 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000957 else {
958 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000959 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000960 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000961 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000962 }
Chris Lattner80e17152007-12-15 23:11:06 +0000963 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 }
965}
966
967
Reid Spencer5f016e22007-07-11 17:01:13 +0000968//===----------------------------------------------------------------------===//
969// Basic Parser driver
970//===----------------------------------------------------------------------===//
971
Ted Kremenek95041a22007-12-19 22:51:13 +0000972static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000973 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000974 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000975
976 // Parsing the specified input file.
977 P.ParseTranslationUnit();
978 delete PA;
979}
980
981//===----------------------------------------------------------------------===//
982// Main driver
983//===----------------------------------------------------------------------===//
984
Ted Kremenekdb094a22007-12-05 18:27:04 +0000985/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
986/// action. These consumers can operate on both ASTs that are freshly
987/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000988static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000989 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +0000990 const LangOptions& LangOpts,
991 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +0000992 switch (ProgAction) {
993 default:
994 return NULL;
995
996 case ASTPrint:
997 return CreateASTPrinter();
998
999 case ASTDump:
1000 return CreateASTDumper();
1001
1002 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001003 return CreateASTViewer();
1004
1005 case EmitHTML:
1006 return CreateHTMLPrinter();
Ted Kremenekdb094a22007-12-05 18:27:04 +00001007
Ted Kremenek13e479b2008-03-19 07:53:42 +00001008 case HTMLTest:
1009 return CreateHTMLTest();
1010
Ted Kremenekdb094a22007-12-05 18:27:04 +00001011 case ParseCFGDump:
1012 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001013 return CreateCFGDumper(ProgAction == ParseCFGView,
1014 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001015
1016 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001017 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001018
1019 case WarnDeadStores:
1020 return CreateDeadStoreChecker(Diag);
1021
1022 case WarnUninitVals:
1023 return CreateUnitValsChecker(Diag);
1024
Ted Kremeneke01c9872008-02-14 22:36:46 +00001025 case AnalysisGRSimpleVals:
Ted Kremenekcb330932008-02-18 21:21:23 +00001026 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction);
Ted Kremeneke603df42008-01-08 18:04:06 +00001027
Ted Kremenekd55fe522008-02-15 00:35:38 +00001028 case AnalysisGRSimpleValsView:
Ted Kremenekffe0f432008-03-07 22:58:01 +00001029 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, true, TrimGraph);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001030
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001031 case CheckerCFRef:
1032 return CreateCFRefChecker(Diag, AnalyzeSpecificFunction);
1033
Ted Kremenekdb094a22007-12-05 18:27:04 +00001034 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001035 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001036
1037 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001038 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001039 DestModule = new llvm::Module(InFile);
1040 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001041
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001042 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001043 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001044 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001045
Ted Kremenekdb094a22007-12-05 18:27:04 +00001046 case RewriteTest:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001047 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001048 }
1049}
1050
Reid Spencer5f016e22007-07-11 17:01:13 +00001051/// ProcessInputFile - Process a single input file with the specified state.
1052///
Ted Kremenek7dcc9682007-12-19 22:32:34 +00001053static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +00001054 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001055
1056 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001057 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001058 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001059
Reid Spencer5f016e22007-07-11 17:01:13 +00001060 switch (ProgAction) {
1061 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001062 Consumer = CreateASTConsumer(InFile,
1063 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001064 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001065 PP.getLangOptions(),
1066 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001067
1068 if (!Consumer) {
1069 fprintf(stderr, "Unexpected program action!\n");
1070 return;
1071 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001072
Ted Kremenekdb094a22007-12-05 18:27:04 +00001073 break;
1074
Reid Spencer5f016e22007-07-11 17:01:13 +00001075 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001076 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001077 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001078 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001079 do {
1080 PP.Lex(Tok);
1081 PP.DumpToken(Tok, true);
1082 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001083 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001084 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001085 break;
1086 }
1087 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001088 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001090 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001091 do {
1092 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001093 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001094 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 break;
1096 }
1097
1098 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001099 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001100 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 break;
1102
1103 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001104 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001105 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 break;
1107
1108 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001109 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001110 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001112
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001113 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001114 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001115 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001116 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001117
1118 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001119 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001120 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001121
1122 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001123 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001125
1126 // If running the code generator, finish up now.
1127 if (CodeGenModule) {
1128 std::ostream *Out;
1129 if (OutputFile == "-") {
1130 Out = llvm::cout.stream();
1131 } else if (!OutputFile.empty()) {
1132 Out = new std::ofstream(OutputFile.c_str(),
1133 std::ios_base::binary|std::ios_base::out);
1134 } else if (InFile == "-") {
1135 Out = llvm::cout.stream();
1136 } else {
1137 llvm::sys::Path Path(InFile);
1138 Path.eraseSuffix();
1139 if (ProgAction == EmitLLVM)
1140 Path.appendSuffix("ll");
1141 else if (ProgAction == EmitBC)
1142 Path.appendSuffix("bc");
1143 else
1144 assert(0 && "Unknown action");
1145 Out = new std::ofstream(Path.toString().c_str(),
1146 std::ios_base::binary|std::ios_base::out);
1147 }
1148
1149 if (ProgAction == EmitLLVM) {
1150 CodeGenModule->print(*Out);
1151 } else {
1152 assert(ProgAction == EmitBC);
1153 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1154 }
1155
1156 if (Out != llvm::cout.stream())
1157 delete Out;
1158 delete CodeGenModule;
1159 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001160
1161 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001162 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001163 PP.PrintStats();
1164 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001165 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001166 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001167 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001168 fprintf(stderr, "\n");
1169 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001170
1171 // For a multi-file compilation, some things are ok with nuking the source
1172 // manager tables, other require stable fileid/macroid's across multiple
1173 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001174 if (ClearSourceMgr)
1175 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001176}
1177
Ted Kremenek20e97482007-12-12 23:41:08 +00001178static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1179 FileManager& FileMgr) {
1180
1181 if (VerifyDiagnostics) {
1182 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1183 exit (1);
1184 }
1185
1186 llvm::sys::Path Filename(InFile);
1187
1188 if (!Filename.isValid()) {
1189 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1190 exit (1);
1191 }
1192
Ted Kremenekee533642007-12-20 19:47:16 +00001193 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001194
1195 if (!TU) {
1196 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1197 InFile.c_str());
1198 exit (1);
1199 }
1200
Ted Kremenek63ea8632007-12-19 19:27:38 +00001201 // Observe that we use the source file name stored in the deserialized
1202 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001203 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001204 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001205 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1206 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001207
1208 if (!Consumer) {
1209 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1210 exit (1);
1211 }
1212
Ted Kremenek95041a22007-12-19 22:51:13 +00001213 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001214
Chris Lattnere66b65c2008-02-06 01:42:25 +00001215 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001216 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1217 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001218}
1219
1220
Reid Spencer5f016e22007-07-11 17:01:13 +00001221static llvm::cl::list<std::string>
1222InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1223
Ted Kremenek20e97482007-12-12 23:41:08 +00001224static bool isSerializedFile(const std::string& InFile) {
1225 if (InFile.size() < 4)
1226 return false;
1227
1228 const char* s = InFile.c_str()+InFile.size()-4;
1229
1230 return s[0] == '.' &&
1231 s[1] == 'a' &&
1232 s[2] == 's' &&
1233 s[3] == 't';
1234}
1235
Reid Spencer5f016e22007-07-11 17:01:13 +00001236
1237int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001238 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 llvm::sys::PrintStackTraceOnErrorSignal();
1240
1241 // If no input was specified, read from stdin.
1242 if (InputFilenames.empty())
1243 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001244
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 // Create a file manager object to provide access to and cache the filesystem.
1246 FileManager FileMgr;
1247
Ted Kremenek31e703b2007-12-11 23:28:38 +00001248 // Create the diagnostic client for reporting errors or for
1249 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001251 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001253 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 } else {
1255 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001256 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001257
1258 if (InputFilenames.size() != 1) {
1259 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001260 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 return 1;
1262 }
1263 }
1264
1265 // Configure our handling of diagnostics.
1266 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001267 InitializeDiagnostics(Diags);
1268
Chris Lattner4f037832007-12-05 23:24:17 +00001269 // -I- is a deprecated GCC feature, scan for it and reject it.
1270 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1271 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001272 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001273 I_dirs.erase(I_dirs.begin()+i);
1274 --i;
1275 }
1276 }
Chris Lattner11215192008-03-14 06:12:05 +00001277
1278 // Get information about the target being compiled for.
1279 std::string Triple = CreateTargetTriple();
1280 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1281 if (Target == 0) {
1282 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1283 Triple.c_str());
1284 fprintf(stderr, "Please use -triple or -arch.\n");
1285 exit(1);
1286 }
Chris Lattner4f037832007-12-05 23:24:17 +00001287
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001289 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001290
Ted Kremenek20e97482007-12-12 23:41:08 +00001291 if (isSerializedFile(InFile))
1292 ProcessSerializedFile(InFile,Diags,FileMgr);
1293 else {
1294 /// Create a SourceManager object. This tracks and owns all the file
1295 /// buffers allocated to a translation unit.
1296 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001297
Ted Kremenek20e97482007-12-12 23:41:08 +00001298 // Initialize language options, inferring file types from input filenames.
1299 LangOptions LangInfo;
1300 InitializeBaseLanguage();
1301 LangKind LK = GetLanguage(InFile);
1302 InitializeLangOptions(LangInfo, LK);
1303 InitializeLanguageStandard(LangInfo, LK);
1304
1305 // Process the -I options and set them in the HeaderInfo.
1306 HeaderSearch HeaderInfo(FileMgr);
1307 DiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001308 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001309
Ted Kremenek20e97482007-12-12 23:41:08 +00001310 // Set up the preprocessor with these options.
1311 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1312
1313 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001314 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001315 continue;
1316
Ted Kremenek1036b682007-12-19 23:48:45 +00001317 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001318 HeaderInfo.ClearFileInfo();
1319
1320 if (Stats)
1321 SourceMgr.PrintStats();
1322 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 }
1324
Chris Lattner11215192008-03-14 06:12:05 +00001325 delete Target;
1326
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1328
1329 if (NumDiagnostics)
1330 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1331 (NumDiagnostics == 1 ? "" : "s"));
1332
1333 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 FileMgr.PrintStats();
1335 fprintf(stderr, "\n");
1336 }
1337
Chris Lattner96f1a642007-07-21 05:40:53 +00001338 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001339}