blob: 680707591291dbe6eacee005c5dcfb6281569c4f [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
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000464static llvm::cl::opt<bool>
465TrimGraph("trim-path-graph",
466 llvm::cl::desc("Only show error-related paths in the analysis graph."));
467
468
Ted Kremenek0118bb52008-02-18 21:21:23 +0000469//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000470// Target Triple Processing.
471//===----------------------------------------------------------------------===//
472
473static llvm::cl::opt<std::string>
474TargetTriple("triple",
475 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
476
Chris Lattnerfc457002008-03-05 01:18:20 +0000477static llvm::cl::opt<std::string>
Ted Kremenek40499482007-12-03 22:06:55 +0000478Archs("arch",
479 llvm::cl::desc("Specify target architecture (e.g. i686)."));
480
481namespace {
482 class TripleProcessor {
483 llvm::StringMap<char> TriplesProcessed;
484 std::vector<std::string>& triples;
485 public:
486 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
487
488 void addTriple(const std::string& t) {
489 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
490 TriplesProcessed.end()) {
491 triples.push_back(t);
492 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
493 }
494 }
495 };
496}
497
498static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenek40499482007-12-03 22:06:55 +0000499 // Initialize base triple. If a -triple option has been specified, use
500 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000501 std::string Triple = TargetTriple;
502 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000503
504 // Decompose the base triple into "arch" and suffix.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000505 std::string::size_type firstDash = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000506
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000507 if (firstDash == std::string::npos) {
508 fprintf(stderr,
509 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner210c0cc2007-12-12 05:01:48 +0000510 Triple.c_str());
511 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000512 }
Ted Kremenek40499482007-12-03 22:06:55 +0000513
Chris Lattner210c0cc2007-12-12 05:01:48 +0000514 std::string suffix(Triple, firstDash+1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000515
516 if (suffix.empty()) {
Chris Lattner210c0cc2007-12-12 05:01:48 +0000517 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
518 Triple.c_str());
519 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000520 }
Ted Kremenek40499482007-12-03 22:06:55 +0000521
522 // Create triple cacher.
523 TripleProcessor tp(triples);
524
525 // Add the primary triple to our set of triples if we are using the
526 // host-triple with no archs or using a specified target triple.
527 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner210c0cc2007-12-12 05:01:48 +0000528 tp.addTriple(Triple);
Chris Lattnerfc457002008-03-05 01:18:20 +0000529
530 if (!Archs.empty())
531 tp.addTriple(Archs + "-" + suffix);
Ted Kremenek40499482007-12-03 22:06:55 +0000532}
533
534//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000535// Preprocessor Initialization
536//===----------------------------------------------------------------------===//
537
538// FIXME: Preprocessor builtins to support.
539// -A... - Play with #assertions
540// -undef - Undefine all predefined macros
541
542static llvm::cl::list<std::string>
543D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
544 llvm::cl::desc("Predefine the specified macro"));
545static llvm::cl::list<std::string>
546U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
547 llvm::cl::desc("Undefine the specified macro"));
548
Chris Lattner008da782008-01-10 01:53:41 +0000549static llvm::cl::list<std::string>
550ImplicitIncludes("include", llvm::cl::value_desc("file"),
551 llvm::cl::desc("Include file before parsing"));
552
553
Chris Lattner4b009652007-07-25 00:24:17 +0000554// Append a #define line to Buf for Macro. Macro should be of the form XXX,
555// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
556// "#define XXX Y z W". To get a #define with no value, use "XXX=".
557static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
558 const char *Command = "#define ") {
559 Buf.insert(Buf.end(), Command, Command+strlen(Command));
560 if (const char *Equal = strchr(Macro, '=')) {
561 // Turn the = into ' '.
562 Buf.insert(Buf.end(), Macro, Equal);
563 Buf.push_back(' ');
564 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
565 } else {
566 // Push "macroname 1".
567 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
568 Buf.push_back(' ');
569 Buf.push_back('1');
570 }
571 Buf.push_back('\n');
572}
573
Chris Lattner008da782008-01-10 01:53:41 +0000574/// AddImplicitInclude - Add an implicit #include of the specified file to the
575/// predefines buffer.
576static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
577 const char *Inc = "#include \"";
578 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
579 Buf.insert(Buf.end(), File.begin(), File.end());
580 Buf.push_back('"');
581 Buf.push_back('\n');
582}
583
Chris Lattner4b009652007-07-25 00:24:17 +0000584
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000585/// InitializePreprocessor - Initialize the preprocessor getting it and the
586/// environment ready to process a single file. This returns the file ID for the
587/// input file. If a failure happens, it returns 0.
588///
589static unsigned InitializePreprocessor(Preprocessor &PP,
590 const std::string &InFile,
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000591 std::vector<char> &PredefineBuffer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000592
Chris Lattner968982d2007-12-15 20:48:40 +0000593 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000594
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000595 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000596 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000597 if (InFile != "-") {
598 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +0000599 if (File) SourceMgr.createMainFileID(File, SourceLocation());
600 if (SourceMgr.getMainFileID() == 0) {
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000601 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
602 return 0;
603 }
604 } else {
605 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +0000606 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
607 if (SourceMgr.getMainFileID() == 0) {
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000608 fprintf(stderr, "Error reading standard input! Empty?\n");
609 return 0;
610 }
Chris Lattner4b009652007-07-25 00:24:17 +0000611 }
612
Chris Lattner4b009652007-07-25 00:24:17 +0000613 // Add macros from the command line.
614 // FIXME: Should traverse the #define/#undef lists in parallel.
615 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000616 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000617 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000618 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
619
Chris Lattner008da782008-01-10 01:53:41 +0000620 // FIXME: Read any files specified by -imacros.
621
622 // Add implicit #includes from -include.
623 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
624 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000625
626 // Null terminate PredefinedBuffer and add it.
627 PredefineBuffer.push_back(0);
628 PP.setPredefines(&PredefineBuffer[0]);
629
630 // Once we've read this, we're done.
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +0000631 return SourceMgr.getMainFileID();
Chris Lattner4b009652007-07-25 00:24:17 +0000632}
633
634//===----------------------------------------------------------------------===//
635// Preprocessor include path information.
636//===----------------------------------------------------------------------===//
637
638// This tool exports a large number of command line options to control how the
639// preprocessor searches for header files. At root, however, the Preprocessor
640// object takes a very simple interface: a list of directories to search for
641//
642// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000643// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000644//
Chris Lattner008da782008-01-10 01:53:41 +0000645// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000646
647static llvm::cl::opt<bool>
648nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
649
650// Various command line options. These four add directories to each chain.
651static llvm::cl::list<std::string>
652F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
653 llvm::cl::desc("Add directory to framework include search path"));
654static llvm::cl::list<std::string>
655I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
656 llvm::cl::desc("Add directory to include search path"));
657static llvm::cl::list<std::string>
658idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
659 llvm::cl::desc("Add directory to AFTER include search path"));
660static llvm::cl::list<std::string>
661iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
662 llvm::cl::desc("Add directory to QUOTE include search path"));
663static llvm::cl::list<std::string>
664isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
665 llvm::cl::desc("Add directory to SYSTEM include search path"));
666
667// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
668static llvm::cl::list<std::string>
669iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
670 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
671static llvm::cl::list<std::string>
672iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
673 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
674static llvm::cl::list<std::string>
675iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
676 llvm::cl::Prefix,
677 llvm::cl::desc("Set directory to include search path with prefix"));
678
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000679static llvm::cl::opt<std::string>
680isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
681 llvm::cl::desc("Set the system root directory (usually /)"));
682
Chris Lattner4b009652007-07-25 00:24:17 +0000683// Finally, implement the code that groks the options above.
684enum IncludeDirGroup {
685 Quoted = 0,
686 Angled,
687 System,
688 After
689};
690
691static std::vector<DirectoryLookup> IncludeGroup[4];
692
693/// AddPath - Add the specified path to the specified group list.
694///
695static void AddPath(const std::string &Path, IncludeDirGroup Group,
696 bool isCXXAware, bool isUserSupplied,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000697 bool isFramework, HeaderSearch &HS) {
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000698 assert(!Path.empty() && "can't handle empty path here");
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000699 FileManager &FM = HS.getFileMgr();
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000700
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000701 // Compute the actual path, taking into consideration -isysroot.
702 llvm::SmallString<256> MappedPath;
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000703
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000704 // Handle isysroot.
705 if (Group == System) {
Chris Lattner2a2702a2007-12-17 06:51:34 +0000706 // FIXME: Portability. This should be a sys::Path interface, this doesn't
707 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000708 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
709 MappedPath.append(isysroot.begin(), isysroot.end());
Chris Lattner4b009652007-07-25 00:24:17 +0000710 }
711
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000712 MappedPath.append(Path.begin(), Path.end());
713
714 // Compute the DirectoryLookup type.
Chris Lattner4b009652007-07-25 00:24:17 +0000715 DirectoryLookup::DirType Type;
716 if (Group == Quoted || Group == Angled)
717 Type = DirectoryLookup::NormalHeaderDir;
718 else if (isCXXAware)
719 Type = DirectoryLookup::SystemHeaderDir;
720 else
721 Type = DirectoryLookup::ExternCSystemHeaderDir;
722
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000723
724 // If the directory exists, add it.
725 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
726 &MappedPath[0]+
727 MappedPath.size())) {
728 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
729 isFramework));
730 return;
731 }
732
Chris Lattnerb7426782007-12-17 07:52:39 +0000733 // Check to see if this is an apple-style headermap (which are not allowed to
734 // be frameworks).
735 if (!isFramework) {
736 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
737 &MappedPath[0]+MappedPath.size())) {
Chris Lattner9af36d32007-12-17 18:34:53 +0000738 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
739 // It is a headermap, add it to the search path.
Chris Lattnerb7426782007-12-17 07:52:39 +0000740 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
741 return;
742 }
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000743 }
744 }
745
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000746 if (Verbose)
747 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000748}
749
750/// RemoveDuplicates - If there are duplicate directory entries in the specified
751/// search list, remove the later (dead) ones.
752static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattnerac139d22007-12-15 23:20:07 +0000753 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerb7426782007-12-17 07:52:39 +0000754 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnercf33e932007-12-17 06:44:29 +0000755 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Chris Lattner4b009652007-07-25 00:24:17 +0000756 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnercf33e932007-12-17 06:44:29 +0000757 if (SearchList[i].isNormalDir()) {
758 // If this isn't the first time we've seen this dir, remove it.
759 if (SeenDirs.insert(SearchList[i].getDir()))
760 continue;
761
Chris Lattner4b009652007-07-25 00:24:17 +0000762 if (Verbose)
763 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
764 SearchList[i].getDir()->getName());
Chris Lattnerb7426782007-12-17 07:52:39 +0000765 } else if (SearchList[i].isFramework()) {
766 // If this isn't the first time we've seen this framework dir, remove it.
767 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
768 continue;
769
770 if (Verbose)
771 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
772 SearchList[i].getFrameworkDir()->getName());
773
Chris Lattnercf33e932007-12-17 06:44:29 +0000774 } else {
775 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
776 // If this isn't the first time we've seen this headermap, remove it.
777 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
778 continue;
779
780 if (Verbose)
781 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
782 SearchList[i].getDir()->getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000783 }
Chris Lattnercf33e932007-12-17 06:44:29 +0000784
785 // This is reached if the current entry is a duplicate.
786 SearchList.erase(SearchList.begin()+i);
787 --i;
Chris Lattner4b009652007-07-25 00:24:17 +0000788 }
789}
790
Chris Lattner4f022a72008-03-01 08:07:28 +0000791// AddEnvVarPaths - Add a list of paths from an environment variable to a
792// header search list.
793//
794static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
795 const char* at = getenv(Name);
796 if (!at)
797 return;
798
799 const char* delim = strchr(at, llvm::sys::PathSeparator);
800 while (delim != 0) {
801 if (delim-at == 0)
802 AddPath(".", Angled, false, true, false, Headers);
803 else
804 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
805 true, false, Headers);
806 at = delim + 1;
807 delim = strchr(at, llvm::sys::PathSeparator);
808 }
809 if (*at == 0)
810 AddPath(".", Angled, false, true, false, Headers);
811 else
812 AddPath(at, Angled, false, true, false, Headers);
813}
814
Chris Lattner4b009652007-07-25 00:24:17 +0000815/// InitializeIncludePaths - Process the -I options and set them in the
816/// HeaderSearch object.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000817static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
818 FileManager &FM, const LangOptions &Lang) {
Chris Lattner4b009652007-07-25 00:24:17 +0000819 // Handle -F... options.
820 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000821 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000822
823 // Handle -I... options.
Chris Lattner45a56e02007-12-05 23:24:17 +0000824 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000825 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000826
827 // Handle -idirafter... options.
828 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000829 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000830
831 // Handle -iquote... options.
832 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000833 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000834
835 // Handle -isystem... options.
836 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000837 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000838
839 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
840 // parallel, processing the values in order of occurance to get the right
841 // prefixes.
842 {
843 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
844 unsigned iprefix_idx = 0;
845 unsigned iwithprefix_idx = 0;
846 unsigned iwithprefixbefore_idx = 0;
847 bool iprefix_done = iprefix_vals.empty();
848 bool iwithprefix_done = iwithprefix_vals.empty();
849 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
850 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
851 if (!iprefix_done &&
852 (iwithprefix_done ||
853 iprefix_vals.getPosition(iprefix_idx) <
854 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
855 (iwithprefixbefore_done ||
856 iprefix_vals.getPosition(iprefix_idx) <
857 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
858 Prefix = iprefix_vals[iprefix_idx];
859 ++iprefix_idx;
860 iprefix_done = iprefix_idx == iprefix_vals.size();
861 } else if (!iwithprefix_done &&
862 (iwithprefixbefore_done ||
863 iwithprefix_vals.getPosition(iwithprefix_idx) <
864 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
865 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000866 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000867 ++iwithprefix_idx;
868 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
869 } else {
870 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000871 Angled, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000872 ++iwithprefixbefore_idx;
873 iwithprefixbefore_done =
874 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
875 }
876 }
877 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000878
879 AddEnvVarPaths("CPATH", Headers);
880 if (Lang.CPlusPlus && Lang.ObjC1)
881 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
882 else if (Lang.CPlusPlus)
883 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
884 else if (Lang.ObjC1)
885 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
886 else
887 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
888
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000889 // Add the clang headers, which are relative to the clang driver.
890 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000891 llvm::sys::Path::GetMainExecutable(Argv0,
892 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000893 if (!MainExecutablePath.isEmpty()) {
894 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
895 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
896 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
897 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
898 }
899
Chris Lattner4b009652007-07-25 00:24:17 +0000900 // FIXME: temporary hack: hard-coded paths.
901 // FIXME: get these from the target?
902 if (!nostdinc) {
903 if (Lang.CPlusPlus) {
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000904 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000905 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000906 false, Headers);
907 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
908 Headers);
Lauro Ramos Venanciof6a66272008-02-15 22:36:38 +0000909
910 // Ubuntu 7.10 - Gutsy Gibbon
911 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
912 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
913 false, Headers);
914 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
915 Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000916 }
917
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000918 AddPath("/usr/local/include", System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000919 // leopard
920 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000921 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000922 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000923 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000924 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
925 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000926 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000927
928 // tiger
929 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000930 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000931 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000932 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000933 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
934 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000935 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000936
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000937 // Ubuntu 7.10 - Gutsy Gibbon
938 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattner43b885f2008-02-25 21:04:36 +0000939 false, false, false, Headers);
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000940
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000941 AddPath("/usr/include", System, false, false, false, Headers);
942 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
943 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000944 }
945
946 // Now that we have collected all of the include paths, merge them all
947 // together and tell the preprocessor about them.
948
949 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
950 std::vector<DirectoryLookup> SearchList;
951 SearchList = IncludeGroup[Angled];
952 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
953 IncludeGroup[System].end());
954 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
955 IncludeGroup[After].end());
956 RemoveDuplicates(SearchList);
957 RemoveDuplicates(IncludeGroup[Quoted]);
958
959 // Prepend QUOTED list on the search list.
960 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
961 IncludeGroup[Quoted].end());
962
963
964 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
965 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
966 DontSearchCurDir);
967
968 // If verbose, print the list of directories that will be searched.
969 if (Verbose) {
970 fprintf(stderr, "#include \"...\" search starts here:\n");
971 unsigned QuotedIdx = IncludeGroup[Quoted].size();
972 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
973 if (i == QuotedIdx)
974 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner1df68f92007-12-17 17:57:27 +0000975 const char *Name = SearchList[i].getName();
976 const char *Suffix;
Chris Lattner0f64f652007-12-17 17:42:26 +0000977 if (SearchList[i].isNormalDir())
Chris Lattner1df68f92007-12-17 17:57:27 +0000978 Suffix = "";
Chris Lattner0f64f652007-12-17 17:42:26 +0000979 else if (SearchList[i].isFramework())
Chris Lattner1df68f92007-12-17 17:57:27 +0000980 Suffix = " (framework directory)";
Chris Lattner0f64f652007-12-17 17:42:26 +0000981 else {
982 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner1df68f92007-12-17 17:57:27 +0000983 Suffix = " (headermap)";
Chris Lattner0f64f652007-12-17 17:42:26 +0000984 }
Chris Lattner1df68f92007-12-17 17:57:27 +0000985 fprintf(stderr, " %s%s\n", Name, Suffix);
Chris Lattner4b009652007-07-25 00:24:17 +0000986 }
Chris Lattnerac553842007-12-15 23:11:06 +0000987 fprintf(stderr, "End of search list.\n");
Chris Lattner4b009652007-07-25 00:24:17 +0000988 }
989}
990
991
Chris Lattner4b009652007-07-25 00:24:17 +0000992//===----------------------------------------------------------------------===//
993// Basic Parser driver
994//===----------------------------------------------------------------------===//
995
Ted Kremenek17861c52007-12-19 22:51:13 +0000996static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Chris Lattner4b009652007-07-25 00:24:17 +0000997 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +0000998 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +0000999
1000 // Parsing the specified input file.
1001 P.ParseTranslationUnit();
1002 delete PA;
1003}
1004
1005//===----------------------------------------------------------------------===//
1006// Main driver
1007//===----------------------------------------------------------------------===//
1008
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001009/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1010/// action. These consumers can operate on both ASTs that are freshly
1011/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001012static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001013 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001014 const LangOptions& LangOpts,
1015 llvm::Module *&DestModule) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001016 switch (ProgAction) {
1017 default:
1018 return NULL;
1019
1020 case ASTPrint:
1021 return CreateASTPrinter();
1022
1023 case ASTDump:
1024 return CreateASTDumper();
1025
1026 case ASTView:
1027 return CreateASTViewer();
1028
1029 case ParseCFGDump:
1030 case ParseCFGView:
Ted Kremenek83390ec2008-02-22 20:00:31 +00001031 return CreateCFGDumper(ProgAction == ParseCFGView,
1032 AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001033
1034 case AnalysisLiveVariables:
Ted Kremenekb278abb2008-02-22 20:13:09 +00001035 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001036
1037 case WarnDeadStores:
1038 return CreateDeadStoreChecker(Diag);
1039
1040 case WarnUninitVals:
1041 return CreateUnitValsChecker(Diag);
1042
Ted Kremenek3862eb12008-02-14 22:36:46 +00001043 case AnalysisGRSimpleVals:
Ted Kremenek0118bb52008-02-18 21:21:23 +00001044 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction);
Ted Kremenek3b451132008-01-08 18:04:06 +00001045
Ted Kremenek1da5b142008-02-15 00:35:38 +00001046 case AnalysisGRSimpleValsView:
Ted Kremenek5e1e05c2008-03-07 22:58:01 +00001047 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, true, TrimGraph);
Ted Kremenek1da5b142008-02-15 00:35:38 +00001048
Ted Kremenek827f93b2008-03-06 00:08:09 +00001049 case CheckerCFRef:
1050 return CreateCFRefChecker(Diag, AnalyzeSpecificFunction);
1051
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001052 case TestSerialization:
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001053 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001054
1055 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001056 case EmitBC:
Chris Lattner8d72ee02008-02-06 01:42:25 +00001057 DestModule = new llvm::Module(InFile);
1058 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001059
Ted Kremenekbde30332007-12-19 17:25:59 +00001060 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001061 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +00001062 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek397de012007-12-13 00:37:31 +00001063
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001064 case RewriteTest:
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +00001065 return CreateCodeRewriterTest(InFile, Diag);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001066 }
1067}
1068
Chris Lattner4b009652007-07-25 00:24:17 +00001069/// ProcessInputFile - Process a single input file with the specified state.
1070///
Ted Kremenek0fd6e492007-12-19 22:32:34 +00001071static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattner968982d2007-12-15 20:48:40 +00001072 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001073
1074 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +00001075 bool ClearSourceMgr = false;
Chris Lattner8d72ee02008-02-06 01:42:25 +00001076 llvm::Module *CodeGenModule = 0;
Ted Kremenek6856c632007-09-26 18:39:29 +00001077
Chris Lattner4b009652007-07-25 00:24:17 +00001078 switch (ProgAction) {
1079 default:
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001080 Consumer = CreateASTConsumer(InFile,
1081 PP.getDiagnostics(),
Chris Lattner968982d2007-12-15 20:48:40 +00001082 PP.getFileManager(),
Chris Lattner8d72ee02008-02-06 01:42:25 +00001083 PP.getLangOptions(),
1084 CodeGenModule);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001085
1086 if (!Consumer) {
1087 fprintf(stderr, "Unexpected program action!\n");
1088 return;
1089 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001090
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001091 break;
1092
Chris Lattner4b009652007-07-25 00:24:17 +00001093 case DumpTokens: { // Token dump mode.
1094 Token Tok;
1095 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001096 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001097 do {
1098 PP.Lex(Tok);
1099 PP.DumpToken(Tok, true);
1100 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001101 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001102 ClearSourceMgr = true;
1103 break;
1104 }
1105 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1106 Token Tok;
1107 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001108 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001109 do {
1110 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001111 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001112 ClearSourceMgr = true;
1113 break;
1114 }
1115
1116 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001117 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001118 ClearSourceMgr = true;
1119 break;
1120
1121 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001122 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001123 ClearSourceMgr = true;
1124 break;
1125
1126 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001127 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001128 ClearSourceMgr = true;
1129 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001130
Ted Kremenek6856c632007-09-26 18:39:29 +00001131 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +00001132 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001133 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001134 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001135
1136 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001137 if (VerifyDiagnostics)
Ted Kremenek17861c52007-12-19 22:51:13 +00001138 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001139
1140 // This deletes Consumer.
Ted Kremenek17861c52007-12-19 22:51:13 +00001141 ParseAST(PP, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001142 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001143
1144 // If running the code generator, finish up now.
1145 if (CodeGenModule) {
1146 std::ostream *Out;
1147 if (OutputFile == "-") {
1148 Out = llvm::cout.stream();
1149 } else if (!OutputFile.empty()) {
1150 Out = new std::ofstream(OutputFile.c_str(),
1151 std::ios_base::binary|std::ios_base::out);
1152 } else if (InFile == "-") {
1153 Out = llvm::cout.stream();
1154 } else {
1155 llvm::sys::Path Path(InFile);
1156 Path.eraseSuffix();
1157 if (ProgAction == EmitLLVM)
1158 Path.appendSuffix("ll");
1159 else if (ProgAction == EmitBC)
1160 Path.appendSuffix("bc");
1161 else
1162 assert(0 && "Unknown action");
1163 Out = new std::ofstream(Path.toString().c_str(),
1164 std::ios_base::binary|std::ios_base::out);
1165 }
1166
1167 if (ProgAction == EmitLLVM) {
1168 CodeGenModule->print(*Out);
1169 } else {
1170 assert(ProgAction == EmitBC);
1171 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1172 }
1173
1174 if (Out != llvm::cout.stream())
1175 delete Out;
1176 delete CodeGenModule;
1177 }
Chris Lattner4b009652007-07-25 00:24:17 +00001178
1179 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001180 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001181 PP.PrintStats();
1182 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001183 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001184 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001185 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001186 fprintf(stderr, "\n");
1187 }
1188
1189 // For a multi-file compilation, some things are ok with nuking the source
1190 // manager tables, other require stable fileid/macroid's across multiple
1191 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001192 if (ClearSourceMgr)
1193 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001194}
1195
Ted Kremenek80d53372007-12-12 23:41:08 +00001196static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1197 FileManager& FileMgr) {
1198
1199 if (VerifyDiagnostics) {
1200 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1201 exit (1);
1202 }
1203
1204 llvm::sys::Path Filename(InFile);
1205
1206 if (!Filename.isValid()) {
1207 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1208 exit (1);
1209 }
1210
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001211 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001212
1213 if (!TU) {
1214 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1215 InFile.c_str());
1216 exit (1);
1217 }
1218
Ted Kremenekab749372007-12-19 19:27:38 +00001219 // Observe that we use the source file name stored in the deserialized
1220 // translation unit, rather than InFile.
Chris Lattner8d72ee02008-02-06 01:42:25 +00001221 llvm::Module *DestModule;
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001222 llvm::OwningPtr<ASTConsumer>
Chris Lattner8d72ee02008-02-06 01:42:25 +00001223 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1224 DestModule));
Ted Kremenek80d53372007-12-12 23:41:08 +00001225
1226 if (!Consumer) {
1227 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1228 exit (1);
1229 }
1230
Ted Kremenek17861c52007-12-19 22:51:13 +00001231 Consumer->Initialize(*TU->getContext());
Ted Kremenek80d53372007-12-12 23:41:08 +00001232
Chris Lattner8d72ee02008-02-06 01:42:25 +00001233 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001234 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1235 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001236}
1237
1238
Chris Lattner4b009652007-07-25 00:24:17 +00001239static llvm::cl::list<std::string>
1240InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1241
Ted Kremenek80d53372007-12-12 23:41:08 +00001242static bool isSerializedFile(const std::string& InFile) {
1243 if (InFile.size() < 4)
1244 return false;
1245
1246 const char* s = InFile.c_str()+InFile.size()-4;
1247
1248 return s[0] == '.' &&
1249 s[1] == 'a' &&
1250 s[2] == 's' &&
1251 s[3] == 't';
1252}
1253
Chris Lattner4b009652007-07-25 00:24:17 +00001254
1255int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001256 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001257 llvm::sys::PrintStackTraceOnErrorSignal();
1258
1259 // If no input was specified, read from stdin.
1260 if (InputFilenames.empty())
1261 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001262
Chris Lattner4b009652007-07-25 00:24:17 +00001263 // Create a file manager object to provide access to and cache the filesystem.
1264 FileManager FileMgr;
1265
Ted Kremenekb240e822007-12-11 23:28:38 +00001266 // Create the diagnostic client for reporting errors or for
1267 // implementing -verify.
Chris Lattner4b009652007-07-25 00:24:17 +00001268 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek56b70862007-09-26 20:14:22 +00001269 if (!VerifyDiagnostics) {
Chris Lattner4b009652007-07-25 00:24:17 +00001270 // Print diagnostics to stderr by default.
Ted Kremenekb3ee1932007-12-11 21:27:55 +00001271 DiagClient.reset(new TextDiagnosticPrinter());
Chris Lattner4b009652007-07-25 00:24:17 +00001272 } else {
1273 // When checking diagnostics, just buffer them up.
Ted Kremenekb3ee1932007-12-11 21:27:55 +00001274 DiagClient.reset(new TextDiagnosticBuffer());
Chris Lattner4b009652007-07-25 00:24:17 +00001275
1276 if (InputFilenames.size() != 1) {
1277 fprintf(stderr,
Ted Kremenek56b70862007-09-26 20:14:22 +00001278 "-verify only works on single input files for now.\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001279 return 1;
1280 }
1281 }
1282
1283 // Configure our handling of diagnostics.
1284 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +00001285 InitializeDiagnostics(Diags);
1286
Chris Lattner45a56e02007-12-05 23:24:17 +00001287 // -I- is a deprecated GCC feature, scan for it and reject it.
1288 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1289 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001290 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001291 I_dirs.erase(I_dirs.begin()+i);
1292 --i;
1293 }
1294 }
1295
Chris Lattner4b009652007-07-25 00:24:17 +00001296 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001297 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001298
Ted Kremenek80d53372007-12-12 23:41:08 +00001299 if (isSerializedFile(InFile))
1300 ProcessSerializedFile(InFile,Diags,FileMgr);
1301 else {
1302 /// Create a SourceManager object. This tracks and owns all the file
1303 /// buffers allocated to a translation unit.
1304 SourceManager SourceMgr;
Ted Kremenekb240e822007-12-11 23:28:38 +00001305
Ted Kremenek80d53372007-12-12 23:41:08 +00001306 // Initialize language options, inferring file types from input filenames.
1307 LangOptions LangInfo;
1308 InitializeBaseLanguage();
1309 LangKind LK = GetLanguage(InFile);
1310 InitializeLangOptions(LangInfo, LK);
1311 InitializeLanguageStandard(LangInfo, LK);
1312
1313 // Process the -I options and set them in the HeaderInfo.
1314 HeaderSearch HeaderInfo(FileMgr);
1315 DiagClient->setHeaderSearch(HeaderInfo);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001316 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001317
1318 // Get information about the targets being compiled for. Note that this
1319 // pointer and the TargetInfoImpl objects are never deleted by this toy
1320 // driver.
Ted Kremenek80d53372007-12-12 23:41:08 +00001321 std::vector<std::string> triples;
1322 CreateTargetTriples(triples);
Chris Lattnerfc457002008-03-05 01:18:20 +00001323 TargetInfo *Target = TargetInfo::CreateTargetInfo(triples[0]);
Ted Kremenek80d53372007-12-12 23:41:08 +00001324
1325 if (Target == 0) {
1326 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1327 triples[0].c_str());
1328 fprintf(stderr, "Please use -triple or -arch.\n");
1329 exit(1);
1330 }
1331
1332 // Set up the preprocessor with these options.
1333 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1334
1335 std::vector<char> PredefineBuffer;
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +00001336 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek2578dd02007-12-19 22:29:55 +00001337 continue;
1338
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +00001339 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001340 HeaderInfo.ClearFileInfo();
1341
1342 if (Stats)
1343 SourceMgr.PrintStats();
1344 }
Chris Lattner4b009652007-07-25 00:24:17 +00001345 }
1346
1347 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1348
1349 if (NumDiagnostics)
1350 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1351 (NumDiagnostics == 1 ? "" : "s"));
1352
1353 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001354 FileMgr.PrintStats();
1355 fprintf(stderr, "\n");
1356 }
1357
1358 return Diags.getNumErrors() != 0;
1359}