blob: 216e669ccca9bacd6d4b65379f3553ab2da3620c [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenekac881932007-12-18 21:34:28 +000029#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000030#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000031#include "clang/Sema/ParseAST.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000032#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner8d72ee02008-02-06 01:42:25 +000038#include "llvm/Module.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner8d72ee02008-02-06 01:42:25 +000040#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner4b009652007-07-25 00:24:17 +000041#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/System/Signals.h"
Ted Kremenek40499482007-12-03 22:06:55 +000044#include "llvm/Config/config.h"
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +000045#include "llvm/ADT/OwningPtr.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000046#include "llvm/System/Path.h"
Chris Lattner4b009652007-07-25 00:24:17 +000047#include <memory>
Chris Lattner8d72ee02008-02-06 01:42:25 +000048#include <fstream>
Chris Lattner4b009652007-07-25 00:24:17 +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 Begeman6acbedd2007-12-30 01:38:50 +000058Stats("print-stats",
59 llvm::cl::desc("Print performance metrics and statistics"));
Chris Lattner4b009652007-07-25 00:24:17 +000060
61enum ProgActions {
Chris Lattnerb429ae42007-10-11 00:43:27 +000062 RewriteTest, // Rewriter testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000063 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000064 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000065 SerializeAST, // Emit a .ast file.
Chris Lattner4045a8a2007-10-11 00:18:28 +000066 ASTPrint, // Parse ASTs and print them.
67 ASTDump, // Parse ASTs and dump them.
68 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenek97f75312007-08-21 21:42:03 +000069 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000070 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremenekaa04c512007-09-06 00:17:54 +000071 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek1da5b142008-02-15 00:35:38 +000072 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
73 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek827f93b2008-03-06 00:08:09 +000074 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000075 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek0841c702007-09-25 18:37:20 +000076 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek0a03ce62007-09-17 20:49:30 +000077 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000078 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000079 ParsePrintCallbacks, // Parse and print each callback.
80 ParseSyntaxOnly, // Parse and perform semantic analysis.
81 ParseNoop, // Parse with noop callbacks.
82 RunPreprocessorOnly, // Just lex, no output.
83 PrintPreprocessedInput, // -E mode.
84 DumpTokens // Token dump mode.
85};
86
87static llvm::cl::opt<ProgActions>
88ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
89 llvm::cl::init(ParseSyntaxOnly),
90 llvm::cl::values(
91 clEnumValN(RunPreprocessorOnly, "Eonly",
92 "Just run preprocessor, no output (for timings)"),
93 clEnumValN(PrintPreprocessedInput, "E",
94 "Run preprocessor, emit preprocessed file"),
95 clEnumValN(DumpTokens, "dumptokens",
96 "Run preprocessor, dump internal rep of tokens"),
97 clEnumValN(ParseNoop, "parse-noop",
98 "Run parser with noop callbacks (for timings)"),
99 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
100 "Run parser and perform semantic analysis"),
101 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
102 "Run parser and print each callback invoked"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000103 clEnumValN(ASTPrint, "ast-print",
104 "Build ASTs and then pretty-print them"),
105 clEnumValN(ASTDump, "ast-dump",
106 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000107 clEnumValN(ASTView, "ast-view",
Chris Lattner4045a8a2007-10-11 00:18:28 +0000108 "Build ASTs and view them with GraphViz."),
Ted Kremenek97f75312007-08-21 21:42:03 +0000109 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000110 "Run parser, then build and print CFGs."),
111 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremenekaa04c512007-09-06 00:17:54 +0000112 "Run parser, then build and view CFGs with Graphviz."),
113 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek05334682007-09-06 21:26:58 +0000114 "Print results of live variable analysis."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000115 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremeneke805c4a2007-09-06 23:00:42 +0000116 "Flag warnings of stores to dead variables."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000117 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000118 "Flag warnings of uses of unitialized variables."),
Ted Kremenek3862eb12008-02-14 22:36:46 +0000119 clEnumValN(AnalysisGRSimpleVals, "grsimple",
Chris Lattner2528b5e2008-01-10 01:41:55 +0000120 "Perform path-sensitive constant propagation."),
Ted Kremenek1da5b142008-02-15 00:35:38 +0000121 clEnumValN(AnalysisGRSimpleValsView, "grsimple-view",
122 "View results of path-sensitive constant propagation."),
Ted Kremenek827f93b2008-03-06 00:08:09 +0000123 clEnumValN(CheckerCFRef, "check-cfref",
124 "Run the Core Foundation reference count checker."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000125 clEnumValN(TestSerialization, "test-pickling",
126 "Run prototype serializtion code."),
Chris Lattner4b009652007-07-25 00:24:17 +0000127 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000128 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000129 clEnumValN(EmitBC, "emit-llvm-bc",
130 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000131 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000132 "Build ASTs and emit .ast file"),
Chris Lattnerb429ae42007-10-11 00:43:27 +0000133 clEnumValN(RewriteTest, "rewrite-test",
134 "Playground for the code rewriter"),
Chris Lattner4b009652007-07-25 00:24:17 +0000135 clEnumValEnd));
136
Ted Kremenekd01eae62007-12-19 19:47:59 +0000137
138static llvm::cl::opt<std::string>
139OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000140 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000141 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
142
Ted Kremenek10389cf2007-09-26 19:42:19 +0000143static llvm::cl::opt<bool>
144VerifyDiagnostics("verify",
145 llvm::cl::desc("Verify emitted diagnostics and warnings."));
146
Chris Lattner4b009652007-07-25 00:24:17 +0000147//===----------------------------------------------------------------------===//
148// Language Options
149//===----------------------------------------------------------------------===//
150
151enum LangKind {
152 langkind_unspecified,
153 langkind_c,
154 langkind_c_cpp,
155 langkind_cxx,
156 langkind_cxx_cpp,
157 langkind_objc,
158 langkind_objc_cpp,
159 langkind_objcxx,
160 langkind_objcxx_cpp
161};
162
163/* TODO: GCC also accepts:
164 c-header c++-header objective-c-header objective-c++-header
165 assembler assembler-with-cpp
166 ada, f77*, ratfor (!), f95, java, treelang
167 */
168static llvm::cl::opt<LangKind>
169BaseLang("x", llvm::cl::desc("Base language to compile"),
170 llvm::cl::init(langkind_unspecified),
171 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
172 clEnumValN(langkind_cxx, "c++", "C++"),
173 clEnumValN(langkind_objc, "objective-c", "Objective C"),
174 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
175 clEnumValN(langkind_c_cpp, "c-cpp-output",
176 "Preprocessed C"),
177 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
178 "Preprocessed C++"),
179 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
180 "Preprocessed Objective C"),
181 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
182 "Preprocessed Objective C++"),
183 clEnumValEnd));
184
185static llvm::cl::opt<bool>
186LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
187 llvm::cl::Hidden);
188static llvm::cl::opt<bool>
189LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
190 llvm::cl::Hidden);
191
Ted Kremenek11ad8952007-12-05 23:49:08 +0000192/// InitializeBaseLanguage - Handle the -x foo options.
193static void InitializeBaseLanguage() {
194 if (LangObjC)
195 BaseLang = langkind_objc;
196 else if (LangObjCXX)
197 BaseLang = langkind_objcxx;
198}
199
200static LangKind GetLanguage(const std::string &Filename) {
201 if (BaseLang != langkind_unspecified)
202 return BaseLang;
203
204 std::string::size_type DotPos = Filename.rfind('.');
205
206 if (DotPos == std::string::npos) {
207 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000208 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000209 }
210
Ted Kremenek11ad8952007-12-05 23:49:08 +0000211 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
212 // C header: .h
213 // C++ header: .hh or .H;
214 // assembler no preprocessing: .s
215 // assembler: .S
216 if (Ext == "c")
217 return langkind_c;
218 else if (Ext == "i")
219 return langkind_c_cpp;
220 else if (Ext == "ii")
221 return langkind_cxx_cpp;
222 else if (Ext == "m")
223 return langkind_objc;
224 else if (Ext == "mi")
225 return langkind_objc_cpp;
226 else if (Ext == "mm" || Ext == "M")
227 return langkind_objcxx;
228 else if (Ext == "mii")
229 return langkind_objcxx_cpp;
230 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
231 Ext == "c++" || Ext == "cp" || Ext == "cxx")
232 return langkind_cxx;
233 else
234 return langkind_c;
235}
236
237
238static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000239 // FIXME: implement -fpreprocessed mode.
240 bool NoPreprocess = false;
241
Ted Kremenek11ad8952007-12-05 23:49:08 +0000242 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000243 default: assert(0 && "Unknown language kind!");
244 case langkind_c_cpp:
245 NoPreprocess = true;
246 // FALLTHROUGH
247 case langkind_c:
248 break;
249 case langkind_cxx_cpp:
250 NoPreprocess = true;
251 // FALLTHROUGH
252 case langkind_cxx:
253 Options.CPlusPlus = 1;
254 break;
255 case langkind_objc_cpp:
256 NoPreprocess = true;
257 // FALLTHROUGH
258 case langkind_objc:
259 Options.ObjC1 = Options.ObjC2 = 1;
260 break;
261 case langkind_objcxx_cpp:
262 NoPreprocess = true;
263 // FALLTHROUGH
264 case langkind_objcxx:
265 Options.ObjC1 = Options.ObjC2 = 1;
266 Options.CPlusPlus = 1;
267 break;
268 }
269}
270
271/// LangStds - Language standards we support.
272enum LangStds {
273 lang_unspecified,
274 lang_c89, lang_c94, lang_c99,
275 lang_gnu89, lang_gnu99,
276 lang_cxx98, lang_gnucxx98,
277 lang_cxx0x, lang_gnucxx0x
278};
279
280static llvm::cl::opt<LangStds>
281LangStd("std", llvm::cl::desc("Language standard to compile for"),
282 llvm::cl::init(lang_unspecified),
283 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
284 clEnumValN(lang_c89, "c90", "ISO C 1990"),
285 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
286 clEnumValN(lang_c94, "iso9899:199409",
287 "ISO C 1990 with amendment 1"),
288 clEnumValN(lang_c99, "c99", "ISO C 1999"),
289// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
290 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
291// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
292 clEnumValN(lang_gnu89, "gnu89",
293 "ISO C 1990 with GNU extensions (default for C)"),
294 clEnumValN(lang_gnu99, "gnu99",
295 "ISO C 1999 with GNU extensions"),
296 clEnumValN(lang_gnu99, "gnu9x",
297 "ISO C 1999 with GNU extensions"),
298 clEnumValN(lang_cxx98, "c++98",
299 "ISO C++ 1998 with amendments"),
300 clEnumValN(lang_gnucxx98, "gnu++98",
301 "ISO C++ 1998 with amendments and GNU "
302 "extensions (default for C++)"),
303 clEnumValN(lang_cxx0x, "c++0x",
304 "Upcoming ISO C++ 200x with amendments"),
305 clEnumValN(lang_gnucxx0x, "gnu++0x",
306 "Upcoming ISO C++ 200x with amendments and GNU "
307 "extensions (default for C++)"),
308 clEnumValEnd));
309
310static llvm::cl::opt<bool>
311NoOperatorNames("fno-operator-names",
312 llvm::cl::desc("Do not treat C++ operator name keywords as "
313 "synonyms for operators"));
314
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000315static llvm::cl::opt<bool>
316PascalStrings("fpascal-strings",
317 llvm::cl::desc("Recognize and construct Pascal-style "
318 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000319
320static llvm::cl::opt<bool>
321MSExtensions("fms-extensions",
322 llvm::cl::desc("Accept some non-standard constructs used in "
323 "Microsoft header files. "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000324
325static llvm::cl::opt<bool>
326WritableStrings("fwritable-strings",
327 llvm::cl::desc("Store string literals as writable data."));
Anders Carlssone87cd982007-11-30 04:21:22 +0000328
329static llvm::cl::opt<bool>
330LaxVectorConversions("flax-vector-conversions",
331 llvm::cl::desc("Allow implicit conversions between vectors"
332 " with a different number of elements or "
333 "different element types."));
Chris Lattner4b009652007-07-25 00:24:17 +0000334// FIXME: add:
335// -ansi
336// -trigraphs
337// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000338// -fpascal-strings
Ted Kremenek11ad8952007-12-05 23:49:08 +0000339static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000340 if (LangStd == lang_unspecified) {
341 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000342 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000343 default: assert(0 && "Unknown base language");
344 case langkind_c:
345 case langkind_c_cpp:
346 case langkind_objc:
347 case langkind_objc_cpp:
348 LangStd = lang_gnu99;
349 break;
350 case langkind_cxx:
351 case langkind_cxx_cpp:
352 case langkind_objcxx:
353 case langkind_objcxx_cpp:
354 LangStd = lang_gnucxx98;
355 break;
356 }
357 }
358
359 switch (LangStd) {
360 default: assert(0 && "Unknown language standard!");
361
362 // Fall through from newer standards to older ones. This isn't really right.
363 // FIXME: Enable specifically the right features based on the language stds.
364 case lang_gnucxx0x:
365 case lang_cxx0x:
366 Options.CPlusPlus0x = 1;
367 // FALL THROUGH
368 case lang_gnucxx98:
369 case lang_cxx98:
370 Options.CPlusPlus = 1;
371 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000372 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000373 // FALL THROUGH.
374 case lang_gnu99:
375 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000376 Options.C99 = 1;
377 Options.HexFloats = 1;
378 // FALL THROUGH.
379 case lang_gnu89:
380 Options.BCPLComment = 1; // Only for C99/C++.
381 // FALL THROUGH.
382 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000383 Options.Digraphs = 1; // C94, C99, C++.
384 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000385 case lang_c89:
386 break;
387 }
388
389 Options.Trigraphs = 1; // -trigraphs or -ansi
390 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000391 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000392 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000393 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000394 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000395}
396
397//===----------------------------------------------------------------------===//
398// Our DiagnosticClient implementation
399//===----------------------------------------------------------------------===//
400
401// FIXME: Werror should take a list of things, -Werror=foo,bar
402static llvm::cl::opt<bool>
403WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
404
405static llvm::cl::opt<bool>
406WarnOnExtensions("pedantic", llvm::cl::init(false),
407 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
408
409static llvm::cl::opt<bool>
410ErrorOnExtensions("pedantic-errors",
411 llvm::cl::desc("Issue an error on uses of GCC extensions"));
412
413static llvm::cl::opt<bool>
414WarnUnusedMacros("Wunused_macros",
415 llvm::cl::desc("Warn for unused macros in the main translation unit"));
416
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000417static llvm::cl::opt<bool>
418WarnFloatEqual("Wfloat-equal",
419 llvm::cl::desc("Warn about equality comparisons of floating point values."));
420
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000421static llvm::cl::opt<bool>
422WarnNoFormatNonLiteral("Wno-format-nonliteral",
423 llvm::cl::desc("Do not warn about non-literal format strings."));
424
Chris Lattnera616ee32008-01-23 17:19:46 +0000425static llvm::cl::opt<bool>
426WarnUndefMacros("Wundef",
427 llvm::cl::desc("Warn on use of undefined macros in #if's"));
428
429
Chris Lattner4b009652007-07-25 00:24:17 +0000430/// InitializeDiagnostics - Initialize the diagnostic object, based on the
431/// current command line option settings.
432static void InitializeDiagnostics(Diagnostic &Diags) {
433 Diags.setWarningsAsErrors(WarningsAsErrors);
434 Diags.setWarnOnExtensions(WarnOnExtensions);
435 Diags.setErrorOnExtensions(ErrorOnExtensions);
436
437 // Silence the "macro is not used" warning unless requested.
438 if (!WarnUnusedMacros)
439 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000440
441 // Silence "floating point comparison" warnings unless requested.
442 if (!WarnFloatEqual)
443 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000444
445 // Silence "format string is not a string literal" warnings if requested
446 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000447 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
448 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000449 if (!WarnUndefMacros)
450 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000451
452 if (MSExtensions) // MS allows unnamed struct/union fields.
453 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner4b009652007-07-25 00:24:17 +0000454}
455
456//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000457// Analysis-specific options.
458//===----------------------------------------------------------------------===//
459
460static llvm::cl::opt<std::string>
461AnalyzeSpecificFunction("analyze-function",
462 llvm::cl::desc("Run analysis on specific function."));
463
464//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000465// Target Triple Processing.
466//===----------------------------------------------------------------------===//
467
468static llvm::cl::opt<std::string>
469TargetTriple("triple",
470 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
471
Chris Lattnerfc457002008-03-05 01:18:20 +0000472static llvm::cl::opt<std::string>
Ted Kremenek40499482007-12-03 22:06:55 +0000473Archs("arch",
474 llvm::cl::desc("Specify target architecture (e.g. i686)."));
475
476namespace {
477 class TripleProcessor {
478 llvm::StringMap<char> TriplesProcessed;
479 std::vector<std::string>& triples;
480 public:
481 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
482
483 void addTriple(const std::string& t) {
484 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
485 TriplesProcessed.end()) {
486 triples.push_back(t);
487 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
488 }
489 }
490 };
491}
492
493static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenek40499482007-12-03 22:06:55 +0000494 // Initialize base triple. If a -triple option has been specified, use
495 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000496 std::string Triple = TargetTriple;
497 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000498
499 // Decompose the base triple into "arch" and suffix.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000500 std::string::size_type firstDash = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000501
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000502 if (firstDash == std::string::npos) {
503 fprintf(stderr,
504 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner210c0cc2007-12-12 05:01:48 +0000505 Triple.c_str());
506 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000507 }
Ted Kremenek40499482007-12-03 22:06:55 +0000508
Chris Lattner210c0cc2007-12-12 05:01:48 +0000509 std::string suffix(Triple, firstDash+1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000510
511 if (suffix.empty()) {
Chris Lattner210c0cc2007-12-12 05:01:48 +0000512 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
513 Triple.c_str());
514 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000515 }
Ted Kremenek40499482007-12-03 22:06:55 +0000516
517 // Create triple cacher.
518 TripleProcessor tp(triples);
519
520 // Add the primary triple to our set of triples if we are using the
521 // host-triple with no archs or using a specified target triple.
522 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner210c0cc2007-12-12 05:01:48 +0000523 tp.addTriple(Triple);
Chris Lattnerfc457002008-03-05 01:18:20 +0000524
525 if (!Archs.empty())
526 tp.addTriple(Archs + "-" + suffix);
Ted Kremenek40499482007-12-03 22:06:55 +0000527}
528
529//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000530// Preprocessor Initialization
531//===----------------------------------------------------------------------===//
532
533// FIXME: Preprocessor builtins to support.
534// -A... - Play with #assertions
535// -undef - Undefine all predefined macros
536
537static llvm::cl::list<std::string>
538D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
539 llvm::cl::desc("Predefine the specified macro"));
540static llvm::cl::list<std::string>
541U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
542 llvm::cl::desc("Undefine the specified macro"));
543
Chris Lattner008da782008-01-10 01:53:41 +0000544static llvm::cl::list<std::string>
545ImplicitIncludes("include", llvm::cl::value_desc("file"),
546 llvm::cl::desc("Include file before parsing"));
547
548
Chris Lattner4b009652007-07-25 00:24:17 +0000549// Append a #define line to Buf for Macro. Macro should be of the form XXX,
550// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
551// "#define XXX Y z W". To get a #define with no value, use "XXX=".
552static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
553 const char *Command = "#define ") {
554 Buf.insert(Buf.end(), Command, Command+strlen(Command));
555 if (const char *Equal = strchr(Macro, '=')) {
556 // Turn the = into ' '.
557 Buf.insert(Buf.end(), Macro, Equal);
558 Buf.push_back(' ');
559 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
560 } else {
561 // Push "macroname 1".
562 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
563 Buf.push_back(' ');
564 Buf.push_back('1');
565 }
566 Buf.push_back('\n');
567}
568
Chris Lattner008da782008-01-10 01:53:41 +0000569/// AddImplicitInclude - Add an implicit #include of the specified file to the
570/// predefines buffer.
571static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
572 const char *Inc = "#include \"";
573 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
574 Buf.insert(Buf.end(), File.begin(), File.end());
575 Buf.push_back('"');
576 Buf.push_back('\n');
577}
578
Chris Lattner4b009652007-07-25 00:24:17 +0000579
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000580/// InitializePreprocessor - Initialize the preprocessor getting it and the
581/// environment ready to process a single file. This returns the file ID for the
582/// input file. If a failure happens, it returns 0.
583///
584static unsigned InitializePreprocessor(Preprocessor &PP,
585 const std::string &InFile,
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000586 std::vector<char> &PredefineBuffer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000587
Chris Lattner968982d2007-12-15 20:48:40 +0000588 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000589
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000590 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000591 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000592 if (InFile != "-") {
593 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +0000594 if (File) SourceMgr.createMainFileID(File, SourceLocation());
595 if (SourceMgr.getMainFileID() == 0) {
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000596 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
597 return 0;
598 }
599 } else {
600 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +0000601 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
602 if (SourceMgr.getMainFileID() == 0) {
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000603 fprintf(stderr, "Error reading standard input! Empty?\n");
604 return 0;
605 }
Chris Lattner4b009652007-07-25 00:24:17 +0000606 }
607
Chris Lattner4b009652007-07-25 00:24:17 +0000608 // Add macros from the command line.
609 // FIXME: Should traverse the #define/#undef lists in parallel.
610 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000611 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000612 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000613 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
614
Chris Lattner008da782008-01-10 01:53:41 +0000615 // FIXME: Read any files specified by -imacros.
616
617 // Add implicit #includes from -include.
618 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
619 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000620
621 // Null terminate PredefinedBuffer and add it.
622 PredefineBuffer.push_back(0);
623 PP.setPredefines(&PredefineBuffer[0]);
624
625 // Once we've read this, we're done.
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +0000626 return SourceMgr.getMainFileID();
Chris Lattner4b009652007-07-25 00:24:17 +0000627}
628
629//===----------------------------------------------------------------------===//
630// Preprocessor include path information.
631//===----------------------------------------------------------------------===//
632
633// This tool exports a large number of command line options to control how the
634// preprocessor searches for header files. At root, however, the Preprocessor
635// object takes a very simple interface: a list of directories to search for
636//
637// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000638// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000639//
Chris Lattner008da782008-01-10 01:53:41 +0000640// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000641
642static llvm::cl::opt<bool>
643nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
644
645// Various command line options. These four add directories to each chain.
646static llvm::cl::list<std::string>
647F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
648 llvm::cl::desc("Add directory to framework include search path"));
649static llvm::cl::list<std::string>
650I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
651 llvm::cl::desc("Add directory to include search path"));
652static llvm::cl::list<std::string>
653idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
654 llvm::cl::desc("Add directory to AFTER include search path"));
655static llvm::cl::list<std::string>
656iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
657 llvm::cl::desc("Add directory to QUOTE include search path"));
658static llvm::cl::list<std::string>
659isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
660 llvm::cl::desc("Add directory to SYSTEM include search path"));
661
662// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
663static llvm::cl::list<std::string>
664iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
665 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
666static llvm::cl::list<std::string>
667iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
668 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
669static llvm::cl::list<std::string>
670iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
671 llvm::cl::Prefix,
672 llvm::cl::desc("Set directory to include search path with prefix"));
673
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000674static llvm::cl::opt<std::string>
675isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
676 llvm::cl::desc("Set the system root directory (usually /)"));
677
Chris Lattner4b009652007-07-25 00:24:17 +0000678// Finally, implement the code that groks the options above.
679enum IncludeDirGroup {
680 Quoted = 0,
681 Angled,
682 System,
683 After
684};
685
686static std::vector<DirectoryLookup> IncludeGroup[4];
687
688/// AddPath - Add the specified path to the specified group list.
689///
690static void AddPath(const std::string &Path, IncludeDirGroup Group,
691 bool isCXXAware, bool isUserSupplied,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000692 bool isFramework, HeaderSearch &HS) {
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000693 assert(!Path.empty() && "can't handle empty path here");
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000694 FileManager &FM = HS.getFileMgr();
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000695
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000696 // Compute the actual path, taking into consideration -isysroot.
697 llvm::SmallString<256> MappedPath;
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000698
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000699 // Handle isysroot.
700 if (Group == System) {
Chris Lattner2a2702a2007-12-17 06:51:34 +0000701 // FIXME: Portability. This should be a sys::Path interface, this doesn't
702 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000703 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
704 MappedPath.append(isysroot.begin(), isysroot.end());
Chris Lattner4b009652007-07-25 00:24:17 +0000705 }
706
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000707 MappedPath.append(Path.begin(), Path.end());
708
709 // Compute the DirectoryLookup type.
Chris Lattner4b009652007-07-25 00:24:17 +0000710 DirectoryLookup::DirType Type;
711 if (Group == Quoted || Group == Angled)
712 Type = DirectoryLookup::NormalHeaderDir;
713 else if (isCXXAware)
714 Type = DirectoryLookup::SystemHeaderDir;
715 else
716 Type = DirectoryLookup::ExternCSystemHeaderDir;
717
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000718
719 // If the directory exists, add it.
720 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
721 &MappedPath[0]+
722 MappedPath.size())) {
723 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
724 isFramework));
725 return;
726 }
727
Chris Lattnerb7426782007-12-17 07:52:39 +0000728 // Check to see if this is an apple-style headermap (which are not allowed to
729 // be frameworks).
730 if (!isFramework) {
731 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
732 &MappedPath[0]+MappedPath.size())) {
Chris Lattner9af36d32007-12-17 18:34:53 +0000733 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
734 // It is a headermap, add it to the search path.
Chris Lattnerb7426782007-12-17 07:52:39 +0000735 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
736 return;
737 }
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000738 }
739 }
740
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000741 if (Verbose)
742 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000743}
744
745/// RemoveDuplicates - If there are duplicate directory entries in the specified
746/// search list, remove the later (dead) ones.
747static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattnerac139d22007-12-15 23:20:07 +0000748 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerb7426782007-12-17 07:52:39 +0000749 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnercf33e932007-12-17 06:44:29 +0000750 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Chris Lattner4b009652007-07-25 00:24:17 +0000751 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnercf33e932007-12-17 06:44:29 +0000752 if (SearchList[i].isNormalDir()) {
753 // If this isn't the first time we've seen this dir, remove it.
754 if (SeenDirs.insert(SearchList[i].getDir()))
755 continue;
756
Chris Lattner4b009652007-07-25 00:24:17 +0000757 if (Verbose)
758 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
759 SearchList[i].getDir()->getName());
Chris Lattnerb7426782007-12-17 07:52:39 +0000760 } else if (SearchList[i].isFramework()) {
761 // If this isn't the first time we've seen this framework dir, remove it.
762 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
763 continue;
764
765 if (Verbose)
766 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
767 SearchList[i].getFrameworkDir()->getName());
768
Chris Lattnercf33e932007-12-17 06:44:29 +0000769 } else {
770 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
771 // If this isn't the first time we've seen this headermap, remove it.
772 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
773 continue;
774
775 if (Verbose)
776 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
777 SearchList[i].getDir()->getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000778 }
Chris Lattnercf33e932007-12-17 06:44:29 +0000779
780 // This is reached if the current entry is a duplicate.
781 SearchList.erase(SearchList.begin()+i);
782 --i;
Chris Lattner4b009652007-07-25 00:24:17 +0000783 }
784}
785
Chris Lattner4f022a72008-03-01 08:07:28 +0000786// AddEnvVarPaths - Add a list of paths from an environment variable to a
787// header search list.
788//
789static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
790 const char* at = getenv(Name);
791 if (!at)
792 return;
793
794 const char* delim = strchr(at, llvm::sys::PathSeparator);
795 while (delim != 0) {
796 if (delim-at == 0)
797 AddPath(".", Angled, false, true, false, Headers);
798 else
799 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
800 true, false, Headers);
801 at = delim + 1;
802 delim = strchr(at, llvm::sys::PathSeparator);
803 }
804 if (*at == 0)
805 AddPath(".", Angled, false, true, false, Headers);
806 else
807 AddPath(at, Angled, false, true, false, Headers);
808}
809
Chris Lattner4b009652007-07-25 00:24:17 +0000810/// InitializeIncludePaths - Process the -I options and set them in the
811/// HeaderSearch object.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000812static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
813 FileManager &FM, const LangOptions &Lang) {
Chris Lattner4b009652007-07-25 00:24:17 +0000814 // Handle -F... options.
815 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000816 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000817
818 // Handle -I... options.
Chris Lattner45a56e02007-12-05 23:24:17 +0000819 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000820 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000821
822 // Handle -idirafter... options.
823 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000824 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000825
826 // Handle -iquote... options.
827 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000828 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000829
830 // Handle -isystem... options.
831 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000832 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000833
834 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
835 // parallel, processing the values in order of occurance to get the right
836 // prefixes.
837 {
838 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
839 unsigned iprefix_idx = 0;
840 unsigned iwithprefix_idx = 0;
841 unsigned iwithprefixbefore_idx = 0;
842 bool iprefix_done = iprefix_vals.empty();
843 bool iwithprefix_done = iwithprefix_vals.empty();
844 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
845 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
846 if (!iprefix_done &&
847 (iwithprefix_done ||
848 iprefix_vals.getPosition(iprefix_idx) <
849 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
850 (iwithprefixbefore_done ||
851 iprefix_vals.getPosition(iprefix_idx) <
852 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
853 Prefix = iprefix_vals[iprefix_idx];
854 ++iprefix_idx;
855 iprefix_done = iprefix_idx == iprefix_vals.size();
856 } else if (!iwithprefix_done &&
857 (iwithprefixbefore_done ||
858 iwithprefix_vals.getPosition(iwithprefix_idx) <
859 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
860 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000861 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000862 ++iwithprefix_idx;
863 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
864 } else {
865 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000866 Angled, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000867 ++iwithprefixbefore_idx;
868 iwithprefixbefore_done =
869 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
870 }
871 }
872 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000873
874 AddEnvVarPaths("CPATH", Headers);
875 if (Lang.CPlusPlus && Lang.ObjC1)
876 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
877 else if (Lang.CPlusPlus)
878 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
879 else if (Lang.ObjC1)
880 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
881 else
882 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
883
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000884 // Add the clang headers, which are relative to the clang driver.
885 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000886 llvm::sys::Path::GetMainExecutable(Argv0,
887 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000888 if (!MainExecutablePath.isEmpty()) {
889 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
890 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
891 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
892 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
893 }
894
Chris Lattner4b009652007-07-25 00:24:17 +0000895 // FIXME: temporary hack: hard-coded paths.
896 // FIXME: get these from the target?
897 if (!nostdinc) {
898 if (Lang.CPlusPlus) {
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000899 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000900 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000901 false, Headers);
902 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
903 Headers);
Lauro Ramos Venanciof6a66272008-02-15 22:36:38 +0000904
905 // Ubuntu 7.10 - Gutsy Gibbon
906 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
907 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
908 false, Headers);
909 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
910 Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000911 }
912
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000913 AddPath("/usr/local/include", System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000914 // leopard
915 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000916 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000917 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000918 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000919 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
920 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000921 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000922
923 // tiger
924 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000925 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000926 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000927 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000928 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
929 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000930 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000931
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000932 // Ubuntu 7.10 - Gutsy Gibbon
933 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattner43b885f2008-02-25 21:04:36 +0000934 false, false, false, Headers);
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000935
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000936 AddPath("/usr/include", System, false, false, false, Headers);
937 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
938 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000939 }
940
941 // Now that we have collected all of the include paths, merge them all
942 // together and tell the preprocessor about them.
943
944 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
945 std::vector<DirectoryLookup> SearchList;
946 SearchList = IncludeGroup[Angled];
947 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
948 IncludeGroup[System].end());
949 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
950 IncludeGroup[After].end());
951 RemoveDuplicates(SearchList);
952 RemoveDuplicates(IncludeGroup[Quoted]);
953
954 // Prepend QUOTED list on the search list.
955 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
956 IncludeGroup[Quoted].end());
957
958
959 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
960 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
961 DontSearchCurDir);
962
963 // If verbose, print the list of directories that will be searched.
964 if (Verbose) {
965 fprintf(stderr, "#include \"...\" search starts here:\n");
966 unsigned QuotedIdx = IncludeGroup[Quoted].size();
967 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
968 if (i == QuotedIdx)
969 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner1df68f92007-12-17 17:57:27 +0000970 const char *Name = SearchList[i].getName();
971 const char *Suffix;
Chris Lattner0f64f652007-12-17 17:42:26 +0000972 if (SearchList[i].isNormalDir())
Chris Lattner1df68f92007-12-17 17:57:27 +0000973 Suffix = "";
Chris Lattner0f64f652007-12-17 17:42:26 +0000974 else if (SearchList[i].isFramework())
Chris Lattner1df68f92007-12-17 17:57:27 +0000975 Suffix = " (framework directory)";
Chris Lattner0f64f652007-12-17 17:42:26 +0000976 else {
977 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner1df68f92007-12-17 17:57:27 +0000978 Suffix = " (headermap)";
Chris Lattner0f64f652007-12-17 17:42:26 +0000979 }
Chris Lattner1df68f92007-12-17 17:57:27 +0000980 fprintf(stderr, " %s%s\n", Name, Suffix);
Chris Lattner4b009652007-07-25 00:24:17 +0000981 }
Chris Lattnerac553842007-12-15 23:11:06 +0000982 fprintf(stderr, "End of search list.\n");
Chris Lattner4b009652007-07-25 00:24:17 +0000983 }
984}
985
986
Chris Lattner4b009652007-07-25 00:24:17 +0000987//===----------------------------------------------------------------------===//
988// Basic Parser driver
989//===----------------------------------------------------------------------===//
990
Ted Kremenek17861c52007-12-19 22:51:13 +0000991static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Chris Lattner4b009652007-07-25 00:24:17 +0000992 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +0000993 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +0000994
995 // Parsing the specified input file.
996 P.ParseTranslationUnit();
997 delete PA;
998}
999
1000//===----------------------------------------------------------------------===//
1001// Main driver
1002//===----------------------------------------------------------------------===//
1003
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001004/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1005/// action. These consumers can operate on both ASTs that are freshly
1006/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001007static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001008 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001009 const LangOptions& LangOpts,
1010 llvm::Module *&DestModule) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001011 switch (ProgAction) {
1012 default:
1013 return NULL;
1014
1015 case ASTPrint:
1016 return CreateASTPrinter();
1017
1018 case ASTDump:
1019 return CreateASTDumper();
1020
1021 case ASTView:
1022 return CreateASTViewer();
1023
1024 case ParseCFGDump:
1025 case ParseCFGView:
Ted Kremenek83390ec2008-02-22 20:00:31 +00001026 return CreateCFGDumper(ProgAction == ParseCFGView,
1027 AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001028
1029 case AnalysisLiveVariables:
Ted Kremenekb278abb2008-02-22 20:13:09 +00001030 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001031
1032 case WarnDeadStores:
1033 return CreateDeadStoreChecker(Diag);
1034
1035 case WarnUninitVals:
1036 return CreateUnitValsChecker(Diag);
1037
Ted Kremenek3862eb12008-02-14 22:36:46 +00001038 case AnalysisGRSimpleVals:
Ted Kremenek0118bb52008-02-18 21:21:23 +00001039 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction);
Ted Kremenek3b451132008-01-08 18:04:06 +00001040
Ted Kremenek1da5b142008-02-15 00:35:38 +00001041 case AnalysisGRSimpleValsView:
Ted Kremenek0118bb52008-02-18 21:21:23 +00001042 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, true);
Ted Kremenek1da5b142008-02-15 00:35:38 +00001043
Ted Kremenek827f93b2008-03-06 00:08:09 +00001044 case CheckerCFRef:
1045 return CreateCFRefChecker(Diag, AnalyzeSpecificFunction);
1046
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001047 case TestSerialization:
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001048 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001049
1050 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001051 case EmitBC:
Chris Lattner8d72ee02008-02-06 01:42:25 +00001052 DestModule = new llvm::Module(InFile);
1053 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001054
Ted Kremenekbde30332007-12-19 17:25:59 +00001055 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001056 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +00001057 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek397de012007-12-13 00:37:31 +00001058
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001059 case RewriteTest:
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +00001060 return CreateCodeRewriterTest(InFile, Diag);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001061 }
1062}
1063
Chris Lattner4b009652007-07-25 00:24:17 +00001064/// ProcessInputFile - Process a single input file with the specified state.
1065///
Ted Kremenek0fd6e492007-12-19 22:32:34 +00001066static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattner968982d2007-12-15 20:48:40 +00001067 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001068
1069 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +00001070 bool ClearSourceMgr = false;
Chris Lattner8d72ee02008-02-06 01:42:25 +00001071 llvm::Module *CodeGenModule = 0;
Ted Kremenek6856c632007-09-26 18:39:29 +00001072
Chris Lattner4b009652007-07-25 00:24:17 +00001073 switch (ProgAction) {
1074 default:
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001075 Consumer = CreateASTConsumer(InFile,
1076 PP.getDiagnostics(),
Chris Lattner968982d2007-12-15 20:48:40 +00001077 PP.getFileManager(),
Chris Lattner8d72ee02008-02-06 01:42:25 +00001078 PP.getLangOptions(),
1079 CodeGenModule);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001080
1081 if (!Consumer) {
1082 fprintf(stderr, "Unexpected program action!\n");
1083 return;
1084 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001085
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001086 break;
1087
Chris Lattner4b009652007-07-25 00:24:17 +00001088 case DumpTokens: { // Token dump mode.
1089 Token Tok;
1090 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001091 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001092 do {
1093 PP.Lex(Tok);
1094 PP.DumpToken(Tok, true);
1095 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001096 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001097 ClearSourceMgr = true;
1098 break;
1099 }
1100 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1101 Token Tok;
1102 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001103 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001104 do {
1105 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001106 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001107 ClearSourceMgr = true;
1108 break;
1109 }
1110
1111 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001112 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001113 ClearSourceMgr = true;
1114 break;
1115
1116 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001117 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001118 ClearSourceMgr = true;
1119 break;
1120
1121 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001122 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001123 ClearSourceMgr = true;
1124 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001125
Ted Kremenek6856c632007-09-26 18:39:29 +00001126 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +00001127 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001128 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001129 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001130
1131 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001132 if (VerifyDiagnostics)
Ted Kremenek17861c52007-12-19 22:51:13 +00001133 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001134
1135 // This deletes Consumer.
Ted Kremenek17861c52007-12-19 22:51:13 +00001136 ParseAST(PP, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001137 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001138
1139 // If running the code generator, finish up now.
1140 if (CodeGenModule) {
1141 std::ostream *Out;
1142 if (OutputFile == "-") {
1143 Out = llvm::cout.stream();
1144 } else if (!OutputFile.empty()) {
1145 Out = new std::ofstream(OutputFile.c_str(),
1146 std::ios_base::binary|std::ios_base::out);
1147 } else if (InFile == "-") {
1148 Out = llvm::cout.stream();
1149 } else {
1150 llvm::sys::Path Path(InFile);
1151 Path.eraseSuffix();
1152 if (ProgAction == EmitLLVM)
1153 Path.appendSuffix("ll");
1154 else if (ProgAction == EmitBC)
1155 Path.appendSuffix("bc");
1156 else
1157 assert(0 && "Unknown action");
1158 Out = new std::ofstream(Path.toString().c_str(),
1159 std::ios_base::binary|std::ios_base::out);
1160 }
1161
1162 if (ProgAction == EmitLLVM) {
1163 CodeGenModule->print(*Out);
1164 } else {
1165 assert(ProgAction == EmitBC);
1166 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1167 }
1168
1169 if (Out != llvm::cout.stream())
1170 delete Out;
1171 delete CodeGenModule;
1172 }
Chris Lattner4b009652007-07-25 00:24:17 +00001173
1174 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001175 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001176 PP.PrintStats();
1177 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001178 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001179 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001180 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001181 fprintf(stderr, "\n");
1182 }
1183
1184 // For a multi-file compilation, some things are ok with nuking the source
1185 // manager tables, other require stable fileid/macroid's across multiple
1186 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001187 if (ClearSourceMgr)
1188 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001189}
1190
Ted Kremenek80d53372007-12-12 23:41:08 +00001191static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1192 FileManager& FileMgr) {
1193
1194 if (VerifyDiagnostics) {
1195 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1196 exit (1);
1197 }
1198
1199 llvm::sys::Path Filename(InFile);
1200
1201 if (!Filename.isValid()) {
1202 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1203 exit (1);
1204 }
1205
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001206 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001207
1208 if (!TU) {
1209 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1210 InFile.c_str());
1211 exit (1);
1212 }
1213
Ted Kremenekab749372007-12-19 19:27:38 +00001214 // Observe that we use the source file name stored in the deserialized
1215 // translation unit, rather than InFile.
Chris Lattner8d72ee02008-02-06 01:42:25 +00001216 llvm::Module *DestModule;
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001217 llvm::OwningPtr<ASTConsumer>
Chris Lattner8d72ee02008-02-06 01:42:25 +00001218 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1219 DestModule));
Ted Kremenek80d53372007-12-12 23:41:08 +00001220
1221 if (!Consumer) {
1222 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1223 exit (1);
1224 }
1225
Ted Kremenek17861c52007-12-19 22:51:13 +00001226 Consumer->Initialize(*TU->getContext());
Ted Kremenek80d53372007-12-12 23:41:08 +00001227
Chris Lattner8d72ee02008-02-06 01:42:25 +00001228 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001229 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1230 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001231}
1232
1233
Chris Lattner4b009652007-07-25 00:24:17 +00001234static llvm::cl::list<std::string>
1235InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1236
Ted Kremenek80d53372007-12-12 23:41:08 +00001237static bool isSerializedFile(const std::string& InFile) {
1238 if (InFile.size() < 4)
1239 return false;
1240
1241 const char* s = InFile.c_str()+InFile.size()-4;
1242
1243 return s[0] == '.' &&
1244 s[1] == 'a' &&
1245 s[2] == 's' &&
1246 s[3] == 't';
1247}
1248
Chris Lattner4b009652007-07-25 00:24:17 +00001249
1250int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001251 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001252 llvm::sys::PrintStackTraceOnErrorSignal();
1253
1254 // If no input was specified, read from stdin.
1255 if (InputFilenames.empty())
1256 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001257
Chris Lattner4b009652007-07-25 00:24:17 +00001258 // Create a file manager object to provide access to and cache the filesystem.
1259 FileManager FileMgr;
1260
Ted Kremenekb240e822007-12-11 23:28:38 +00001261 // Create the diagnostic client for reporting errors or for
1262 // implementing -verify.
Chris Lattner4b009652007-07-25 00:24:17 +00001263 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek56b70862007-09-26 20:14:22 +00001264 if (!VerifyDiagnostics) {
Chris Lattner4b009652007-07-25 00:24:17 +00001265 // Print diagnostics to stderr by default.
Ted Kremenekb3ee1932007-12-11 21:27:55 +00001266 DiagClient.reset(new TextDiagnosticPrinter());
Chris Lattner4b009652007-07-25 00:24:17 +00001267 } else {
1268 // When checking diagnostics, just buffer them up.
Ted Kremenekb3ee1932007-12-11 21:27:55 +00001269 DiagClient.reset(new TextDiagnosticBuffer());
Chris Lattner4b009652007-07-25 00:24:17 +00001270
1271 if (InputFilenames.size() != 1) {
1272 fprintf(stderr,
Ted Kremenek56b70862007-09-26 20:14:22 +00001273 "-verify only works on single input files for now.\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001274 return 1;
1275 }
1276 }
1277
1278 // Configure our handling of diagnostics.
1279 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +00001280 InitializeDiagnostics(Diags);
1281
Chris Lattner45a56e02007-12-05 23:24:17 +00001282 // -I- is a deprecated GCC feature, scan for it and reject it.
1283 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1284 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001285 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001286 I_dirs.erase(I_dirs.begin()+i);
1287 --i;
1288 }
1289 }
1290
Chris Lattner4b009652007-07-25 00:24:17 +00001291 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001292 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001293
Ted Kremenek80d53372007-12-12 23:41:08 +00001294 if (isSerializedFile(InFile))
1295 ProcessSerializedFile(InFile,Diags,FileMgr);
1296 else {
1297 /// Create a SourceManager object. This tracks and owns all the file
1298 /// buffers allocated to a translation unit.
1299 SourceManager SourceMgr;
Ted Kremenekb240e822007-12-11 23:28:38 +00001300
Ted Kremenek80d53372007-12-12 23:41:08 +00001301 // Initialize language options, inferring file types from input filenames.
1302 LangOptions LangInfo;
1303 InitializeBaseLanguage();
1304 LangKind LK = GetLanguage(InFile);
1305 InitializeLangOptions(LangInfo, LK);
1306 InitializeLanguageStandard(LangInfo, LK);
1307
1308 // Process the -I options and set them in the HeaderInfo.
1309 HeaderSearch HeaderInfo(FileMgr);
1310 DiagClient->setHeaderSearch(HeaderInfo);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001311 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001312
1313 // Get information about the targets being compiled for. Note that this
1314 // pointer and the TargetInfoImpl objects are never deleted by this toy
1315 // driver.
Ted Kremenek80d53372007-12-12 23:41:08 +00001316 std::vector<std::string> triples;
1317 CreateTargetTriples(triples);
Chris Lattnerfc457002008-03-05 01:18:20 +00001318 TargetInfo *Target = TargetInfo::CreateTargetInfo(triples[0]);
Ted Kremenek80d53372007-12-12 23:41:08 +00001319
1320 if (Target == 0) {
1321 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1322 triples[0].c_str());
1323 fprintf(stderr, "Please use -triple or -arch.\n");
1324 exit(1);
1325 }
1326
1327 // Set up the preprocessor with these options.
1328 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1329
1330 std::vector<char> PredefineBuffer;
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +00001331 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek2578dd02007-12-19 22:29:55 +00001332 continue;
1333
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +00001334 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001335 HeaderInfo.ClearFileInfo();
1336
1337 if (Stats)
1338 SourceMgr.PrintStats();
1339 }
Chris Lattner4b009652007-07-25 00:24:17 +00001340 }
1341
1342 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1343
1344 if (NumDiagnostics)
1345 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1346 (NumDiagnostics == 1 ? "" : "s"));
1347
1348 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001349 FileMgr.PrintStats();
1350 fprintf(stderr, "\n");
1351 }
1352
1353 return Diags.getNumErrors() != 0;
1354}