blob: 6c82f195722fde0c68278611a26582053fe4cee8 [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 Kremenek88f5cde2008-03-27 06:17:42 +000029#include "HTMLDiagnostics.h"
30#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000031#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000032#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000033#include "clang/Sema/ParseAST.h"
Chris Lattner556beb72007-09-15 22:56:56 +000034#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "clang/Parse/Parser.h"
36#include "clang/Lex/HeaderSearch.h"
37#include "clang/Basic/FileManager.h"
38#include "clang/Basic/SourceManager.h"
39#include "clang/Basic/TargetInfo.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000040#include "llvm/Module.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000041#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000042#include "llvm/Bitcode/ReaderWriter.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/MemoryBuffer.h"
45#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000046#include "llvm/Config/config.h"
Ted Kremenekee533642007-12-20 19:47:16 +000047#include "llvm/ADT/OwningPtr.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000048#include "llvm/System/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include <memory>
Chris Lattnere66b65c2008-02-06 01:42:25 +000050#include <fstream>
Reid Spencer5f016e22007-07-11 17:01:13 +000051using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// Global options.
55//===----------------------------------------------------------------------===//
56
57static llvm::cl::opt<bool>
58Verbose("v", llvm::cl::desc("Enable verbose output"));
59static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000060Stats("print-stats",
61 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000062
63enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 RewriteTest, // Rewriter testing stuff.
Ted Kremenek13e479b2008-03-19 07:53:42 +000065 HTMLTest, // HTML displayer testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000066 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000067 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000068 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000069 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000070 ASTPrint, // Parse ASTs and print them.
71 ASTDump, // Parse ASTs and dump them.
72 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000073 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000074 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000075 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenekd55fe522008-02-15 00:35:38 +000076 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
77 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek2fff37e2008-03-06 00:08:09 +000078 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremenek055c2752007-09-06 23:00:42 +000079 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000080 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000081 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000082 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000083 ParsePrintCallbacks, // Parse and print each callback.
84 ParseSyntaxOnly, // Parse and perform semantic analysis.
85 ParseNoop, // Parse with noop callbacks.
86 RunPreprocessorOnly, // Just lex, no output.
87 PrintPreprocessedInput, // -E mode.
88 DumpTokens // Token dump mode.
89};
90
91static llvm::cl::opt<ProgActions>
92ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
93 llvm::cl::init(ParseSyntaxOnly),
94 llvm::cl::values(
95 clEnumValN(RunPreprocessorOnly, "Eonly",
96 "Just run preprocessor, no output (for timings)"),
97 clEnumValN(PrintPreprocessedInput, "E",
98 "Run preprocessor, emit preprocessed file"),
99 clEnumValN(DumpTokens, "dumptokens",
100 "Run preprocessor, dump internal rep of tokens"),
101 clEnumValN(ParseNoop, "parse-noop",
102 "Run parser with noop callbacks (for timings)"),
103 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
104 "Run parser and perform semantic analysis"),
105 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
106 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000107 clEnumValN(EmitHTML, "emit-html",
108 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000109 clEnumValN(ASTPrint, "ast-print",
110 "Build ASTs and then pretty-print them"),
111 clEnumValN(ASTDump, "ast-dump",
112 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000113 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000114 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000115 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000116 "Run parser, then build and print CFGs."),
117 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000118 "Run parser, then build and view CFGs with Graphviz."),
119 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000120 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000121 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000122 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000123 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000124 "Flag warnings of uses of unitialized variables."),
Ted Kremeneke01c9872008-02-14 22:36:46 +0000125 clEnumValN(AnalysisGRSimpleVals, "grsimple",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000126 "Perform path-sensitive constant propagation."),
Ted Kremenekd55fe522008-02-15 00:35:38 +0000127 clEnumValN(AnalysisGRSimpleValsView, "grsimple-view",
128 "View results of path-sensitive constant propagation."),
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000129 clEnumValN(CheckerCFRef, "check-cfref",
130 "Run the Core Foundation reference count checker."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000131 clEnumValN(TestSerialization, "test-pickling",
Chris Lattnerf3dabbd2008-03-09 05:25:01 +0000132 "Run prototype serialization code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000133 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000134 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000135 clEnumValN(EmitBC, "emit-llvm-bc",
136 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000137 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000138 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000139 clEnumValN(RewriteTest, "rewrite-test",
140 "Playground for the code rewriter"),
Ted Kremenek13e479b2008-03-19 07:53:42 +0000141 clEnumValN(HTMLTest, "html-test",
142 "Playground for the HTML displayer"),
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000143
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 clEnumValEnd));
145
Ted Kremenekccc76472007-12-19 19:47:59 +0000146
147static llvm::cl::opt<std::string>
148OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000149 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000150 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
151
Ted Kremenek41193e42007-09-26 19:42:19 +0000152static llvm::cl::opt<bool>
153VerifyDiagnostics("verify",
154 llvm::cl::desc("Verify emitted diagnostics and warnings."));
155
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000156static llvm::cl::opt<std::string>
157HTMLDiag("html-diags",
158 llvm::cl::desc("Generate HTML to report diagnostics"),
159 llvm::cl::value_desc("HTML directory"));
160
Reid Spencer5f016e22007-07-11 17:01:13 +0000161//===----------------------------------------------------------------------===//
162// Language Options
163//===----------------------------------------------------------------------===//
164
165enum LangKind {
166 langkind_unspecified,
167 langkind_c,
168 langkind_c_cpp,
169 langkind_cxx,
170 langkind_cxx_cpp,
171 langkind_objc,
172 langkind_objc_cpp,
173 langkind_objcxx,
174 langkind_objcxx_cpp
175};
176
177/* TODO: GCC also accepts:
178 c-header c++-header objective-c-header objective-c++-header
179 assembler assembler-with-cpp
180 ada, f77*, ratfor (!), f95, java, treelang
181 */
182static llvm::cl::opt<LangKind>
183BaseLang("x", llvm::cl::desc("Base language to compile"),
184 llvm::cl::init(langkind_unspecified),
185 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
186 clEnumValN(langkind_cxx, "c++", "C++"),
187 clEnumValN(langkind_objc, "objective-c", "Objective C"),
188 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
189 clEnumValN(langkind_c_cpp, "c-cpp-output",
190 "Preprocessed C"),
191 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
192 "Preprocessed C++"),
193 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
194 "Preprocessed Objective C"),
195 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
196 "Preprocessed Objective C++"),
197 clEnumValEnd));
198
199static llvm::cl::opt<bool>
200LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
201 llvm::cl::Hidden);
202static llvm::cl::opt<bool>
203LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
204 llvm::cl::Hidden);
205
Ted Kremenek8904f152007-12-05 23:49:08 +0000206/// InitializeBaseLanguage - Handle the -x foo options.
207static void InitializeBaseLanguage() {
208 if (LangObjC)
209 BaseLang = langkind_objc;
210 else if (LangObjCXX)
211 BaseLang = langkind_objcxx;
212}
213
214static LangKind GetLanguage(const std::string &Filename) {
215 if (BaseLang != langkind_unspecified)
216 return BaseLang;
217
218 std::string::size_type DotPos = Filename.rfind('.');
219
220 if (DotPos == std::string::npos) {
221 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000222 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000223 }
224
Ted Kremenek8904f152007-12-05 23:49:08 +0000225 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
226 // C header: .h
227 // C++ header: .hh or .H;
228 // assembler no preprocessing: .s
229 // assembler: .S
230 if (Ext == "c")
231 return langkind_c;
232 else if (Ext == "i")
233 return langkind_c_cpp;
234 else if (Ext == "ii")
235 return langkind_cxx_cpp;
236 else if (Ext == "m")
237 return langkind_objc;
238 else if (Ext == "mi")
239 return langkind_objc_cpp;
240 else if (Ext == "mm" || Ext == "M")
241 return langkind_objcxx;
242 else if (Ext == "mii")
243 return langkind_objcxx_cpp;
244 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
245 Ext == "c++" || Ext == "cp" || Ext == "cxx")
246 return langkind_cxx;
247 else
248 return langkind_c;
249}
250
251
252static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 // FIXME: implement -fpreprocessed mode.
254 bool NoPreprocess = false;
255
Ted Kremenek8904f152007-12-05 23:49:08 +0000256 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 default: assert(0 && "Unknown language kind!");
258 case langkind_c_cpp:
259 NoPreprocess = true;
260 // FALLTHROUGH
261 case langkind_c:
262 break;
263 case langkind_cxx_cpp:
264 NoPreprocess = true;
265 // FALLTHROUGH
266 case langkind_cxx:
267 Options.CPlusPlus = 1;
268 break;
269 case langkind_objc_cpp:
270 NoPreprocess = true;
271 // FALLTHROUGH
272 case langkind_objc:
273 Options.ObjC1 = Options.ObjC2 = 1;
274 break;
275 case langkind_objcxx_cpp:
276 NoPreprocess = true;
277 // FALLTHROUGH
278 case langkind_objcxx:
279 Options.ObjC1 = Options.ObjC2 = 1;
280 Options.CPlusPlus = 1;
281 break;
282 }
283}
284
285/// LangStds - Language standards we support.
286enum LangStds {
287 lang_unspecified,
288 lang_c89, lang_c94, lang_c99,
289 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000290 lang_cxx98, lang_gnucxx98,
291 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000292};
293
294static llvm::cl::opt<LangStds>
295LangStd("std", llvm::cl::desc("Language standard to compile for"),
296 llvm::cl::init(lang_unspecified),
297 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
298 clEnumValN(lang_c89, "c90", "ISO C 1990"),
299 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
300 clEnumValN(lang_c94, "iso9899:199409",
301 "ISO C 1990 with amendment 1"),
302 clEnumValN(lang_c99, "c99", "ISO C 1999"),
303// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
304 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
305// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
306 clEnumValN(lang_gnu89, "gnu89",
307 "ISO C 1990 with GNU extensions (default for C)"),
308 clEnumValN(lang_gnu99, "gnu99",
309 "ISO C 1999 with GNU extensions"),
310 clEnumValN(lang_gnu99, "gnu9x",
311 "ISO C 1999 with GNU extensions"),
312 clEnumValN(lang_cxx98, "c++98",
313 "ISO C++ 1998 with amendments"),
314 clEnumValN(lang_gnucxx98, "gnu++98",
315 "ISO C++ 1998 with amendments and GNU "
316 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000317 clEnumValN(lang_cxx0x, "c++0x",
318 "Upcoming ISO C++ 200x with amendments"),
319 clEnumValN(lang_gnucxx0x, "gnu++0x",
320 "Upcoming ISO C++ 200x with amendments and GNU "
321 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 clEnumValEnd));
323
324static llvm::cl::opt<bool>
325NoOperatorNames("fno-operator-names",
326 llvm::cl::desc("Do not treat C++ operator name keywords as "
327 "synonyms for operators"));
328
Anders Carlssonee98ac52007-10-15 02:50:23 +0000329static llvm::cl::opt<bool>
330PascalStrings("fpascal-strings",
331 llvm::cl::desc("Recognize and construct Pascal-style "
332 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000333
334static llvm::cl::opt<bool>
335MSExtensions("fms-extensions",
336 llvm::cl::desc("Accept some non-standard constructs used in "
337 "Microsoft header files. "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000338
339static llvm::cl::opt<bool>
340WritableStrings("fwritable-strings",
341 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000342
343static llvm::cl::opt<bool>
344LaxVectorConversions("flax-vector-conversions",
345 llvm::cl::desc("Allow implicit conversions between vectors"
346 " with a different number of elements or "
347 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000348// FIXME: add:
349// -ansi
350// -trigraphs
351// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000352// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000353static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 if (LangStd == lang_unspecified) {
355 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000356 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 default: assert(0 && "Unknown base language");
358 case langkind_c:
359 case langkind_c_cpp:
360 case langkind_objc:
361 case langkind_objc_cpp:
362 LangStd = lang_gnu99;
363 break;
364 case langkind_cxx:
365 case langkind_cxx_cpp:
366 case langkind_objcxx:
367 case langkind_objcxx_cpp:
368 LangStd = lang_gnucxx98;
369 break;
370 }
371 }
372
373 switch (LangStd) {
374 default: assert(0 && "Unknown language standard!");
375
376 // Fall through from newer standards to older ones. This isn't really right.
377 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000378 case lang_gnucxx0x:
379 case lang_cxx0x:
380 Options.CPlusPlus0x = 1;
381 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 case lang_gnucxx98:
383 case lang_cxx98:
384 Options.CPlusPlus = 1;
385 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000386 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // FALL THROUGH.
388 case lang_gnu99:
389 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 Options.C99 = 1;
391 Options.HexFloats = 1;
392 // FALL THROUGH.
393 case lang_gnu89:
394 Options.BCPLComment = 1; // Only for C99/C++.
395 // FALL THROUGH.
396 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000397 Options.Digraphs = 1; // C94, C99, C++.
398 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 case lang_c89:
400 break;
401 }
402
Chris Lattnerd658b562008-04-05 06:32:51 +0000403 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
404 Options.ImplicitInt = 1;
405 else
406 Options.ImplicitInt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 Options.Trigraphs = 1; // -trigraphs or -ansi
408 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000409 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000410 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000411 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000412 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000413}
414
415//===----------------------------------------------------------------------===//
416// Our DiagnosticClient implementation
417//===----------------------------------------------------------------------===//
418
419// FIXME: Werror should take a list of things, -Werror=foo,bar
420static llvm::cl::opt<bool>
421WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
422
423static llvm::cl::opt<bool>
424WarnOnExtensions("pedantic", llvm::cl::init(false),
425 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
426
427static llvm::cl::opt<bool>
428ErrorOnExtensions("pedantic-errors",
429 llvm::cl::desc("Issue an error on uses of GCC extensions"));
430
431static llvm::cl::opt<bool>
432WarnUnusedMacros("Wunused_macros",
433 llvm::cl::desc("Warn for unused macros in the main translation unit"));
434
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000435static llvm::cl::opt<bool>
436WarnFloatEqual("Wfloat-equal",
437 llvm::cl::desc("Warn about equality comparisons of floating point values."));
438
Ted Kremenek73da5902007-12-17 17:50:07 +0000439static llvm::cl::opt<bool>
440WarnNoFormatNonLiteral("Wno-format-nonliteral",
441 llvm::cl::desc("Do not warn about non-literal format strings."));
442
Chris Lattner116a4b12008-01-23 17:19:46 +0000443static llvm::cl::opt<bool>
444WarnUndefMacros("Wundef",
445 llvm::cl::desc("Warn on use of undefined macros in #if's"));
446
447
Reid Spencer5f016e22007-07-11 17:01:13 +0000448/// InitializeDiagnostics - Initialize the diagnostic object, based on the
449/// current command line option settings.
450static void InitializeDiagnostics(Diagnostic &Diags) {
451 Diags.setWarningsAsErrors(WarningsAsErrors);
452 Diags.setWarnOnExtensions(WarnOnExtensions);
453 Diags.setErrorOnExtensions(ErrorOnExtensions);
454
455 // Silence the "macro is not used" warning unless requested.
456 if (!WarnUnusedMacros)
457 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000458
459 // Silence "floating point comparison" warnings unless requested.
460 if (!WarnFloatEqual)
461 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000462
463 // Silence "format string is not a string literal" warnings if requested
464 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000465 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
466 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000467 if (!WarnUndefMacros)
468 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000469
470 if (MSExtensions) // MS allows unnamed struct/union fields.
471 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000472}
473
474//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000475// Analysis-specific options.
476//===----------------------------------------------------------------------===//
477
478static llvm::cl::opt<std::string>
479AnalyzeSpecificFunction("analyze-function",
480 llvm::cl::desc("Run analysis on specific function."));
481
Ted Kremenekffe0f432008-03-07 22:58:01 +0000482static llvm::cl::opt<bool>
483TrimGraph("trim-path-graph",
484 llvm::cl::desc("Only show error-related paths in the analysis graph."));
485
486
Ted Kremenekcb330932008-02-18 21:21:23 +0000487//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000488// Target Triple Processing.
489//===----------------------------------------------------------------------===//
490
491static llvm::cl::opt<std::string>
492TargetTriple("triple",
493 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
494
Chris Lattner42e67372008-03-05 01:18:20 +0000495static llvm::cl::opt<std::string>
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000496Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)."));
Ted Kremenekae360762007-12-03 22:06:55 +0000497
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000498static std::string CreateTargetTriple() {
Ted Kremenekae360762007-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 Lattner6590d212007-12-12 05:01:48 +0000501 std::string Triple = TargetTriple;
502 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000503
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000504 // If -arch foo was specified, remove the architecture from the triple we have
505 // so far and replace it with the specified one.
506 if (Arch.empty())
507 return Triple;
508
Ted Kremenekae360762007-12-03 22:06:55 +0000509 // Decompose the base triple into "arch" and suffix.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000510 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000511
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000512 if (FirstDashIdx == std::string::npos) {
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000513 fprintf(stderr,
514 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000515 Triple.c_str());
516 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000517 }
Ted Kremenekae360762007-12-03 22:06:55 +0000518
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000519 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenekae360762007-12-03 22:06:55 +0000520}
521
522//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000523// Preprocessor Initialization
524//===----------------------------------------------------------------------===//
525
526// FIXME: Preprocessor builtins to support.
527// -A... - Play with #assertions
528// -undef - Undefine all predefined macros
529
530static llvm::cl::list<std::string>
531D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
532 llvm::cl::desc("Predefine the specified macro"));
533static llvm::cl::list<std::string>
534U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
535 llvm::cl::desc("Undefine the specified macro"));
536
Chris Lattner64299f82008-01-10 01:53:41 +0000537static llvm::cl::list<std::string>
538ImplicitIncludes("include", llvm::cl::value_desc("file"),
539 llvm::cl::desc("Include file before parsing"));
540
541
Reid Spencer5f016e22007-07-11 17:01:13 +0000542// Append a #define line to Buf for Macro. Macro should be of the form XXX,
543// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
544// "#define XXX Y z W". To get a #define with no value, use "XXX=".
545static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
546 const char *Command = "#define ") {
547 Buf.insert(Buf.end(), Command, Command+strlen(Command));
548 if (const char *Equal = strchr(Macro, '=')) {
549 // Turn the = into ' '.
550 Buf.insert(Buf.end(), Macro, Equal);
551 Buf.push_back(' ');
552 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
553 } else {
554 // Push "macroname 1".
555 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
556 Buf.push_back(' ');
557 Buf.push_back('1');
558 }
559 Buf.push_back('\n');
560}
561
Chris Lattner64299f82008-01-10 01:53:41 +0000562/// AddImplicitInclude - Add an implicit #include of the specified file to the
563/// predefines buffer.
564static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
565 const char *Inc = "#include \"";
566 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
567 Buf.insert(Buf.end(), File.begin(), File.end());
568 Buf.push_back('"');
569 Buf.push_back('\n');
570}
571
Reid Spencer5f016e22007-07-11 17:01:13 +0000572
Chris Lattner53b0dab2007-10-09 22:10:18 +0000573/// InitializePreprocessor - Initialize the preprocessor getting it and the
574/// environment ready to process a single file. This returns the file ID for the
575/// input file. If a failure happens, it returns 0.
576///
577static unsigned InitializePreprocessor(Preprocessor &PP,
578 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000579 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000580
Chris Lattnerdee73592007-12-15 20:48:40 +0000581 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000582
Chris Lattner53b0dab2007-10-09 22:10:18 +0000583 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000584 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000585 if (InFile != "-") {
586 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000587 if (File) SourceMgr.createMainFileID(File, SourceLocation());
588 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000589 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
590 return 0;
591 }
592 } else {
593 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000594 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
595 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000596 fprintf(stderr, "Error reading standard input! Empty?\n");
597 return 0;
598 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000599 }
600
Reid Spencer5f016e22007-07-11 17:01:13 +0000601 // Add macros from the command line.
602 // FIXME: Should traverse the #define/#undef lists in parallel.
603 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000604 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000606 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
607
Chris Lattner64299f82008-01-10 01:53:41 +0000608 // FIXME: Read any files specified by -imacros.
609
610 // Add implicit #includes from -include.
611 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
612 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000613
614 // Null terminate PredefinedBuffer and add it.
615 PredefineBuffer.push_back(0);
616 PP.setPredefines(&PredefineBuffer[0]);
617
618 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000619 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000620}
621
622//===----------------------------------------------------------------------===//
623// Preprocessor include path information.
624//===----------------------------------------------------------------------===//
625
626// This tool exports a large number of command line options to control how the
627// preprocessor searches for header files. At root, however, the Preprocessor
628// object takes a very simple interface: a list of directories to search for
629//
630// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000631// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000632//
Chris Lattner64299f82008-01-10 01:53:41 +0000633// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000634
635static llvm::cl::opt<bool>
636nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
637
638// Various command line options. These four add directories to each chain.
639static llvm::cl::list<std::string>
640F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
641 llvm::cl::desc("Add directory to framework include search path"));
642static llvm::cl::list<std::string>
643I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
644 llvm::cl::desc("Add directory to include search path"));
645static llvm::cl::list<std::string>
646idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
647 llvm::cl::desc("Add directory to AFTER include search path"));
648static llvm::cl::list<std::string>
649iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
650 llvm::cl::desc("Add directory to QUOTE include search path"));
651static llvm::cl::list<std::string>
652isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
653 llvm::cl::desc("Add directory to SYSTEM include search path"));
654
655// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
656static llvm::cl::list<std::string>
657iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
658 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
659static llvm::cl::list<std::string>
660iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
661 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
662static llvm::cl::list<std::string>
663iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
664 llvm::cl::Prefix,
665 llvm::cl::desc("Set directory to include search path with prefix"));
666
Chris Lattner0c946412007-08-26 17:47:35 +0000667static llvm::cl::opt<std::string>
668isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
669 llvm::cl::desc("Set the system root directory (usually /)"));
670
Reid Spencer5f016e22007-07-11 17:01:13 +0000671// Finally, implement the code that groks the options above.
672enum IncludeDirGroup {
673 Quoted = 0,
674 Angled,
675 System,
676 After
677};
678
679static std::vector<DirectoryLookup> IncludeGroup[4];
680
681/// AddPath - Add the specified path to the specified group list.
682///
683static void AddPath(const std::string &Path, IncludeDirGroup Group,
684 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000685 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000686 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000687 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000688
Chris Lattnerd6655272007-12-17 05:59:27 +0000689 // Compute the actual path, taking into consideration -isysroot.
690 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000691
Chris Lattnerd6655272007-12-17 05:59:27 +0000692 // Handle isysroot.
693 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000694 // FIXME: Portability. This should be a sys::Path interface, this doesn't
695 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000696 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
697 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000698 }
699
Chris Lattnerd6655272007-12-17 05:59:27 +0000700 MappedPath.append(Path.begin(), Path.end());
701
702 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 DirectoryLookup::DirType Type;
704 if (Group == Quoted || Group == Angled)
705 Type = DirectoryLookup::NormalHeaderDir;
706 else if (isCXXAware)
707 Type = DirectoryLookup::SystemHeaderDir;
708 else
709 Type = DirectoryLookup::ExternCSystemHeaderDir;
710
Chris Lattnerd6655272007-12-17 05:59:27 +0000711
712 // If the directory exists, add it.
713 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
714 &MappedPath[0]+
715 MappedPath.size())) {
716 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
717 isFramework));
718 return;
719 }
720
Chris Lattnerdf772332007-12-17 07:52:39 +0000721 // Check to see if this is an apple-style headermap (which are not allowed to
722 // be frameworks).
723 if (!isFramework) {
724 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
725 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000726 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
727 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000728 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
729 return;
730 }
Chris Lattner822da612007-12-17 06:36:45 +0000731 }
732 }
733
Chris Lattnerd6655272007-12-17 05:59:27 +0000734 if (Verbose)
735 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000736}
737
738/// RemoveDuplicates - If there are duplicate directory entries in the specified
739/// search list, remove the later (dead) ones.
740static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000741 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000742 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000743 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000745 if (SearchList[i].isNormalDir()) {
746 // If this isn't the first time we've seen this dir, remove it.
747 if (SeenDirs.insert(SearchList[i].getDir()))
748 continue;
749
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 if (Verbose)
751 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
752 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000753 } else if (SearchList[i].isFramework()) {
754 // If this isn't the first time we've seen this framework dir, remove it.
755 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
756 continue;
757
758 if (Verbose)
759 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
760 SearchList[i].getFrameworkDir()->getName());
761
Chris Lattnerb94c7072007-12-17 06:44:29 +0000762 } else {
763 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
764 // If this isn't the first time we've seen this headermap, remove it.
765 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
766 continue;
767
768 if (Verbose)
769 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
770 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000771 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000772
773 // This is reached if the current entry is a duplicate.
774 SearchList.erase(SearchList.begin()+i);
775 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000776 }
777}
778
Chris Lattner5f9eae52008-03-01 08:07:28 +0000779// AddEnvVarPaths - Add a list of paths from an environment variable to a
780// header search list.
781//
782static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
783 const char* at = getenv(Name);
784 if (!at)
785 return;
786
787 const char* delim = strchr(at, llvm::sys::PathSeparator);
788 while (delim != 0) {
789 if (delim-at == 0)
790 AddPath(".", Angled, false, true, false, Headers);
791 else
792 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
793 true, false, Headers);
794 at = delim + 1;
795 delim = strchr(at, llvm::sys::PathSeparator);
796 }
797 if (*at == 0)
798 AddPath(".", Angled, false, true, false, Headers);
799 else
800 AddPath(at, Angled, false, true, false, Headers);
801}
802
Reid Spencer5f016e22007-07-11 17:01:13 +0000803/// InitializeIncludePaths - Process the -I options and set them in the
804/// HeaderSearch object.
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000805static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
806 FileManager &FM, const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000807 // Handle -F... options.
808 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000809 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000810
811 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000812 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000813 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000814
815 // Handle -idirafter... options.
816 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000817 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000818
819 // Handle -iquote... options.
820 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000821 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000822
823 // Handle -isystem... options.
824 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000825 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000826
827 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
828 // parallel, processing the values in order of occurance to get the right
829 // prefixes.
830 {
831 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
832 unsigned iprefix_idx = 0;
833 unsigned iwithprefix_idx = 0;
834 unsigned iwithprefixbefore_idx = 0;
835 bool iprefix_done = iprefix_vals.empty();
836 bool iwithprefix_done = iwithprefix_vals.empty();
837 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
838 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
839 if (!iprefix_done &&
840 (iwithprefix_done ||
841 iprefix_vals.getPosition(iprefix_idx) <
842 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
843 (iwithprefixbefore_done ||
844 iprefix_vals.getPosition(iprefix_idx) <
845 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
846 Prefix = iprefix_vals[iprefix_idx];
847 ++iprefix_idx;
848 iprefix_done = iprefix_idx == iprefix_vals.size();
849 } else if (!iwithprefix_done &&
850 (iwithprefixbefore_done ||
851 iwithprefix_vals.getPosition(iwithprefix_idx) <
852 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
853 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000854 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000855 ++iwithprefix_idx;
856 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
857 } else {
858 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000859 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 ++iwithprefixbefore_idx;
861 iwithprefixbefore_done =
862 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
863 }
864 }
865 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000866
867 AddEnvVarPaths("CPATH", Headers);
868 if (Lang.CPlusPlus && Lang.ObjC1)
869 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
870 else if (Lang.CPlusPlus)
871 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
872 else if (Lang.ObjC1)
873 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
874 else
875 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
876
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000877 // Add the clang headers, which are relative to the clang driver.
878 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000879 llvm::sys::Path::GetMainExecutable(Argv0,
880 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000881 if (!MainExecutablePath.isEmpty()) {
882 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
883 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
884 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
885 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
886 }
887
Reid Spencer5f016e22007-07-11 17:01:13 +0000888 // FIXME: temporary hack: hard-coded paths.
889 // FIXME: get these from the target?
890 if (!nostdinc) {
891 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000892 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000893 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000894 false, Headers);
895 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
896 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000897
898 // Ubuntu 7.10 - Gutsy Gibbon
899 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
900 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
901 false, Headers);
902 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
903 Headers);
Chris Lattner04421082008-04-08 04:40:51 +0000904
905 // Fedora 8
906 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
907 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false, false, Headers);
908 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 }
910
Chris Lattner822da612007-12-17 06:36:45 +0000911 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 // leopard
913 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000914 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000915 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000916 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
918 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000919 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000920
921 // tiger
922 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000923 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000924 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000925 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
927 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000928 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000929
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000930 // Ubuntu 7.10 - Gutsy Gibbon
931 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +0000932 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000933
Chris Lattner04421082008-04-08 04:40:51 +0000934 // Fedora 8
935 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
936 false, false, false, Headers);
937
Andrew Lenharth92d56b72008-03-24 21:25:48 +0000938 //Debian testing/lenny x86
939 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
940 false, false, false, Headers);
Andrew Lenharthf24964c2008-03-24 21:39:05 +0000941
942 //Debian testing/lenny amd64
943 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
944 false, false, false, Headers);
Andrew Lenharth92d56b72008-03-24 21:25:48 +0000945
Chris Lattner822da612007-12-17 06:36:45 +0000946 AddPath("/usr/include", System, false, false, false, Headers);
947 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
948 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000949 }
950
951 // Now that we have collected all of the include paths, merge them all
952 // together and tell the preprocessor about them.
953
954 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
955 std::vector<DirectoryLookup> SearchList;
956 SearchList = IncludeGroup[Angled];
957 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
958 IncludeGroup[System].end());
959 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
960 IncludeGroup[After].end());
961 RemoveDuplicates(SearchList);
962 RemoveDuplicates(IncludeGroup[Quoted]);
963
964 // Prepend QUOTED list on the search list.
965 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
966 IncludeGroup[Quoted].end());
967
968
969 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
970 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
971 DontSearchCurDir);
972
973 // If verbose, print the list of directories that will be searched.
974 if (Verbose) {
975 fprintf(stderr, "#include \"...\" search starts here:\n");
976 unsigned QuotedIdx = IncludeGroup[Quoted].size();
977 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
978 if (i == QuotedIdx)
979 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000980 const char *Name = SearchList[i].getName();
981 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000982 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000983 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000984 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000985 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000986 else {
987 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000988 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000989 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000990 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000991 }
Chris Lattner80e17152007-12-15 23:11:06 +0000992 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 }
994}
995
996
Reid Spencer5f016e22007-07-11 17:01:13 +0000997//===----------------------------------------------------------------------===//
998// Basic Parser driver
999//===----------------------------------------------------------------------===//
1000
Ted Kremenek95041a22007-12-19 22:51:13 +00001001static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +00001002 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001003 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001004
1005 // Parsing the specified input file.
1006 P.ParseTranslationUnit();
1007 delete PA;
1008}
1009
1010//===----------------------------------------------------------------------===//
1011// Main driver
1012//===----------------------------------------------------------------------===//
1013
Ted Kremenekdb094a22007-12-05 18:27:04 +00001014/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1015/// action. These consumers can operate on both ASTs that are freshly
1016/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001017static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001018 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001019 const LangOptions& LangOpts,
1020 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001021 switch (ProgAction) {
1022 default:
1023 return NULL;
1024
1025 case ASTPrint:
1026 return CreateASTPrinter();
1027
1028 case ASTDump:
1029 return CreateASTDumper();
1030
1031 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001032 return CreateASTViewer();
1033
1034 case EmitHTML:
1035 return CreateHTMLPrinter();
Ted Kremenekdb094a22007-12-05 18:27:04 +00001036
Ted Kremenek13e479b2008-03-19 07:53:42 +00001037 case HTMLTest:
1038 return CreateHTMLTest();
1039
Ted Kremenekdb094a22007-12-05 18:27:04 +00001040 case ParseCFGDump:
1041 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001042 return CreateCFGDumper(ProgAction == ParseCFGView,
1043 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001044
1045 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001046 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001047
1048 case WarnDeadStores:
1049 return CreateDeadStoreChecker(Diag);
1050
1051 case WarnUninitVals:
1052 return CreateUnitValsChecker(Diag);
1053
Ted Kremeneke01c9872008-02-14 22:36:46 +00001054 case AnalysisGRSimpleVals:
Ted Kremenek4dc41cc2008-03-31 18:26:32 +00001055 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, OutputFile);
Ted Kremeneke603df42008-01-08 18:04:06 +00001056
Ted Kremenekd55fe522008-02-15 00:35:38 +00001057 case AnalysisGRSimpleValsView:
Ted Kremenek4dc41cc2008-03-31 18:26:32 +00001058 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, OutputFile,
1059 true, TrimGraph);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001060
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001061 case CheckerCFRef:
Ted Kremenek4dc41cc2008-03-31 18:26:32 +00001062 return CreateCFRefChecker(Diag, AnalyzeSpecificFunction, OutputFile);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001063
Ted Kremenekdb094a22007-12-05 18:27:04 +00001064 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001065 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001066
1067 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001068 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001069 DestModule = new llvm::Module(InFile);
1070 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001071
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001072 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001073 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001074 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001075
Ted Kremenekdb094a22007-12-05 18:27:04 +00001076 case RewriteTest:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001077 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001078 }
1079}
1080
Reid Spencer5f016e22007-07-11 17:01:13 +00001081/// ProcessInputFile - Process a single input file with the specified state.
1082///
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001083static void ProcessInputFile(Preprocessor &PP, const std::string &InFile) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001084
1085 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001086 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001087 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001088
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 switch (ProgAction) {
1090 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001091 Consumer = CreateASTConsumer(InFile,
1092 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001093 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001094 PP.getLangOptions(),
1095 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001096
1097 if (!Consumer) {
1098 fprintf(stderr, "Unexpected program action!\n");
1099 return;
1100 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001101
Ted Kremenekdb094a22007-12-05 18:27:04 +00001102 break;
1103
Reid Spencer5f016e22007-07-11 17:01:13 +00001104 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001105 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001107 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 do {
1109 PP.Lex(Tok);
1110 PP.DumpToken(Tok, true);
1111 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001112 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001113 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 break;
1115 }
1116 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001117 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001119 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 do {
1121 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001122 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001123 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 break;
1125 }
1126
1127 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001128 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001129 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 break;
1131
1132 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001133 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001134 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 break;
1136
1137 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001138 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001139 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001141
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001142 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001143 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001144 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001145 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001146
1147 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001148 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001149 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001150
1151 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001152 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001154
1155 // If running the code generator, finish up now.
1156 if (CodeGenModule) {
1157 std::ostream *Out;
1158 if (OutputFile == "-") {
1159 Out = llvm::cout.stream();
1160 } else if (!OutputFile.empty()) {
1161 Out = new std::ofstream(OutputFile.c_str(),
1162 std::ios_base::binary|std::ios_base::out);
1163 } else if (InFile == "-") {
1164 Out = llvm::cout.stream();
1165 } else {
1166 llvm::sys::Path Path(InFile);
1167 Path.eraseSuffix();
1168 if (ProgAction == EmitLLVM)
1169 Path.appendSuffix("ll");
1170 else if (ProgAction == EmitBC)
1171 Path.appendSuffix("bc");
1172 else
1173 assert(0 && "Unknown action");
1174 Out = new std::ofstream(Path.toString().c_str(),
1175 std::ios_base::binary|std::ios_base::out);
1176 }
1177
1178 if (ProgAction == EmitLLVM) {
1179 CodeGenModule->print(*Out);
1180 } else {
1181 assert(ProgAction == EmitBC);
1182 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1183 }
1184
1185 if (Out != llvm::cout.stream())
1186 delete Out;
1187 delete CodeGenModule;
1188 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001189
1190 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001191 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 PP.PrintStats();
1193 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001194 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001195 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001196 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001197 fprintf(stderr, "\n");
1198 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001199
1200 // For a multi-file compilation, some things are ok with nuking the source
1201 // manager tables, other require stable fileid/macroid's across multiple
1202 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001203 if (ClearSourceMgr)
1204 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001205}
1206
Ted Kremenek20e97482007-12-12 23:41:08 +00001207static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1208 FileManager& FileMgr) {
1209
1210 if (VerifyDiagnostics) {
1211 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1212 exit (1);
1213 }
1214
1215 llvm::sys::Path Filename(InFile);
1216
1217 if (!Filename.isValid()) {
1218 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1219 exit (1);
1220 }
1221
Ted Kremenekee533642007-12-20 19:47:16 +00001222 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001223
1224 if (!TU) {
1225 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1226 InFile.c_str());
1227 exit (1);
1228 }
1229
Ted Kremenek63ea8632007-12-19 19:27:38 +00001230 // Observe that we use the source file name stored in the deserialized
1231 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001232 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001233 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001234 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1235 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001236
1237 if (!Consumer) {
1238 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1239 exit (1);
1240 }
1241
Ted Kremenek95041a22007-12-19 22:51:13 +00001242 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001243
Chris Lattnere66b65c2008-02-06 01:42:25 +00001244 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001245 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1246 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001247}
1248
1249
Reid Spencer5f016e22007-07-11 17:01:13 +00001250static llvm::cl::list<std::string>
1251InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1252
Ted Kremenek20e97482007-12-12 23:41:08 +00001253static bool isSerializedFile(const std::string& InFile) {
1254 if (InFile.size() < 4)
1255 return false;
1256
1257 const char* s = InFile.c_str()+InFile.size()-4;
1258
1259 return s[0] == '.' &&
1260 s[1] == 'a' &&
1261 s[2] == 's' &&
1262 s[3] == 't';
1263}
1264
Reid Spencer5f016e22007-07-11 17:01:13 +00001265
1266int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001267 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001268 llvm::sys::PrintStackTraceOnErrorSignal();
1269
1270 // If no input was specified, read from stdin.
1271 if (InputFilenames.empty())
1272 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001273
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 // Create a file manager object to provide access to and cache the filesystem.
1275 FileManager FileMgr;
1276
Ted Kremenek31e703b2007-12-11 23:28:38 +00001277 // Create the diagnostic client for reporting errors or for
1278 // implementing -verify.
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001279 std::auto_ptr<DiagnosticClient> DiagClient;
1280 TextDiagnostics* TextDiagClient = NULL;
1281
1282 if (!HTMLDiag.empty()) {
1283 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
1284 }
1285 else { // Use Text diagnostics.
1286 if (!VerifyDiagnostics) {
1287 // Print diagnostics to stderr by default.
1288 TextDiagClient = new TextDiagnosticPrinter();
1289 } else {
1290 // When checking diagnostics, just buffer them up.
1291 TextDiagClient = new TextDiagnosticBuffer();
1292
1293 if (InputFilenames.size() != 1) {
1294 fprintf(stderr,
1295 "-verify only works on single input files for now.\n");
1296 return 1;
1297 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 }
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001299
1300 assert (TextDiagClient);
1301 DiagClient.reset(TextDiagClient);
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 }
1303
1304 // Configure our handling of diagnostics.
1305 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001306 InitializeDiagnostics(Diags);
1307
Chris Lattner4f037832007-12-05 23:24:17 +00001308 // -I- is a deprecated GCC feature, scan for it and reject it.
1309 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1310 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001311 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001312 I_dirs.erase(I_dirs.begin()+i);
1313 --i;
1314 }
1315 }
Chris Lattner11215192008-03-14 06:12:05 +00001316
1317 // Get information about the target being compiled for.
1318 std::string Triple = CreateTargetTriple();
1319 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1320 if (Target == 0) {
1321 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1322 Triple.c_str());
1323 fprintf(stderr, "Please use -triple or -arch.\n");
1324 exit(1);
1325 }
Chris Lattner4f037832007-12-05 23:24:17 +00001326
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001328 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001329
Ted Kremenek20e97482007-12-12 23:41:08 +00001330 if (isSerializedFile(InFile))
1331 ProcessSerializedFile(InFile,Diags,FileMgr);
1332 else {
1333 /// Create a SourceManager object. This tracks and owns all the file
1334 /// buffers allocated to a translation unit.
1335 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001336
Ted Kremenek20e97482007-12-12 23:41:08 +00001337 // Initialize language options, inferring file types from input filenames.
1338 LangOptions LangInfo;
1339 InitializeBaseLanguage();
1340 LangKind LK = GetLanguage(InFile);
1341 InitializeLangOptions(LangInfo, LK);
1342 InitializeLanguageStandard(LangInfo, LK);
1343
1344 // Process the -I options and set them in the HeaderInfo.
1345 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001346 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001347 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001348
Ted Kremenek20e97482007-12-12 23:41:08 +00001349 // Set up the preprocessor with these options.
1350 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1351
1352 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001353 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001354 continue;
1355
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001356 ProcessInputFile(PP, InFile);
Ted Kremenek20e97482007-12-12 23:41:08 +00001357 HeaderInfo.ClearFileInfo();
1358
1359 if (Stats)
1360 SourceMgr.PrintStats();
1361 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 }
1363
Chris Lattner11215192008-03-14 06:12:05 +00001364 delete Target;
1365
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1367
1368 if (NumDiagnostics)
1369 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1370 (NumDiagnostics == 1 ? "" : "s"));
1371
1372 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 FileMgr.PrintStats();
1374 fprintf(stderr, "\n");
1375 }
1376
Chris Lattner96f1a642007-07-21 05:40:53 +00001377 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001378}