blob: 50be86e9a044c74f2004892ea3e133e2ba9d444c [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
Andrew Lenharth92d56b72008-03-24 21:25:48 +0000917 //Debian testing/lenny x86
918 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
919 false, false, false, Headers);
920
921
Chris Lattner822da612007-12-17 06:36:45 +0000922 AddPath("/usr/include", System, false, false, false, Headers);
923 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
924 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 }
926
927 // Now that we have collected all of the include paths, merge them all
928 // together and tell the preprocessor about them.
929
930 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
931 std::vector<DirectoryLookup> SearchList;
932 SearchList = IncludeGroup[Angled];
933 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
934 IncludeGroup[System].end());
935 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
936 IncludeGroup[After].end());
937 RemoveDuplicates(SearchList);
938 RemoveDuplicates(IncludeGroup[Quoted]);
939
940 // Prepend QUOTED list on the search list.
941 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
942 IncludeGroup[Quoted].end());
943
944
945 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
946 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
947 DontSearchCurDir);
948
949 // If verbose, print the list of directories that will be searched.
950 if (Verbose) {
951 fprintf(stderr, "#include \"...\" search starts here:\n");
952 unsigned QuotedIdx = IncludeGroup[Quoted].size();
953 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
954 if (i == QuotedIdx)
955 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000956 const char *Name = SearchList[i].getName();
957 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000958 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000959 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000960 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000961 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000962 else {
963 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000964 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000965 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000966 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000967 }
Chris Lattner80e17152007-12-15 23:11:06 +0000968 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000969 }
970}
971
972
Reid Spencer5f016e22007-07-11 17:01:13 +0000973//===----------------------------------------------------------------------===//
974// Basic Parser driver
975//===----------------------------------------------------------------------===//
976
Ted Kremenek95041a22007-12-19 22:51:13 +0000977static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000979 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000980
981 // Parsing the specified input file.
982 P.ParseTranslationUnit();
983 delete PA;
984}
985
986//===----------------------------------------------------------------------===//
987// Main driver
988//===----------------------------------------------------------------------===//
989
Ted Kremenekdb094a22007-12-05 18:27:04 +0000990/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
991/// action. These consumers can operate on both ASTs that are freshly
992/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000993static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000994 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +0000995 const LangOptions& LangOpts,
996 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +0000997 switch (ProgAction) {
998 default:
999 return NULL;
1000
1001 case ASTPrint:
1002 return CreateASTPrinter();
1003
1004 case ASTDump:
1005 return CreateASTDumper();
1006
1007 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001008 return CreateASTViewer();
1009
1010 case EmitHTML:
1011 return CreateHTMLPrinter();
Ted Kremenekdb094a22007-12-05 18:27:04 +00001012
Ted Kremenek13e479b2008-03-19 07:53:42 +00001013 case HTMLTest:
1014 return CreateHTMLTest();
1015
Ted Kremenekdb094a22007-12-05 18:27:04 +00001016 case ParseCFGDump:
1017 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001018 return CreateCFGDumper(ProgAction == ParseCFGView,
1019 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001020
1021 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001022 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001023
1024 case WarnDeadStores:
1025 return CreateDeadStoreChecker(Diag);
1026
1027 case WarnUninitVals:
1028 return CreateUnitValsChecker(Diag);
1029
Ted Kremeneke01c9872008-02-14 22:36:46 +00001030 case AnalysisGRSimpleVals:
Ted Kremenekcb330932008-02-18 21:21:23 +00001031 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction);
Ted Kremeneke603df42008-01-08 18:04:06 +00001032
Ted Kremenekd55fe522008-02-15 00:35:38 +00001033 case AnalysisGRSimpleValsView:
Ted Kremenekffe0f432008-03-07 22:58:01 +00001034 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, true, TrimGraph);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001035
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001036 case CheckerCFRef:
1037 return CreateCFRefChecker(Diag, AnalyzeSpecificFunction);
1038
Ted Kremenekdb094a22007-12-05 18:27:04 +00001039 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001040 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001041
1042 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001043 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001044 DestModule = new llvm::Module(InFile);
1045 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001046
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001047 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001048 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001049 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001050
Ted Kremenekdb094a22007-12-05 18:27:04 +00001051 case RewriteTest:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001052 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001053 }
1054}
1055
Reid Spencer5f016e22007-07-11 17:01:13 +00001056/// ProcessInputFile - Process a single input file with the specified state.
1057///
Ted Kremenek7dcc9682007-12-19 22:32:34 +00001058static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +00001059 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001060
1061 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001062 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001063 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001064
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 switch (ProgAction) {
1066 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001067 Consumer = CreateASTConsumer(InFile,
1068 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001069 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001070 PP.getLangOptions(),
1071 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001072
1073 if (!Consumer) {
1074 fprintf(stderr, "Unexpected program action!\n");
1075 return;
1076 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001077
Ted Kremenekdb094a22007-12-05 18:27:04 +00001078 break;
1079
Reid Spencer5f016e22007-07-11 17:01:13 +00001080 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001081 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001083 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001084 do {
1085 PP.Lex(Tok);
1086 PP.DumpToken(Tok, true);
1087 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001088 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001089 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 break;
1091 }
1092 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001093 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001095 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001096 do {
1097 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001098 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001099 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 break;
1101 }
1102
1103 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001104 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001105 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 break;
1107
1108 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001109 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001110 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 break;
1112
1113 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001114 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001115 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001116 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001117
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001118 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001119 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001120 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001121 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001122
1123 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001124 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001125 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001126
1127 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001128 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001130
1131 // If running the code generator, finish up now.
1132 if (CodeGenModule) {
1133 std::ostream *Out;
1134 if (OutputFile == "-") {
1135 Out = llvm::cout.stream();
1136 } else if (!OutputFile.empty()) {
1137 Out = new std::ofstream(OutputFile.c_str(),
1138 std::ios_base::binary|std::ios_base::out);
1139 } else if (InFile == "-") {
1140 Out = llvm::cout.stream();
1141 } else {
1142 llvm::sys::Path Path(InFile);
1143 Path.eraseSuffix();
1144 if (ProgAction == EmitLLVM)
1145 Path.appendSuffix("ll");
1146 else if (ProgAction == EmitBC)
1147 Path.appendSuffix("bc");
1148 else
1149 assert(0 && "Unknown action");
1150 Out = new std::ofstream(Path.toString().c_str(),
1151 std::ios_base::binary|std::ios_base::out);
1152 }
1153
1154 if (ProgAction == EmitLLVM) {
1155 CodeGenModule->print(*Out);
1156 } else {
1157 assert(ProgAction == EmitBC);
1158 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1159 }
1160
1161 if (Out != llvm::cout.stream())
1162 delete Out;
1163 delete CodeGenModule;
1164 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001165
1166 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001167 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001168 PP.PrintStats();
1169 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001170 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001171 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001172 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001173 fprintf(stderr, "\n");
1174 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001175
1176 // For a multi-file compilation, some things are ok with nuking the source
1177 // manager tables, other require stable fileid/macroid's across multiple
1178 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001179 if (ClearSourceMgr)
1180 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001181}
1182
Ted Kremenek20e97482007-12-12 23:41:08 +00001183static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1184 FileManager& FileMgr) {
1185
1186 if (VerifyDiagnostics) {
1187 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1188 exit (1);
1189 }
1190
1191 llvm::sys::Path Filename(InFile);
1192
1193 if (!Filename.isValid()) {
1194 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1195 exit (1);
1196 }
1197
Ted Kremenekee533642007-12-20 19:47:16 +00001198 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001199
1200 if (!TU) {
1201 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1202 InFile.c_str());
1203 exit (1);
1204 }
1205
Ted Kremenek63ea8632007-12-19 19:27:38 +00001206 // Observe that we use the source file name stored in the deserialized
1207 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001208 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001209 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001210 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1211 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001212
1213 if (!Consumer) {
1214 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1215 exit (1);
1216 }
1217
Ted Kremenek95041a22007-12-19 22:51:13 +00001218 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001219
Chris Lattnere66b65c2008-02-06 01:42:25 +00001220 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001221 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1222 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001223}
1224
1225
Reid Spencer5f016e22007-07-11 17:01:13 +00001226static llvm::cl::list<std::string>
1227InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1228
Ted Kremenek20e97482007-12-12 23:41:08 +00001229static bool isSerializedFile(const std::string& InFile) {
1230 if (InFile.size() < 4)
1231 return false;
1232
1233 const char* s = InFile.c_str()+InFile.size()-4;
1234
1235 return s[0] == '.' &&
1236 s[1] == 'a' &&
1237 s[2] == 's' &&
1238 s[3] == 't';
1239}
1240
Reid Spencer5f016e22007-07-11 17:01:13 +00001241
1242int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001243 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 llvm::sys::PrintStackTraceOnErrorSignal();
1245
1246 // If no input was specified, read from stdin.
1247 if (InputFilenames.empty())
1248 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001249
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 // Create a file manager object to provide access to and cache the filesystem.
1251 FileManager FileMgr;
1252
Ted Kremenek31e703b2007-12-11 23:28:38 +00001253 // Create the diagnostic client for reporting errors or for
1254 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001256 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001258 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 } else {
1260 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001261 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001262
1263 if (InputFilenames.size() != 1) {
1264 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001265 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 return 1;
1267 }
1268 }
1269
1270 // Configure our handling of diagnostics.
1271 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001272 InitializeDiagnostics(Diags);
1273
Chris Lattner4f037832007-12-05 23:24:17 +00001274 // -I- is a deprecated GCC feature, scan for it and reject it.
1275 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1276 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001277 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001278 I_dirs.erase(I_dirs.begin()+i);
1279 --i;
1280 }
1281 }
Chris Lattner11215192008-03-14 06:12:05 +00001282
1283 // Get information about the target being compiled for.
1284 std::string Triple = CreateTargetTriple();
1285 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1286 if (Target == 0) {
1287 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1288 Triple.c_str());
1289 fprintf(stderr, "Please use -triple or -arch.\n");
1290 exit(1);
1291 }
Chris Lattner4f037832007-12-05 23:24:17 +00001292
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001294 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001295
Ted Kremenek20e97482007-12-12 23:41:08 +00001296 if (isSerializedFile(InFile))
1297 ProcessSerializedFile(InFile,Diags,FileMgr);
1298 else {
1299 /// Create a SourceManager object. This tracks and owns all the file
1300 /// buffers allocated to a translation unit.
1301 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001302
Ted Kremenek20e97482007-12-12 23:41:08 +00001303 // Initialize language options, inferring file types from input filenames.
1304 LangOptions LangInfo;
1305 InitializeBaseLanguage();
1306 LangKind LK = GetLanguage(InFile);
1307 InitializeLangOptions(LangInfo, LK);
1308 InitializeLanguageStandard(LangInfo, LK);
1309
1310 // Process the -I options and set them in the HeaderInfo.
1311 HeaderSearch HeaderInfo(FileMgr);
1312 DiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001313 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001314
Ted Kremenek20e97482007-12-12 23:41:08 +00001315 // Set up the preprocessor with these options.
1316 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1317
1318 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001319 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001320 continue;
1321
Ted Kremenek1036b682007-12-19 23:48:45 +00001322 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001323 HeaderInfo.ClearFileInfo();
1324
1325 if (Stats)
1326 SourceMgr.PrintStats();
1327 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 }
1329
Chris Lattner11215192008-03-14 06:12:05 +00001330 delete Target;
1331
Reid Spencer5f016e22007-07-11 17:01:13 +00001332 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1333
1334 if (NumDiagnostics)
1335 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1336 (NumDiagnostics == 1 ? "" : "s"));
1337
1338 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 FileMgr.PrintStats();
1340 fprintf(stderr, "\n");
1341 }
1342
Chris Lattner96f1a642007-07-21 05:40:53 +00001343 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001344}