blob: 5d004977ca10957f1018e008091b35f8905396fd [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000029#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000030#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000031#include "clang/Sema/ParseAST.h"
Chris Lattner556beb72007-09-15 22:56:56 +000032#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Parse/Parser.h"
34#include "clang/Lex/HeaderSearch.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000038#include "llvm/Module.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000040#include "llvm/Bitcode/ReaderWriter.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000044#include "llvm/Config/config.h"
Ted Kremenekee533642007-12-20 19:47:16 +000045#include "llvm/ADT/OwningPtr.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000046#include "llvm/System/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047#include <memory>
Chris Lattnere66b65c2008-02-06 01:42:25 +000048#include <fstream>
Reid Spencer5f016e22007-07-11 17:01:13 +000049using namespace clang;
50
51//===----------------------------------------------------------------------===//
52// Global options.
53//===----------------------------------------------------------------------===//
54
55static llvm::cl::opt<bool>
56Verbose("v", llvm::cl::desc("Enable verbose output"));
57static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000058Stats("print-stats",
59 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000060
61enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000062 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000063 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000064 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000065 SerializeAST, // Emit a .ast file.
Chris Lattner3b427b32007-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 Kremenekfddd5182007-08-21 21:42:03 +000069 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000070 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000071 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenekd55fe522008-02-15 00:35:38 +000072 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
73 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek055c2752007-09-06 23:00:42 +000074 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000075 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000076 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000077 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000078 ParsePrintCallbacks, // Parse and print each callback.
79 ParseSyntaxOnly, // Parse and perform semantic analysis.
80 ParseNoop, // Parse with noop callbacks.
81 RunPreprocessorOnly, // Just lex, no output.
82 PrintPreprocessedInput, // -E mode.
83 DumpTokens // Token dump mode.
84};
85
86static llvm::cl::opt<ProgActions>
87ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
88 llvm::cl::init(ParseSyntaxOnly),
89 llvm::cl::values(
90 clEnumValN(RunPreprocessorOnly, "Eonly",
91 "Just run preprocessor, no output (for timings)"),
92 clEnumValN(PrintPreprocessedInput, "E",
93 "Run preprocessor, emit preprocessed file"),
94 clEnumValN(DumpTokens, "dumptokens",
95 "Run preprocessor, dump internal rep of tokens"),
96 clEnumValN(ParseNoop, "parse-noop",
97 "Run parser with noop callbacks (for timings)"),
98 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
99 "Run parser and perform semantic analysis"),
100 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
101 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000102 clEnumValN(ASTPrint, "ast-print",
103 "Build ASTs and then pretty-print them"),
104 clEnumValN(ASTDump, "ast-dump",
105 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000106 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000107 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000108 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000109 "Run parser, then build and print CFGs."),
110 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000111 "Run parser, then build and view CFGs with Graphviz."),
112 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000113 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000114 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000115 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000116 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000117 "Flag warnings of uses of unitialized variables."),
Ted Kremeneke01c9872008-02-14 22:36:46 +0000118 clEnumValN(AnalysisGRSimpleVals, "grsimple",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000119 "Perform path-sensitive constant propagation."),
Ted Kremenekd55fe522008-02-15 00:35:38 +0000120 clEnumValN(AnalysisGRSimpleValsView, "grsimple-view",
121 "View results of path-sensitive constant propagation."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000122 clEnumValN(TestSerialization, "test-pickling",
123 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000125 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000126 clEnumValN(EmitBC, "emit-llvm-bc",
127 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000128 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000129 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000130 clEnumValN(RewriteTest, "rewrite-test",
131 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 clEnumValEnd));
133
Ted Kremenekccc76472007-12-19 19:47:59 +0000134
135static llvm::cl::opt<std::string>
136OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000137 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000138 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
139
Ted Kremenek41193e42007-09-26 19:42:19 +0000140static llvm::cl::opt<bool>
141VerifyDiagnostics("verify",
142 llvm::cl::desc("Verify emitted diagnostics and warnings."));
143
Reid Spencer5f016e22007-07-11 17:01:13 +0000144//===----------------------------------------------------------------------===//
145// Language Options
146//===----------------------------------------------------------------------===//
147
148enum LangKind {
149 langkind_unspecified,
150 langkind_c,
151 langkind_c_cpp,
152 langkind_cxx,
153 langkind_cxx_cpp,
154 langkind_objc,
155 langkind_objc_cpp,
156 langkind_objcxx,
157 langkind_objcxx_cpp
158};
159
160/* TODO: GCC also accepts:
161 c-header c++-header objective-c-header objective-c++-header
162 assembler assembler-with-cpp
163 ada, f77*, ratfor (!), f95, java, treelang
164 */
165static llvm::cl::opt<LangKind>
166BaseLang("x", llvm::cl::desc("Base language to compile"),
167 llvm::cl::init(langkind_unspecified),
168 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
169 clEnumValN(langkind_cxx, "c++", "C++"),
170 clEnumValN(langkind_objc, "objective-c", "Objective C"),
171 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
172 clEnumValN(langkind_c_cpp, "c-cpp-output",
173 "Preprocessed C"),
174 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
175 "Preprocessed C++"),
176 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
177 "Preprocessed Objective C"),
178 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
179 "Preprocessed Objective C++"),
180 clEnumValEnd));
181
182static llvm::cl::opt<bool>
183LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
184 llvm::cl::Hidden);
185static llvm::cl::opt<bool>
186LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
187 llvm::cl::Hidden);
188
Ted Kremenek8904f152007-12-05 23:49:08 +0000189/// InitializeBaseLanguage - Handle the -x foo options.
190static void InitializeBaseLanguage() {
191 if (LangObjC)
192 BaseLang = langkind_objc;
193 else if (LangObjCXX)
194 BaseLang = langkind_objcxx;
195}
196
197static LangKind GetLanguage(const std::string &Filename) {
198 if (BaseLang != langkind_unspecified)
199 return BaseLang;
200
201 std::string::size_type DotPos = Filename.rfind('.');
202
203 if (DotPos == std::string::npos) {
204 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000205 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 }
207
Ted Kremenek8904f152007-12-05 23:49:08 +0000208 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
209 // C header: .h
210 // C++ header: .hh or .H;
211 // assembler no preprocessing: .s
212 // assembler: .S
213 if (Ext == "c")
214 return langkind_c;
215 else if (Ext == "i")
216 return langkind_c_cpp;
217 else if (Ext == "ii")
218 return langkind_cxx_cpp;
219 else if (Ext == "m")
220 return langkind_objc;
221 else if (Ext == "mi")
222 return langkind_objc_cpp;
223 else if (Ext == "mm" || Ext == "M")
224 return langkind_objcxx;
225 else if (Ext == "mii")
226 return langkind_objcxx_cpp;
227 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
228 Ext == "c++" || Ext == "cp" || Ext == "cxx")
229 return langkind_cxx;
230 else
231 return langkind_c;
232}
233
234
235static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 // FIXME: implement -fpreprocessed mode.
237 bool NoPreprocess = false;
238
Ted Kremenek8904f152007-12-05 23:49:08 +0000239 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000240 default: assert(0 && "Unknown language kind!");
241 case langkind_c_cpp:
242 NoPreprocess = true;
243 // FALLTHROUGH
244 case langkind_c:
245 break;
246 case langkind_cxx_cpp:
247 NoPreprocess = true;
248 // FALLTHROUGH
249 case langkind_cxx:
250 Options.CPlusPlus = 1;
251 break;
252 case langkind_objc_cpp:
253 NoPreprocess = true;
254 // FALLTHROUGH
255 case langkind_objc:
256 Options.ObjC1 = Options.ObjC2 = 1;
257 break;
258 case langkind_objcxx_cpp:
259 NoPreprocess = true;
260 // FALLTHROUGH
261 case langkind_objcxx:
262 Options.ObjC1 = Options.ObjC2 = 1;
263 Options.CPlusPlus = 1;
264 break;
265 }
266}
267
268/// LangStds - Language standards we support.
269enum LangStds {
270 lang_unspecified,
271 lang_c89, lang_c94, lang_c99,
272 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000273 lang_cxx98, lang_gnucxx98,
274 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000275};
276
277static llvm::cl::opt<LangStds>
278LangStd("std", llvm::cl::desc("Language standard to compile for"),
279 llvm::cl::init(lang_unspecified),
280 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
281 clEnumValN(lang_c89, "c90", "ISO C 1990"),
282 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
283 clEnumValN(lang_c94, "iso9899:199409",
284 "ISO C 1990 with amendment 1"),
285 clEnumValN(lang_c99, "c99", "ISO C 1999"),
286// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
287 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
288// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
289 clEnumValN(lang_gnu89, "gnu89",
290 "ISO C 1990 with GNU extensions (default for C)"),
291 clEnumValN(lang_gnu99, "gnu99",
292 "ISO C 1999 with GNU extensions"),
293 clEnumValN(lang_gnu99, "gnu9x",
294 "ISO C 1999 with GNU extensions"),
295 clEnumValN(lang_cxx98, "c++98",
296 "ISO C++ 1998 with amendments"),
297 clEnumValN(lang_gnucxx98, "gnu++98",
298 "ISO C++ 1998 with amendments and GNU "
299 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000300 clEnumValN(lang_cxx0x, "c++0x",
301 "Upcoming ISO C++ 200x with amendments"),
302 clEnumValN(lang_gnucxx0x, "gnu++0x",
303 "Upcoming ISO C++ 200x with amendments and GNU "
304 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 clEnumValEnd));
306
307static llvm::cl::opt<bool>
308NoOperatorNames("fno-operator-names",
309 llvm::cl::desc("Do not treat C++ operator name keywords as "
310 "synonyms for operators"));
311
Anders Carlssonee98ac52007-10-15 02:50:23 +0000312static llvm::cl::opt<bool>
313PascalStrings("fpascal-strings",
314 llvm::cl::desc("Recognize and construct Pascal-style "
315 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000316
317static llvm::cl::opt<bool>
318MSExtensions("fms-extensions",
319 llvm::cl::desc("Accept some non-standard constructs used in "
320 "Microsoft header files. "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000321
322static llvm::cl::opt<bool>
323WritableStrings("fwritable-strings",
324 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000325
326static llvm::cl::opt<bool>
327LaxVectorConversions("flax-vector-conversions",
328 llvm::cl::desc("Allow implicit conversions between vectors"
329 " with a different number of elements or "
330 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000331// FIXME: add:
332// -ansi
333// -trigraphs
334// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000335// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000336static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 if (LangStd == lang_unspecified) {
338 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000339 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 default: assert(0 && "Unknown base language");
341 case langkind_c:
342 case langkind_c_cpp:
343 case langkind_objc:
344 case langkind_objc_cpp:
345 LangStd = lang_gnu99;
346 break;
347 case langkind_cxx:
348 case langkind_cxx_cpp:
349 case langkind_objcxx:
350 case langkind_objcxx_cpp:
351 LangStd = lang_gnucxx98;
352 break;
353 }
354 }
355
356 switch (LangStd) {
357 default: assert(0 && "Unknown language standard!");
358
359 // Fall through from newer standards to older ones. This isn't really right.
360 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000361 case lang_gnucxx0x:
362 case lang_cxx0x:
363 Options.CPlusPlus0x = 1;
364 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 case lang_gnucxx98:
366 case lang_cxx98:
367 Options.CPlusPlus = 1;
368 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000369 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 // FALL THROUGH.
371 case lang_gnu99:
372 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 Options.C99 = 1;
374 Options.HexFloats = 1;
375 // FALL THROUGH.
376 case lang_gnu89:
377 Options.BCPLComment = 1; // Only for C99/C++.
378 // FALL THROUGH.
379 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000380 Options.Digraphs = 1; // C94, C99, C++.
381 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 case lang_c89:
383 break;
384 }
385
386 Options.Trigraphs = 1; // -trigraphs or -ansi
387 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000388 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000389 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000390 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000391 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000392}
393
394//===----------------------------------------------------------------------===//
395// Our DiagnosticClient implementation
396//===----------------------------------------------------------------------===//
397
398// FIXME: Werror should take a list of things, -Werror=foo,bar
399static llvm::cl::opt<bool>
400WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
401
402static llvm::cl::opt<bool>
403WarnOnExtensions("pedantic", llvm::cl::init(false),
404 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
405
406static llvm::cl::opt<bool>
407ErrorOnExtensions("pedantic-errors",
408 llvm::cl::desc("Issue an error on uses of GCC extensions"));
409
410static llvm::cl::opt<bool>
411WarnUnusedMacros("Wunused_macros",
412 llvm::cl::desc("Warn for unused macros in the main translation unit"));
413
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000414static llvm::cl::opt<bool>
415WarnFloatEqual("Wfloat-equal",
416 llvm::cl::desc("Warn about equality comparisons of floating point values."));
417
Ted Kremenek73da5902007-12-17 17:50:07 +0000418static llvm::cl::opt<bool>
419WarnNoFormatNonLiteral("Wno-format-nonliteral",
420 llvm::cl::desc("Do not warn about non-literal format strings."));
421
Chris Lattner116a4b12008-01-23 17:19:46 +0000422static llvm::cl::opt<bool>
423WarnUndefMacros("Wundef",
424 llvm::cl::desc("Warn on use of undefined macros in #if's"));
425
426
Reid Spencer5f016e22007-07-11 17:01:13 +0000427/// InitializeDiagnostics - Initialize the diagnostic object, based on the
428/// current command line option settings.
429static void InitializeDiagnostics(Diagnostic &Diags) {
430 Diags.setWarningsAsErrors(WarningsAsErrors);
431 Diags.setWarnOnExtensions(WarnOnExtensions);
432 Diags.setErrorOnExtensions(ErrorOnExtensions);
433
434 // Silence the "macro is not used" warning unless requested.
435 if (!WarnUnusedMacros)
436 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000437
438 // Silence "floating point comparison" warnings unless requested.
439 if (!WarnFloatEqual)
440 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000441
442 // Silence "format string is not a string literal" warnings if requested
443 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000444 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
445 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000446 if (!WarnUndefMacros)
447 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000448
449 if (MSExtensions) // MS allows unnamed struct/union fields.
450 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000451}
452
453//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000454// Analysis-specific options.
455//===----------------------------------------------------------------------===//
456
457static llvm::cl::opt<std::string>
458AnalyzeSpecificFunction("analyze-function",
459 llvm::cl::desc("Run analysis on specific function."));
460
461//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000462// Target Triple Processing.
463//===----------------------------------------------------------------------===//
464
465static llvm::cl::opt<std::string>
466TargetTriple("triple",
467 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
468
469static llvm::cl::list<std::string>
470Archs("arch",
471 llvm::cl::desc("Specify target architecture (e.g. i686)."));
472
473namespace {
474 class TripleProcessor {
475 llvm::StringMap<char> TriplesProcessed;
476 std::vector<std::string>& triples;
477 public:
478 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
479
480 void addTriple(const std::string& t) {
481 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
482 TriplesProcessed.end()) {
483 triples.push_back(t);
484 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
485 }
486 }
487 };
488}
489
490static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000491 // Initialize base triple. If a -triple option has been specified, use
492 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000493 std::string Triple = TargetTriple;
494 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000495
496 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000497 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000498
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000499 if (firstDash == std::string::npos) {
500 fprintf(stderr,
501 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000502 Triple.c_str());
503 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000504 }
Ted Kremenekae360762007-12-03 22:06:55 +0000505
Chris Lattner6590d212007-12-12 05:01:48 +0000506 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000507
508 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000509 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
510 Triple.c_str());
511 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000512 }
Ted Kremenekae360762007-12-03 22:06:55 +0000513
514 // Create triple cacher.
515 TripleProcessor tp(triples);
516
517 // Add the primary triple to our set of triples if we are using the
518 // host-triple with no archs or using a specified target triple.
519 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000520 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000521
522 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
523 tp.addTriple(Archs[i] + "-" + suffix);
524}
525
526//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000527// Preprocessor Initialization
528//===----------------------------------------------------------------------===//
529
530// FIXME: Preprocessor builtins to support.
531// -A... - Play with #assertions
532// -undef - Undefine all predefined macros
533
534static llvm::cl::list<std::string>
535D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
536 llvm::cl::desc("Predefine the specified macro"));
537static llvm::cl::list<std::string>
538U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
539 llvm::cl::desc("Undefine the specified macro"));
540
Chris Lattner64299f82008-01-10 01:53:41 +0000541static llvm::cl::list<std::string>
542ImplicitIncludes("include", llvm::cl::value_desc("file"),
543 llvm::cl::desc("Include file before parsing"));
544
545
Reid Spencer5f016e22007-07-11 17:01:13 +0000546// Append a #define line to Buf for Macro. Macro should be of the form XXX,
547// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
548// "#define XXX Y z W". To get a #define with no value, use "XXX=".
549static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
550 const char *Command = "#define ") {
551 Buf.insert(Buf.end(), Command, Command+strlen(Command));
552 if (const char *Equal = strchr(Macro, '=')) {
553 // Turn the = into ' '.
554 Buf.insert(Buf.end(), Macro, Equal);
555 Buf.push_back(' ');
556 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
557 } else {
558 // Push "macroname 1".
559 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
560 Buf.push_back(' ');
561 Buf.push_back('1');
562 }
563 Buf.push_back('\n');
564}
565
Chris Lattner64299f82008-01-10 01:53:41 +0000566/// AddImplicitInclude - Add an implicit #include of the specified file to the
567/// predefines buffer.
568static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
569 const char *Inc = "#include \"";
570 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
571 Buf.insert(Buf.end(), File.begin(), File.end());
572 Buf.push_back('"');
573 Buf.push_back('\n');
574}
575
Reid Spencer5f016e22007-07-11 17:01:13 +0000576
Chris Lattner53b0dab2007-10-09 22:10:18 +0000577/// InitializePreprocessor - Initialize the preprocessor getting it and the
578/// environment ready to process a single file. This returns the file ID for the
579/// input file. If a failure happens, it returns 0.
580///
581static unsigned InitializePreprocessor(Preprocessor &PP,
582 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000583 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000584
Chris Lattnerdee73592007-12-15 20:48:40 +0000585 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000586
Chris Lattner53b0dab2007-10-09 22:10:18 +0000587 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000588 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000589 if (InFile != "-") {
590 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000591 if (File) SourceMgr.createMainFileID(File, SourceLocation());
592 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000593 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
594 return 0;
595 }
596 } else {
597 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000598 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
599 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000600 fprintf(stderr, "Error reading standard input! Empty?\n");
601 return 0;
602 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000603 }
604
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 // Add macros from the command line.
606 // FIXME: Should traverse the #define/#undef lists in parallel.
607 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000608 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000609 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000610 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
611
Chris Lattner64299f82008-01-10 01:53:41 +0000612 // FIXME: Read any files specified by -imacros.
613
614 // Add implicit #includes from -include.
615 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
616 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000617
618 // Null terminate PredefinedBuffer and add it.
619 PredefineBuffer.push_back(0);
620 PP.setPredefines(&PredefineBuffer[0]);
621
622 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000623 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000624}
625
626//===----------------------------------------------------------------------===//
627// Preprocessor include path information.
628//===----------------------------------------------------------------------===//
629
630// This tool exports a large number of command line options to control how the
631// preprocessor searches for header files. At root, however, the Preprocessor
632// object takes a very simple interface: a list of directories to search for
633//
634// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000635// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000636//
Chris Lattner64299f82008-01-10 01:53:41 +0000637// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000638
639static llvm::cl::opt<bool>
640nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
641
642// Various command line options. These four add directories to each chain.
643static llvm::cl::list<std::string>
644F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
645 llvm::cl::desc("Add directory to framework include search path"));
646static llvm::cl::list<std::string>
647I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
648 llvm::cl::desc("Add directory to include search path"));
649static llvm::cl::list<std::string>
650idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
651 llvm::cl::desc("Add directory to AFTER include search path"));
652static llvm::cl::list<std::string>
653iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
654 llvm::cl::desc("Add directory to QUOTE include search path"));
655static llvm::cl::list<std::string>
656isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
657 llvm::cl::desc("Add directory to SYSTEM include search path"));
658
659// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
660static llvm::cl::list<std::string>
661iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
662 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
663static llvm::cl::list<std::string>
664iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
665 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
666static llvm::cl::list<std::string>
667iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
668 llvm::cl::Prefix,
669 llvm::cl::desc("Set directory to include search path with prefix"));
670
Chris Lattner0c946412007-08-26 17:47:35 +0000671static llvm::cl::opt<std::string>
672isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
673 llvm::cl::desc("Set the system root directory (usually /)"));
674
Reid Spencer5f016e22007-07-11 17:01:13 +0000675// Finally, implement the code that groks the options above.
676enum IncludeDirGroup {
677 Quoted = 0,
678 Angled,
679 System,
680 After
681};
682
683static std::vector<DirectoryLookup> IncludeGroup[4];
684
685/// AddPath - Add the specified path to the specified group list.
686///
687static void AddPath(const std::string &Path, IncludeDirGroup Group,
688 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000689 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000690 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000691 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000692
Chris Lattnerd6655272007-12-17 05:59:27 +0000693 // Compute the actual path, taking into consideration -isysroot.
694 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000695
Chris Lattnerd6655272007-12-17 05:59:27 +0000696 // Handle isysroot.
697 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000698 // FIXME: Portability. This should be a sys::Path interface, this doesn't
699 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000700 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
701 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 }
703
Chris Lattnerd6655272007-12-17 05:59:27 +0000704 MappedPath.append(Path.begin(), Path.end());
705
706 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 DirectoryLookup::DirType Type;
708 if (Group == Quoted || Group == Angled)
709 Type = DirectoryLookup::NormalHeaderDir;
710 else if (isCXXAware)
711 Type = DirectoryLookup::SystemHeaderDir;
712 else
713 Type = DirectoryLookup::ExternCSystemHeaderDir;
714
Chris Lattnerd6655272007-12-17 05:59:27 +0000715
716 // If the directory exists, add it.
717 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
718 &MappedPath[0]+
719 MappedPath.size())) {
720 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
721 isFramework));
722 return;
723 }
724
Chris Lattnerdf772332007-12-17 07:52:39 +0000725 // Check to see if this is an apple-style headermap (which are not allowed to
726 // be frameworks).
727 if (!isFramework) {
728 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
729 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000730 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
731 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000732 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
733 return;
734 }
Chris Lattner822da612007-12-17 06:36:45 +0000735 }
736 }
737
Chris Lattnerd6655272007-12-17 05:59:27 +0000738 if (Verbose)
739 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000740}
741
742/// RemoveDuplicates - If there are duplicate directory entries in the specified
743/// search list, remove the later (dead) ones.
744static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000745 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000746 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000747 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000749 if (SearchList[i].isNormalDir()) {
750 // If this isn't the first time we've seen this dir, remove it.
751 if (SeenDirs.insert(SearchList[i].getDir()))
752 continue;
753
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 if (Verbose)
755 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
756 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000757 } else if (SearchList[i].isFramework()) {
758 // If this isn't the first time we've seen this framework dir, remove it.
759 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
760 continue;
761
762 if (Verbose)
763 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
764 SearchList[i].getFrameworkDir()->getName());
765
Chris Lattnerb94c7072007-12-17 06:44:29 +0000766 } else {
767 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
768 // If this isn't the first time we've seen this headermap, remove it.
769 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
770 continue;
771
772 if (Verbose)
773 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
774 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000776
777 // This is reached if the current entry is a duplicate.
778 SearchList.erase(SearchList.begin()+i);
779 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 }
781}
782
Chris Lattner5f9eae52008-03-01 08:07:28 +0000783// AddEnvVarPaths - Add a list of paths from an environment variable to a
784// header search list.
785//
786static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
787 const char* at = getenv(Name);
788 if (!at)
789 return;
790
791 const char* delim = strchr(at, llvm::sys::PathSeparator);
792 while (delim != 0) {
793 if (delim-at == 0)
794 AddPath(".", Angled, false, true, false, Headers);
795 else
796 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
797 true, false, Headers);
798 at = delim + 1;
799 delim = strchr(at, llvm::sys::PathSeparator);
800 }
801 if (*at == 0)
802 AddPath(".", Angled, false, true, false, Headers);
803 else
804 AddPath(at, Angled, false, true, false, Headers);
805}
806
Reid Spencer5f016e22007-07-11 17:01:13 +0000807/// InitializeIncludePaths - Process the -I options and set them in the
808/// HeaderSearch object.
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000809static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
810 FileManager &FM, const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 // Handle -F... options.
812 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000813 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000814
815 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000816 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000817 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000818
819 // Handle -idirafter... options.
820 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000821 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000822
823 // Handle -iquote... options.
824 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000825 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000826
827 // Handle -isystem... options.
828 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000829 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000830
831 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
832 // parallel, processing the values in order of occurance to get the right
833 // prefixes.
834 {
835 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
836 unsigned iprefix_idx = 0;
837 unsigned iwithprefix_idx = 0;
838 unsigned iwithprefixbefore_idx = 0;
839 bool iprefix_done = iprefix_vals.empty();
840 bool iwithprefix_done = iwithprefix_vals.empty();
841 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
842 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
843 if (!iprefix_done &&
844 (iwithprefix_done ||
845 iprefix_vals.getPosition(iprefix_idx) <
846 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
847 (iwithprefixbefore_done ||
848 iprefix_vals.getPosition(iprefix_idx) <
849 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
850 Prefix = iprefix_vals[iprefix_idx];
851 ++iprefix_idx;
852 iprefix_done = iprefix_idx == iprefix_vals.size();
853 } else if (!iwithprefix_done &&
854 (iwithprefixbefore_done ||
855 iwithprefix_vals.getPosition(iwithprefix_idx) <
856 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
857 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000858 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000859 ++iwithprefix_idx;
860 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
861 } else {
862 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000863 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 ++iwithprefixbefore_idx;
865 iwithprefixbefore_done =
866 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
867 }
868 }
869 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000870
871 AddEnvVarPaths("CPATH", Headers);
872 if (Lang.CPlusPlus && Lang.ObjC1)
873 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
874 else if (Lang.CPlusPlus)
875 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
876 else if (Lang.ObjC1)
877 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
878 else
879 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
880
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000881 // Add the clang headers, which are relative to the clang driver.
882 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000883 llvm::sys::Path::GetMainExecutable(Argv0,
884 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000885 if (!MainExecutablePath.isEmpty()) {
886 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
887 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
888 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
889 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
890 }
891
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 // FIXME: temporary hack: hard-coded paths.
893 // FIXME: get these from the target?
894 if (!nostdinc) {
895 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000896 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000898 false, Headers);
899 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
900 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000901
902 // Ubuntu 7.10 - Gutsy Gibbon
903 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
904 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
905 false, Headers);
906 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
907 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000908 }
909
Chris Lattner822da612007-12-17 06:36:45 +0000910 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 // leopard
912 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000913 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000915 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
917 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000918 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000919
920 // tiger
921 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000922 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000924 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
926 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000927 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000928
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000929 // Ubuntu 7.10 - Gutsy Gibbon
930 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +0000931 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000932
Chris Lattner822da612007-12-17 06:36:45 +0000933 AddPath("/usr/include", System, false, false, false, Headers);
934 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
935 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 }
937
938 // Now that we have collected all of the include paths, merge them all
939 // together and tell the preprocessor about them.
940
941 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
942 std::vector<DirectoryLookup> SearchList;
943 SearchList = IncludeGroup[Angled];
944 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
945 IncludeGroup[System].end());
946 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
947 IncludeGroup[After].end());
948 RemoveDuplicates(SearchList);
949 RemoveDuplicates(IncludeGroup[Quoted]);
950
951 // Prepend QUOTED list on the search list.
952 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
953 IncludeGroup[Quoted].end());
954
955
956 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
957 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
958 DontSearchCurDir);
959
960 // If verbose, print the list of directories that will be searched.
961 if (Verbose) {
962 fprintf(stderr, "#include \"...\" search starts here:\n");
963 unsigned QuotedIdx = IncludeGroup[Quoted].size();
964 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
965 if (i == QuotedIdx)
966 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000967 const char *Name = SearchList[i].getName();
968 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000969 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000970 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000971 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000972 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000973 else {
974 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000975 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000976 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000977 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 }
Chris Lattner80e17152007-12-15 23:11:06 +0000979 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 }
981}
982
983
Reid Spencer5f016e22007-07-11 17:01:13 +0000984//===----------------------------------------------------------------------===//
985// Basic Parser driver
986//===----------------------------------------------------------------------===//
987
Ted Kremenek95041a22007-12-19 22:51:13 +0000988static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000990 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000991
992 // Parsing the specified input file.
993 P.ParseTranslationUnit();
994 delete PA;
995}
996
997//===----------------------------------------------------------------------===//
998// Main driver
999//===----------------------------------------------------------------------===//
1000
Ted Kremenekdb094a22007-12-05 18:27:04 +00001001/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1002/// action. These consumers can operate on both ASTs that are freshly
1003/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001004static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001005 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001006 const LangOptions& LangOpts,
1007 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001008 switch (ProgAction) {
1009 default:
1010 return NULL;
1011
1012 case ASTPrint:
1013 return CreateASTPrinter();
1014
1015 case ASTDump:
1016 return CreateASTDumper();
1017
1018 case ASTView:
1019 return CreateASTViewer();
1020
1021 case ParseCFGDump:
1022 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001023 return CreateCFGDumper(ProgAction == ParseCFGView,
1024 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001025
1026 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001027 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001028
1029 case WarnDeadStores:
1030 return CreateDeadStoreChecker(Diag);
1031
1032 case WarnUninitVals:
1033 return CreateUnitValsChecker(Diag);
1034
Ted Kremeneke01c9872008-02-14 22:36:46 +00001035 case AnalysisGRSimpleVals:
Ted Kremenekcb330932008-02-18 21:21:23 +00001036 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction);
Ted Kremeneke603df42008-01-08 18:04:06 +00001037
Ted Kremenekd55fe522008-02-15 00:35:38 +00001038 case AnalysisGRSimpleValsView:
Ted Kremenekcb330932008-02-18 21:21:23 +00001039 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, true);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001040
Ted Kremenekdb094a22007-12-05 18:27:04 +00001041 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001042 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001043
1044 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001045 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001046 DestModule = new llvm::Module(InFile);
1047 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001048
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001049 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001050 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001051 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001052
Ted Kremenekdb094a22007-12-05 18:27:04 +00001053 case RewriteTest:
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +00001054 return CreateCodeRewriterTest(InFile, Diag);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001055 }
1056}
1057
Reid Spencer5f016e22007-07-11 17:01:13 +00001058/// ProcessInputFile - Process a single input file with the specified state.
1059///
Ted Kremenek7dcc9682007-12-19 22:32:34 +00001060static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +00001061 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001062
1063 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001064 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001065 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001066
Reid Spencer5f016e22007-07-11 17:01:13 +00001067 switch (ProgAction) {
1068 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001069 Consumer = CreateASTConsumer(InFile,
1070 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001071 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001072 PP.getLangOptions(),
1073 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001074
1075 if (!Consumer) {
1076 fprintf(stderr, "Unexpected program action!\n");
1077 return;
1078 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001079
Ted Kremenekdb094a22007-12-05 18:27:04 +00001080 break;
1081
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001083 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001084 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001085 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 do {
1087 PP.Lex(Tok);
1088 PP.DumpToken(Tok, true);
1089 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001090 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001091 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 break;
1093 }
1094 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001095 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001096 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001097 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001098 do {
1099 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001100 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001101 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001102 break;
1103 }
1104
1105 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001106 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001107 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 break;
1109
1110 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001111 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001112 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 break;
1114
1115 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001116 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001117 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001119
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001120 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001121 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001122 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001123 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001124
1125 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001126 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001127 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001128
1129 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001130 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001132
1133 // If running the code generator, finish up now.
1134 if (CodeGenModule) {
1135 std::ostream *Out;
1136 if (OutputFile == "-") {
1137 Out = llvm::cout.stream();
1138 } else if (!OutputFile.empty()) {
1139 Out = new std::ofstream(OutputFile.c_str(),
1140 std::ios_base::binary|std::ios_base::out);
1141 } else if (InFile == "-") {
1142 Out = llvm::cout.stream();
1143 } else {
1144 llvm::sys::Path Path(InFile);
1145 Path.eraseSuffix();
1146 if (ProgAction == EmitLLVM)
1147 Path.appendSuffix("ll");
1148 else if (ProgAction == EmitBC)
1149 Path.appendSuffix("bc");
1150 else
1151 assert(0 && "Unknown action");
1152 Out = new std::ofstream(Path.toString().c_str(),
1153 std::ios_base::binary|std::ios_base::out);
1154 }
1155
1156 if (ProgAction == EmitLLVM) {
1157 CodeGenModule->print(*Out);
1158 } else {
1159 assert(ProgAction == EmitBC);
1160 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1161 }
1162
1163 if (Out != llvm::cout.stream())
1164 delete Out;
1165 delete CodeGenModule;
1166 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001167
1168 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001169 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001170 PP.PrintStats();
1171 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001172 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001173 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001174 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 fprintf(stderr, "\n");
1176 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001177
1178 // For a multi-file compilation, some things are ok with nuking the source
1179 // manager tables, other require stable fileid/macroid's across multiple
1180 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001181 if (ClearSourceMgr)
1182 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001183}
1184
Ted Kremenek20e97482007-12-12 23:41:08 +00001185static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1186 FileManager& FileMgr) {
1187
1188 if (VerifyDiagnostics) {
1189 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1190 exit (1);
1191 }
1192
1193 llvm::sys::Path Filename(InFile);
1194
1195 if (!Filename.isValid()) {
1196 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1197 exit (1);
1198 }
1199
Ted Kremenekee533642007-12-20 19:47:16 +00001200 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001201
1202 if (!TU) {
1203 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1204 InFile.c_str());
1205 exit (1);
1206 }
1207
Ted Kremenek63ea8632007-12-19 19:27:38 +00001208 // Observe that we use the source file name stored in the deserialized
1209 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001210 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001211 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001212 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1213 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001214
1215 if (!Consumer) {
1216 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1217 exit (1);
1218 }
1219
Ted Kremenek95041a22007-12-19 22:51:13 +00001220 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001221
Chris Lattnere66b65c2008-02-06 01:42:25 +00001222 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001223 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1224 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001225}
1226
1227
Reid Spencer5f016e22007-07-11 17:01:13 +00001228static llvm::cl::list<std::string>
1229InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1230
Ted Kremenek20e97482007-12-12 23:41:08 +00001231static bool isSerializedFile(const std::string& InFile) {
1232 if (InFile.size() < 4)
1233 return false;
1234
1235 const char* s = InFile.c_str()+InFile.size()-4;
1236
1237 return s[0] == '.' &&
1238 s[1] == 'a' &&
1239 s[2] == 's' &&
1240 s[3] == 't';
1241}
1242
Reid Spencer5f016e22007-07-11 17:01:13 +00001243
1244int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001245 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 llvm::sys::PrintStackTraceOnErrorSignal();
1247
1248 // If no input was specified, read from stdin.
1249 if (InputFilenames.empty())
1250 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001251
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 // Create a file manager object to provide access to and cache the filesystem.
1253 FileManager FileMgr;
1254
Ted Kremenek31e703b2007-12-11 23:28:38 +00001255 // Create the diagnostic client for reporting errors or for
1256 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001258 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001260 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 } else {
1262 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001263 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001264
1265 if (InputFilenames.size() != 1) {
1266 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001267 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001268 return 1;
1269 }
1270 }
1271
1272 // Configure our handling of diagnostics.
1273 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001274 InitializeDiagnostics(Diags);
1275
Chris Lattner4f037832007-12-05 23:24:17 +00001276 // -I- is a deprecated GCC feature, scan for it and reject it.
1277 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1278 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001279 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001280 I_dirs.erase(I_dirs.begin()+i);
1281 --i;
1282 }
1283 }
1284
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001286 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001287
Ted Kremenek20e97482007-12-12 23:41:08 +00001288 if (isSerializedFile(InFile))
1289 ProcessSerializedFile(InFile,Diags,FileMgr);
1290 else {
1291 /// Create a SourceManager object. This tracks and owns all the file
1292 /// buffers allocated to a translation unit.
1293 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001294
Ted Kremenek20e97482007-12-12 23:41:08 +00001295 // Initialize language options, inferring file types from input filenames.
1296 LangOptions LangInfo;
1297 InitializeBaseLanguage();
1298 LangKind LK = GetLanguage(InFile);
1299 InitializeLangOptions(LangInfo, LK);
1300 InitializeLanguageStandard(LangInfo, LK);
1301
1302 // Process the -I options and set them in the HeaderInfo.
1303 HeaderSearch HeaderInfo(FileMgr);
1304 DiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001305 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001306
1307 // Get information about the targets being compiled for. Note that this
1308 // pointer and the TargetInfoImpl objects are never deleted by this toy
1309 // driver.
1310 TargetInfo *Target;
1311
1312 // Create triples, and create the TargetInfo.
1313 std::vector<std::string> triples;
1314 CreateTargetTriples(triples);
1315 Target = TargetInfo::CreateTargetInfo(&triples[0],
1316 &triples[0]+triples.size(),
1317 &Diags);
1318
1319 if (Target == 0) {
1320 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1321 triples[0].c_str());
1322 fprintf(stderr, "Please use -triple or -arch.\n");
1323 exit(1);
1324 }
1325
1326 // Set up the preprocessor with these options.
1327 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1328
1329 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001330 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001331 continue;
1332
Ted Kremenek1036b682007-12-19 23:48:45 +00001333 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001334 HeaderInfo.ClearFileInfo();
1335
1336 if (Stats)
1337 SourceMgr.PrintStats();
1338 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 }
1340
1341 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1342
1343 if (NumDiagnostics)
1344 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1345 (NumDiagnostics == 1 ? "" : "s"));
1346
1347 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 FileMgr.PrintStats();
1349 fprintf(stderr, "\n");
1350 }
1351
Chris Lattner96f1a642007-07-21 05:40:53 +00001352 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001353}