blob: 287ea9da9bb874421750df17747874a187970036 [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 Kremenekd71ed262008-04-10 22:16:52 +0000125 clEnumValN(AnalysisGRSimpleVals, "checker-simple",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000126 "Perform path-sensitive constant propagation."),
Ted Kremenekd71ed262008-04-10 22:16:52 +0000127 clEnumValN(CheckerCFRef, "checker-cfref",
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000128 "Run the Core Foundation reference count checker."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000129 clEnumValN(TestSerialization, "test-pickling",
Chris Lattnerf3dabbd2008-03-09 05:25:01 +0000130 "Run prototype serialization code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000132 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000133 clEnumValN(EmitBC, "emit-llvm-bc",
134 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000135 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000136 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000137 clEnumValN(RewriteTest, "rewrite-test",
138 "Playground for the code rewriter"),
Ted Kremenek13e479b2008-03-19 07:53:42 +0000139 clEnumValN(HTMLTest, "html-test",
140 "Playground for the HTML displayer"),
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000141
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 clEnumValEnd));
143
Ted Kremenekccc76472007-12-19 19:47:59 +0000144
145static llvm::cl::opt<std::string>
146OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000147 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000148 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000149
150//===----------------------------------------------------------------------===//
151// Diagnostic Options
152//===----------------------------------------------------------------------===//
153
Ted Kremenek41193e42007-09-26 19:42:19 +0000154static llvm::cl::opt<bool>
155VerifyDiagnostics("verify",
156 llvm::cl::desc("Verify emitted diagnostics and warnings."));
157
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000158static llvm::cl::opt<std::string>
159HTMLDiag("html-diags",
160 llvm::cl::desc("Generate HTML to report diagnostics"),
161 llvm::cl::value_desc("HTML directory"));
162
Reid Spencer5f016e22007-07-11 17:01:13 +0000163//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000164// Analyzer Options
165//===----------------------------------------------------------------------===//
166
167static llvm::cl::opt<bool>
168VisualizeEG("visualize-egraph",
169 llvm::cl::desc("Display static analysis Exploded Graph."));
170
171static llvm::cl::opt<bool>
172AnalyzeAll("checker-opt-analyze-headers",
173 llvm::cl::desc("Force the static analyzer to analyze "
174 "functions defined in header files."));
175
176//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000177// Language Options
178//===----------------------------------------------------------------------===//
179
180enum LangKind {
181 langkind_unspecified,
182 langkind_c,
183 langkind_c_cpp,
184 langkind_cxx,
185 langkind_cxx_cpp,
186 langkind_objc,
187 langkind_objc_cpp,
188 langkind_objcxx,
189 langkind_objcxx_cpp
190};
191
192/* TODO: GCC also accepts:
193 c-header c++-header objective-c-header objective-c++-header
194 assembler assembler-with-cpp
195 ada, f77*, ratfor (!), f95, java, treelang
196 */
197static llvm::cl::opt<LangKind>
198BaseLang("x", llvm::cl::desc("Base language to compile"),
199 llvm::cl::init(langkind_unspecified),
200 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
201 clEnumValN(langkind_cxx, "c++", "C++"),
202 clEnumValN(langkind_objc, "objective-c", "Objective C"),
203 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
204 clEnumValN(langkind_c_cpp, "c-cpp-output",
205 "Preprocessed C"),
206 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
207 "Preprocessed C++"),
208 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
209 "Preprocessed Objective C"),
210 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
211 "Preprocessed Objective C++"),
212 clEnumValEnd));
213
214static llvm::cl::opt<bool>
215LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
216 llvm::cl::Hidden);
217static llvm::cl::opt<bool>
218LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
219 llvm::cl::Hidden);
220
Ted Kremenek8904f152007-12-05 23:49:08 +0000221/// InitializeBaseLanguage - Handle the -x foo options.
222static void InitializeBaseLanguage() {
223 if (LangObjC)
224 BaseLang = langkind_objc;
225 else if (LangObjCXX)
226 BaseLang = langkind_objcxx;
227}
228
229static LangKind GetLanguage(const std::string &Filename) {
230 if (BaseLang != langkind_unspecified)
231 return BaseLang;
232
233 std::string::size_type DotPos = Filename.rfind('.');
234
235 if (DotPos == std::string::npos) {
236 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000237 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 }
239
Ted Kremenek8904f152007-12-05 23:49:08 +0000240 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
241 // C header: .h
242 // C++ header: .hh or .H;
243 // assembler no preprocessing: .s
244 // assembler: .S
245 if (Ext == "c")
246 return langkind_c;
247 else if (Ext == "i")
248 return langkind_c_cpp;
249 else if (Ext == "ii")
250 return langkind_cxx_cpp;
251 else if (Ext == "m")
252 return langkind_objc;
253 else if (Ext == "mi")
254 return langkind_objc_cpp;
255 else if (Ext == "mm" || Ext == "M")
256 return langkind_objcxx;
257 else if (Ext == "mii")
258 return langkind_objcxx_cpp;
259 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
260 Ext == "c++" || Ext == "cp" || Ext == "cxx")
261 return langkind_cxx;
262 else
263 return langkind_c;
264}
265
266
267static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 // FIXME: implement -fpreprocessed mode.
269 bool NoPreprocess = false;
270
Ted Kremenek8904f152007-12-05 23:49:08 +0000271 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 default: assert(0 && "Unknown language kind!");
273 case langkind_c_cpp:
274 NoPreprocess = true;
275 // FALLTHROUGH
276 case langkind_c:
277 break;
278 case langkind_cxx_cpp:
279 NoPreprocess = true;
280 // FALLTHROUGH
281 case langkind_cxx:
282 Options.CPlusPlus = 1;
283 break;
284 case langkind_objc_cpp:
285 NoPreprocess = true;
286 // FALLTHROUGH
287 case langkind_objc:
288 Options.ObjC1 = Options.ObjC2 = 1;
289 break;
290 case langkind_objcxx_cpp:
291 NoPreprocess = true;
292 // FALLTHROUGH
293 case langkind_objcxx:
294 Options.ObjC1 = Options.ObjC2 = 1;
295 Options.CPlusPlus = 1;
296 break;
297 }
298}
299
300/// LangStds - Language standards we support.
301enum LangStds {
302 lang_unspecified,
303 lang_c89, lang_c94, lang_c99,
304 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000305 lang_cxx98, lang_gnucxx98,
306 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000307};
308
309static llvm::cl::opt<LangStds>
310LangStd("std", llvm::cl::desc("Language standard to compile for"),
311 llvm::cl::init(lang_unspecified),
312 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
313 clEnumValN(lang_c89, "c90", "ISO C 1990"),
314 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
315 clEnumValN(lang_c94, "iso9899:199409",
316 "ISO C 1990 with amendment 1"),
317 clEnumValN(lang_c99, "c99", "ISO C 1999"),
318// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
319 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
320// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
321 clEnumValN(lang_gnu89, "gnu89",
322 "ISO C 1990 with GNU extensions (default for C)"),
323 clEnumValN(lang_gnu99, "gnu99",
324 "ISO C 1999 with GNU extensions"),
325 clEnumValN(lang_gnu99, "gnu9x",
326 "ISO C 1999 with GNU extensions"),
327 clEnumValN(lang_cxx98, "c++98",
328 "ISO C++ 1998 with amendments"),
329 clEnumValN(lang_gnucxx98, "gnu++98",
330 "ISO C++ 1998 with amendments and GNU "
331 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000332 clEnumValN(lang_cxx0x, "c++0x",
333 "Upcoming ISO C++ 200x with amendments"),
334 clEnumValN(lang_gnucxx0x, "gnu++0x",
335 "Upcoming ISO C++ 200x with amendments and GNU "
336 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 clEnumValEnd));
338
339static llvm::cl::opt<bool>
340NoOperatorNames("fno-operator-names",
341 llvm::cl::desc("Do not treat C++ operator name keywords as "
342 "synonyms for operators"));
343
Anders Carlssonee98ac52007-10-15 02:50:23 +0000344static llvm::cl::opt<bool>
345PascalStrings("fpascal-strings",
346 llvm::cl::desc("Recognize and construct Pascal-style "
347 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000348
349static llvm::cl::opt<bool>
350MSExtensions("fms-extensions",
351 llvm::cl::desc("Accept some non-standard constructs used in "
352 "Microsoft header files. "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000353
354static llvm::cl::opt<bool>
355WritableStrings("fwritable-strings",
356 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000357
358static llvm::cl::opt<bool>
359LaxVectorConversions("flax-vector-conversions",
360 llvm::cl::desc("Allow implicit conversions between vectors"
361 " with a different number of elements or "
362 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000363// FIXME: add:
364// -ansi
365// -trigraphs
366// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000367// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000368static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 if (LangStd == lang_unspecified) {
370 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000371 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 default: assert(0 && "Unknown base language");
373 case langkind_c:
374 case langkind_c_cpp:
375 case langkind_objc:
376 case langkind_objc_cpp:
377 LangStd = lang_gnu99;
378 break;
379 case langkind_cxx:
380 case langkind_cxx_cpp:
381 case langkind_objcxx:
382 case langkind_objcxx_cpp:
383 LangStd = lang_gnucxx98;
384 break;
385 }
386 }
387
388 switch (LangStd) {
389 default: assert(0 && "Unknown language standard!");
390
391 // Fall through from newer standards to older ones. This isn't really right.
392 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000393 case lang_gnucxx0x:
394 case lang_cxx0x:
395 Options.CPlusPlus0x = 1;
396 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000397 case lang_gnucxx98:
398 case lang_cxx98:
399 Options.CPlusPlus = 1;
400 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000401 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 // FALL THROUGH.
403 case lang_gnu99:
404 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 Options.C99 = 1;
406 Options.HexFloats = 1;
407 // FALL THROUGH.
408 case lang_gnu89:
409 Options.BCPLComment = 1; // Only for C99/C++.
410 // FALL THROUGH.
411 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000412 Options.Digraphs = 1; // C94, C99, C++.
413 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 case lang_c89:
415 break;
416 }
417
Chris Lattnerd658b562008-04-05 06:32:51 +0000418 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
419 Options.ImplicitInt = 1;
420 else
421 Options.ImplicitInt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 Options.Trigraphs = 1; // -trigraphs or -ansi
423 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000424 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000425 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000426 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000427 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000428}
429
430//===----------------------------------------------------------------------===//
431// Our DiagnosticClient implementation
432//===----------------------------------------------------------------------===//
433
434// FIXME: Werror should take a list of things, -Werror=foo,bar
435static llvm::cl::opt<bool>
436WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
437
438static llvm::cl::opt<bool>
439WarnOnExtensions("pedantic", llvm::cl::init(false),
440 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
441
442static llvm::cl::opt<bool>
443ErrorOnExtensions("pedantic-errors",
444 llvm::cl::desc("Issue an error on uses of GCC extensions"));
445
446static llvm::cl::opt<bool>
447WarnUnusedMacros("Wunused_macros",
448 llvm::cl::desc("Warn for unused macros in the main translation unit"));
449
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000450static llvm::cl::opt<bool>
451WarnFloatEqual("Wfloat-equal",
452 llvm::cl::desc("Warn about equality comparisons of floating point values."));
453
Ted Kremenek73da5902007-12-17 17:50:07 +0000454static llvm::cl::opt<bool>
455WarnNoFormatNonLiteral("Wno-format-nonliteral",
456 llvm::cl::desc("Do not warn about non-literal format strings."));
457
Chris Lattner116a4b12008-01-23 17:19:46 +0000458static llvm::cl::opt<bool>
459WarnUndefMacros("Wundef",
460 llvm::cl::desc("Warn on use of undefined macros in #if's"));
461
462
Reid Spencer5f016e22007-07-11 17:01:13 +0000463/// InitializeDiagnostics - Initialize the diagnostic object, based on the
464/// current command line option settings.
465static void InitializeDiagnostics(Diagnostic &Diags) {
466 Diags.setWarningsAsErrors(WarningsAsErrors);
467 Diags.setWarnOnExtensions(WarnOnExtensions);
468 Diags.setErrorOnExtensions(ErrorOnExtensions);
469
470 // Silence the "macro is not used" warning unless requested.
471 if (!WarnUnusedMacros)
472 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000473
474 // Silence "floating point comparison" warnings unless requested.
475 if (!WarnFloatEqual)
476 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000477
478 // Silence "format string is not a string literal" warnings if requested
479 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000480 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
481 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000482 if (!WarnUndefMacros)
483 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000484
485 if (MSExtensions) // MS allows unnamed struct/union fields.
486 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000487}
488
489//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000490// Analysis-specific options.
491//===----------------------------------------------------------------------===//
492
493static llvm::cl::opt<std::string>
494AnalyzeSpecificFunction("analyze-function",
495 llvm::cl::desc("Run analysis on specific function."));
496
Ted Kremenekffe0f432008-03-07 22:58:01 +0000497static llvm::cl::opt<bool>
Ted Kremenekd71ed262008-04-10 22:16:52 +0000498TrimGraph("trim-egraph",
Ted Kremenekffe0f432008-03-07 22:58:01 +0000499 llvm::cl::desc("Only show error-related paths in the analysis graph."));
500
Ted Kremenekcb330932008-02-18 21:21:23 +0000501//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000502// Target Triple Processing.
503//===----------------------------------------------------------------------===//
504
505static llvm::cl::opt<std::string>
506TargetTriple("triple",
507 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
508
Chris Lattner42e67372008-03-05 01:18:20 +0000509static llvm::cl::opt<std::string>
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000510Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)."));
Ted Kremenekae360762007-12-03 22:06:55 +0000511
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000512static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000513 // Initialize base triple. If a -triple option has been specified, use
514 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000515 std::string Triple = TargetTriple;
516 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000517
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000518 // If -arch foo was specified, remove the architecture from the triple we have
519 // so far and replace it with the specified one.
520 if (Arch.empty())
521 return Triple;
522
Ted Kremenekae360762007-12-03 22:06:55 +0000523 // Decompose the base triple into "arch" and suffix.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000524 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000525
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000526 if (FirstDashIdx == std::string::npos) {
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000527 fprintf(stderr,
528 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000529 Triple.c_str());
530 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000531 }
Ted Kremenekae360762007-12-03 22:06:55 +0000532
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000533 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenekae360762007-12-03 22:06:55 +0000534}
535
536//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000537// Preprocessor Initialization
538//===----------------------------------------------------------------------===//
539
540// FIXME: Preprocessor builtins to support.
541// -A... - Play with #assertions
542// -undef - Undefine all predefined macros
543
544static llvm::cl::list<std::string>
545D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
546 llvm::cl::desc("Predefine the specified macro"));
547static llvm::cl::list<std::string>
548U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
549 llvm::cl::desc("Undefine the specified macro"));
550
Chris Lattner64299f82008-01-10 01:53:41 +0000551static llvm::cl::list<std::string>
552ImplicitIncludes("include", llvm::cl::value_desc("file"),
553 llvm::cl::desc("Include file before parsing"));
554
555
Reid Spencer5f016e22007-07-11 17:01:13 +0000556// Append a #define line to Buf for Macro. Macro should be of the form XXX,
557// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
558// "#define XXX Y z W". To get a #define with no value, use "XXX=".
559static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
560 const char *Command = "#define ") {
561 Buf.insert(Buf.end(), Command, Command+strlen(Command));
562 if (const char *Equal = strchr(Macro, '=')) {
563 // Turn the = into ' '.
564 Buf.insert(Buf.end(), Macro, Equal);
565 Buf.push_back(' ');
566 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
567 } else {
568 // Push "macroname 1".
569 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
570 Buf.push_back(' ');
571 Buf.push_back('1');
572 }
573 Buf.push_back('\n');
574}
575
Chris Lattner64299f82008-01-10 01:53:41 +0000576/// AddImplicitInclude - Add an implicit #include of the specified file to the
577/// predefines buffer.
578static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
579 const char *Inc = "#include \"";
580 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
581 Buf.insert(Buf.end(), File.begin(), File.end());
582 Buf.push_back('"');
583 Buf.push_back('\n');
584}
585
Reid Spencer5f016e22007-07-11 17:01:13 +0000586
Chris Lattner53b0dab2007-10-09 22:10:18 +0000587/// InitializePreprocessor - Initialize the preprocessor getting it and the
588/// environment ready to process a single file. This returns the file ID for the
589/// input file. If a failure happens, it returns 0.
590///
591static unsigned InitializePreprocessor(Preprocessor &PP,
592 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000593 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000594
Chris Lattnerdee73592007-12-15 20:48:40 +0000595 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000596
Chris Lattner53b0dab2007-10-09 22:10:18 +0000597 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000598 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000599 if (InFile != "-") {
600 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000601 if (File) SourceMgr.createMainFileID(File, SourceLocation());
602 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000603 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
604 return 0;
605 }
606 } else {
607 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000608 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
609 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000610 fprintf(stderr, "Error reading standard input! Empty?\n");
611 return 0;
612 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000613 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000614
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000616 unsigned d = 0, D = D_macros.size();
617 unsigned u = 0, U = U_macros.size();
618 while (d < D || u < U) {
619 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
620 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
621 else
622 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
623 }
624
Chris Lattner64299f82008-01-10 01:53:41 +0000625 // FIXME: Read any files specified by -imacros.
626
627 // Add implicit #includes from -include.
628 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
629 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000630
631 // Null terminate PredefinedBuffer and add it.
632 PredefineBuffer.push_back(0);
633 PP.setPredefines(&PredefineBuffer[0]);
634
635 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000636 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000637}
638
639//===----------------------------------------------------------------------===//
640// Preprocessor include path information.
641//===----------------------------------------------------------------------===//
642
643// This tool exports a large number of command line options to control how the
644// preprocessor searches for header files. At root, however, the Preprocessor
645// object takes a very simple interface: a list of directories to search for
646//
647// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000648// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000649//
Chris Lattner64299f82008-01-10 01:53:41 +0000650// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000651
652static llvm::cl::opt<bool>
653nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
654
655// Various command line options. These four add directories to each chain.
656static llvm::cl::list<std::string>
657F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
658 llvm::cl::desc("Add directory to framework include search path"));
659static llvm::cl::list<std::string>
660I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
661 llvm::cl::desc("Add directory to include search path"));
662static llvm::cl::list<std::string>
663idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
664 llvm::cl::desc("Add directory to AFTER include search path"));
665static llvm::cl::list<std::string>
666iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
667 llvm::cl::desc("Add directory to QUOTE include search path"));
668static llvm::cl::list<std::string>
669isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
670 llvm::cl::desc("Add directory to SYSTEM include search path"));
671
672// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
673static llvm::cl::list<std::string>
674iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
675 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
676static llvm::cl::list<std::string>
677iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
678 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
679static llvm::cl::list<std::string>
680iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
681 llvm::cl::Prefix,
682 llvm::cl::desc("Set directory to include search path with prefix"));
683
Chris Lattner0c946412007-08-26 17:47:35 +0000684static llvm::cl::opt<std::string>
685isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
686 llvm::cl::desc("Set the system root directory (usually /)"));
687
Reid Spencer5f016e22007-07-11 17:01:13 +0000688// Finally, implement the code that groks the options above.
689enum IncludeDirGroup {
690 Quoted = 0,
691 Angled,
692 System,
693 After
694};
695
696static std::vector<DirectoryLookup> IncludeGroup[4];
697
698/// AddPath - Add the specified path to the specified group list.
699///
700static void AddPath(const std::string &Path, IncludeDirGroup Group,
701 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000702 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000703 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000704 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000705
Chris Lattnerd6655272007-12-17 05:59:27 +0000706 // Compute the actual path, taking into consideration -isysroot.
707 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000708
Chris Lattnerd6655272007-12-17 05:59:27 +0000709 // Handle isysroot.
710 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000711 // FIXME: Portability. This should be a sys::Path interface, this doesn't
712 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000713 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
714 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 }
716
Chris Lattnerd6655272007-12-17 05:59:27 +0000717 MappedPath.append(Path.begin(), Path.end());
718
719 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000720 DirectoryLookup::DirType Type;
721 if (Group == Quoted || Group == Angled)
722 Type = DirectoryLookup::NormalHeaderDir;
723 else if (isCXXAware)
724 Type = DirectoryLookup::SystemHeaderDir;
725 else
726 Type = DirectoryLookup::ExternCSystemHeaderDir;
727
Chris Lattnerd6655272007-12-17 05:59:27 +0000728
729 // If the directory exists, add it.
730 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
731 &MappedPath[0]+
732 MappedPath.size())) {
733 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
734 isFramework));
735 return;
736 }
737
Chris Lattnerdf772332007-12-17 07:52:39 +0000738 // Check to see if this is an apple-style headermap (which are not allowed to
739 // be frameworks).
740 if (!isFramework) {
741 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
742 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000743 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
744 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000745 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
746 return;
747 }
Chris Lattner822da612007-12-17 06:36:45 +0000748 }
749 }
750
Chris Lattnerd6655272007-12-17 05:59:27 +0000751 if (Verbose)
752 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000753}
754
755/// RemoveDuplicates - If there are duplicate directory entries in the specified
756/// search list, remove the later (dead) ones.
757static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000758 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000759 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000760 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000762 if (SearchList[i].isNormalDir()) {
763 // If this isn't the first time we've seen this dir, remove it.
764 if (SeenDirs.insert(SearchList[i].getDir()))
765 continue;
766
Reid Spencer5f016e22007-07-11 17:01:13 +0000767 if (Verbose)
768 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
769 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000770 } else if (SearchList[i].isFramework()) {
771 // If this isn't the first time we've seen this framework dir, remove it.
772 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
773 continue;
774
775 if (Verbose)
776 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
777 SearchList[i].getFrameworkDir()->getName());
778
Chris Lattnerb94c7072007-12-17 06:44:29 +0000779 } else {
780 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
781 // If this isn't the first time we've seen this headermap, remove it.
782 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
783 continue;
784
785 if (Verbose)
786 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
787 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000789
790 // This is reached if the current entry is a duplicate.
791 SearchList.erase(SearchList.begin()+i);
792 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 }
794}
795
Chris Lattner5f9eae52008-03-01 08:07:28 +0000796// AddEnvVarPaths - Add a list of paths from an environment variable to a
797// header search list.
798//
799static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
800 const char* at = getenv(Name);
801 if (!at)
802 return;
803
804 const char* delim = strchr(at, llvm::sys::PathSeparator);
805 while (delim != 0) {
806 if (delim-at == 0)
807 AddPath(".", Angled, false, true, false, Headers);
808 else
809 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
810 true, false, Headers);
811 at = delim + 1;
812 delim = strchr(at, llvm::sys::PathSeparator);
813 }
814 if (*at == 0)
815 AddPath(".", Angled, false, true, false, Headers);
816 else
817 AddPath(at, Angled, false, true, false, Headers);
818}
819
Reid Spencer5f016e22007-07-11 17:01:13 +0000820/// InitializeIncludePaths - Process the -I options and set them in the
821/// HeaderSearch object.
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000822static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
823 FileManager &FM, const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000824 // Handle -F... options.
825 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000826 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000827
828 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000829 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000830 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000831
832 // Handle -idirafter... options.
833 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000834 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000835
836 // Handle -iquote... options.
837 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000838 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000839
840 // Handle -isystem... options.
841 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000842 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000843
844 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
845 // parallel, processing the values in order of occurance to get the right
846 // prefixes.
847 {
848 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
849 unsigned iprefix_idx = 0;
850 unsigned iwithprefix_idx = 0;
851 unsigned iwithprefixbefore_idx = 0;
852 bool iprefix_done = iprefix_vals.empty();
853 bool iwithprefix_done = iwithprefix_vals.empty();
854 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
855 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
856 if (!iprefix_done &&
857 (iwithprefix_done ||
858 iprefix_vals.getPosition(iprefix_idx) <
859 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
860 (iwithprefixbefore_done ||
861 iprefix_vals.getPosition(iprefix_idx) <
862 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
863 Prefix = iprefix_vals[iprefix_idx];
864 ++iprefix_idx;
865 iprefix_done = iprefix_idx == iprefix_vals.size();
866 } else if (!iwithprefix_done &&
867 (iwithprefixbefore_done ||
868 iwithprefix_vals.getPosition(iwithprefix_idx) <
869 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
870 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000871 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 ++iwithprefix_idx;
873 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
874 } else {
875 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000876 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 ++iwithprefixbefore_idx;
878 iwithprefixbefore_done =
879 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
880 }
881 }
882 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000883
884 AddEnvVarPaths("CPATH", Headers);
885 if (Lang.CPlusPlus && Lang.ObjC1)
886 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
887 else if (Lang.CPlusPlus)
888 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
889 else if (Lang.ObjC1)
890 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
891 else
892 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
893
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000894 // Add the clang headers, which are relative to the clang driver.
895 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000896 llvm::sys::Path::GetMainExecutable(Argv0,
897 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000898 if (!MainExecutablePath.isEmpty()) {
899 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
900 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
901 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
902 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
903 }
904
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 // FIXME: temporary hack: hard-coded paths.
906 // FIXME: get these from the target?
907 if (!nostdinc) {
908 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000909 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000910 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000911 false, Headers);
912 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
913 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000914
915 // Ubuntu 7.10 - Gutsy Gibbon
916 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
917 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
918 false, Headers);
919 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
920 Headers);
Chris Lattner04421082008-04-08 04:40:51 +0000921
922 // Fedora 8
923 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
924 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false, false, Headers);
925 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 }
927
Chris Lattner822da612007-12-17 06:36:45 +0000928 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 // leopard
930 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000931 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000932 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000933 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000934 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
935 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000936 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000937
938 // tiger
939 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000940 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000941 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000942 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
944 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000945 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000946
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000947 // Ubuntu 7.10 - Gutsy Gibbon
948 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +0000949 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000950
Chris Lattner04421082008-04-08 04:40:51 +0000951 // Fedora 8
952 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
953 false, false, false, Headers);
954
Andrew Lenharth92d56b72008-03-24 21:25:48 +0000955 //Debian testing/lenny x86
956 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
957 false, false, false, Headers);
Andrew Lenharthf24964c2008-03-24 21:39:05 +0000958
959 //Debian testing/lenny amd64
960 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
961 false, false, false, Headers);
Andrew Lenharth92d56b72008-03-24 21:25:48 +0000962
Chris Lattner822da612007-12-17 06:36:45 +0000963 AddPath("/usr/include", System, false, false, false, Headers);
964 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
965 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000966 }
967
968 // Now that we have collected all of the include paths, merge them all
969 // together and tell the preprocessor about them.
970
971 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
972 std::vector<DirectoryLookup> SearchList;
973 SearchList = IncludeGroup[Angled];
974 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
975 IncludeGroup[System].end());
976 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
977 IncludeGroup[After].end());
978 RemoveDuplicates(SearchList);
979 RemoveDuplicates(IncludeGroup[Quoted]);
980
981 // Prepend QUOTED list on the search list.
982 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
983 IncludeGroup[Quoted].end());
984
985
986 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
987 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
988 DontSearchCurDir);
989
990 // If verbose, print the list of directories that will be searched.
991 if (Verbose) {
992 fprintf(stderr, "#include \"...\" search starts here:\n");
993 unsigned QuotedIdx = IncludeGroup[Quoted].size();
994 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
995 if (i == QuotedIdx)
996 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000997 const char *Name = SearchList[i].getName();
998 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000999 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +00001000 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +00001001 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +00001002 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +00001003 else {
1004 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +00001005 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +00001006 }
Chris Lattner3af66a92007-12-17 17:57:27 +00001007 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +00001008 }
Chris Lattner80e17152007-12-15 23:11:06 +00001009 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001010 }
1011}
1012
1013
Reid Spencer5f016e22007-07-11 17:01:13 +00001014//===----------------------------------------------------------------------===//
1015// Basic Parser driver
1016//===----------------------------------------------------------------------===//
1017
Ted Kremenek95041a22007-12-19 22:51:13 +00001018static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +00001019 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001020 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001021
1022 // Parsing the specified input file.
1023 P.ParseTranslationUnit();
1024 delete PA;
1025}
1026
1027//===----------------------------------------------------------------------===//
1028// Main driver
1029//===----------------------------------------------------------------------===//
1030
Ted Kremenekdb094a22007-12-05 18:27:04 +00001031/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1032/// action. These consumers can operate on both ASTs that are freshly
1033/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001034static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001035 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001036 const LangOptions& LangOpts,
1037 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001038 switch (ProgAction) {
1039 default:
1040 return NULL;
1041
1042 case ASTPrint:
1043 return CreateASTPrinter();
1044
1045 case ASTDump:
1046 return CreateASTDumper();
1047
1048 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001049 return CreateASTViewer();
1050
1051 case EmitHTML:
1052 return CreateHTMLPrinter();
Ted Kremenekdb094a22007-12-05 18:27:04 +00001053
Ted Kremenek13e479b2008-03-19 07:53:42 +00001054 case HTMLTest:
1055 return CreateHTMLTest();
1056
Ted Kremenekdb094a22007-12-05 18:27:04 +00001057 case ParseCFGDump:
1058 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001059 return CreateCFGDumper(ProgAction == ParseCFGView,
1060 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001061
1062 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001063 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001064
1065 case WarnDeadStores:
1066 return CreateDeadStoreChecker(Diag);
1067
1068 case WarnUninitVals:
1069 return CreateUnitValsChecker(Diag);
1070
Ted Kremeneke01c9872008-02-14 22:36:46 +00001071 case AnalysisGRSimpleVals:
Ted Kremenek4dc41cc2008-03-31 18:26:32 +00001072 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, OutputFile,
Ted Kremenek55af98c2008-04-14 18:40:58 +00001073 VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001074
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001075 case CheckerCFRef:
Ted Kremenekd71ed262008-04-10 22:16:52 +00001076 return CreateCFRefChecker(Diag, AnalyzeSpecificFunction, OutputFile,
Ted Kremenek55af98c2008-04-14 18:40:58 +00001077 VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001078
Ted Kremenekdb094a22007-12-05 18:27:04 +00001079 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001080 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001081
1082 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001083 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001084 DestModule = new llvm::Module(InFile);
1085 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001086
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001087 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001088 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001089 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001090
Ted Kremenekdb094a22007-12-05 18:27:04 +00001091 case RewriteTest:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001092 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001093 }
1094}
1095
Reid Spencer5f016e22007-07-11 17:01:13 +00001096/// ProcessInputFile - Process a single input file with the specified state.
1097///
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001098static void ProcessInputFile(Preprocessor &PP, const std::string &InFile) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001099
1100 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001101 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001102 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001103
Reid Spencer5f016e22007-07-11 17:01:13 +00001104 switch (ProgAction) {
1105 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001106 Consumer = CreateASTConsumer(InFile,
1107 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001108 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001109 PP.getLangOptions(),
1110 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001111
1112 if (!Consumer) {
1113 fprintf(stderr, "Unexpected program action!\n");
1114 return;
1115 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001116
Ted Kremenekdb094a22007-12-05 18:27:04 +00001117 break;
1118
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001120 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001121 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001122 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 do {
1124 PP.Lex(Tok);
1125 PP.DumpToken(Tok, true);
1126 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001127 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001128 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 break;
1130 }
1131 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001132 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001134 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 do {
1136 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001137 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001138 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 break;
1140 }
1141
1142 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001143 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001144 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 break;
1146
1147 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001148 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001149 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 break;
1151
1152 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001153 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001154 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001156
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001157 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001158 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001159 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001160 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001161
1162 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001163 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001164 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001165
1166 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001167 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001168 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001169
1170 // If running the code generator, finish up now.
1171 if (CodeGenModule) {
1172 std::ostream *Out;
1173 if (OutputFile == "-") {
1174 Out = llvm::cout.stream();
1175 } else if (!OutputFile.empty()) {
1176 Out = new std::ofstream(OutputFile.c_str(),
1177 std::ios_base::binary|std::ios_base::out);
1178 } else if (InFile == "-") {
1179 Out = llvm::cout.stream();
1180 } else {
1181 llvm::sys::Path Path(InFile);
1182 Path.eraseSuffix();
1183 if (ProgAction == EmitLLVM)
1184 Path.appendSuffix("ll");
1185 else if (ProgAction == EmitBC)
1186 Path.appendSuffix("bc");
1187 else
1188 assert(0 && "Unknown action");
1189 Out = new std::ofstream(Path.toString().c_str(),
1190 std::ios_base::binary|std::ios_base::out);
1191 }
1192
1193 if (ProgAction == EmitLLVM) {
1194 CodeGenModule->print(*Out);
1195 } else {
1196 assert(ProgAction == EmitBC);
1197 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1198 }
1199
1200 if (Out != llvm::cout.stream())
1201 delete Out;
1202 delete CodeGenModule;
1203 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001204
1205 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001206 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 PP.PrintStats();
1208 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001209 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001210 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001211 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 fprintf(stderr, "\n");
1213 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001214
1215 // For a multi-file compilation, some things are ok with nuking the source
1216 // manager tables, other require stable fileid/macroid's across multiple
1217 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001218 if (ClearSourceMgr)
1219 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001220}
1221
Ted Kremenek20e97482007-12-12 23:41:08 +00001222static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1223 FileManager& FileMgr) {
1224
1225 if (VerifyDiagnostics) {
1226 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1227 exit (1);
1228 }
1229
1230 llvm::sys::Path Filename(InFile);
1231
1232 if (!Filename.isValid()) {
1233 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1234 exit (1);
1235 }
1236
Ted Kremenekee533642007-12-20 19:47:16 +00001237 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001238
1239 if (!TU) {
1240 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1241 InFile.c_str());
1242 exit (1);
1243 }
1244
Ted Kremenek63ea8632007-12-19 19:27:38 +00001245 // Observe that we use the source file name stored in the deserialized
1246 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001247 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001248 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001249 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1250 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001251
1252 if (!Consumer) {
1253 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1254 exit (1);
1255 }
1256
Ted Kremenek95041a22007-12-19 22:51:13 +00001257 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001258
Chris Lattnere66b65c2008-02-06 01:42:25 +00001259 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001260 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1261 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001262}
1263
1264
Reid Spencer5f016e22007-07-11 17:01:13 +00001265static llvm::cl::list<std::string>
1266InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1267
Ted Kremenek20e97482007-12-12 23:41:08 +00001268static bool isSerializedFile(const std::string& InFile) {
1269 if (InFile.size() < 4)
1270 return false;
1271
1272 const char* s = InFile.c_str()+InFile.size()-4;
1273
1274 return s[0] == '.' &&
1275 s[1] == 'a' &&
1276 s[2] == 's' &&
1277 s[3] == 't';
1278}
1279
Reid Spencer5f016e22007-07-11 17:01:13 +00001280
1281int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001282 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 llvm::sys::PrintStackTraceOnErrorSignal();
1284
1285 // If no input was specified, read from stdin.
1286 if (InputFilenames.empty())
1287 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001288
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 // Create a file manager object to provide access to and cache the filesystem.
1290 FileManager FileMgr;
1291
Ted Kremenek31e703b2007-12-11 23:28:38 +00001292 // Create the diagnostic client for reporting errors or for
1293 // implementing -verify.
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001294 std::auto_ptr<DiagnosticClient> DiagClient;
1295 TextDiagnostics* TextDiagClient = NULL;
1296
1297 if (!HTMLDiag.empty()) {
1298 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
1299 }
1300 else { // Use Text diagnostics.
1301 if (!VerifyDiagnostics) {
1302 // Print diagnostics to stderr by default.
1303 TextDiagClient = new TextDiagnosticPrinter();
1304 } else {
1305 // When checking diagnostics, just buffer them up.
1306 TextDiagClient = new TextDiagnosticBuffer();
1307
1308 if (InputFilenames.size() != 1) {
1309 fprintf(stderr,
1310 "-verify only works on single input files for now.\n");
1311 return 1;
1312 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001313 }
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001314
1315 assert (TextDiagClient);
1316 DiagClient.reset(TextDiagClient);
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 }
1318
1319 // Configure our handling of diagnostics.
1320 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001321 InitializeDiagnostics(Diags);
1322
Chris Lattner4f037832007-12-05 23:24:17 +00001323 // -I- is a deprecated GCC feature, scan for it and reject it.
1324 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1325 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001326 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001327 I_dirs.erase(I_dirs.begin()+i);
1328 --i;
1329 }
1330 }
Chris Lattner11215192008-03-14 06:12:05 +00001331
1332 // Get information about the target being compiled for.
1333 std::string Triple = CreateTargetTriple();
1334 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1335 if (Target == 0) {
1336 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1337 Triple.c_str());
1338 fprintf(stderr, "Please use -triple or -arch.\n");
1339 exit(1);
1340 }
Chris Lattner4f037832007-12-05 23:24:17 +00001341
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001343 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001344
Ted Kremenek20e97482007-12-12 23:41:08 +00001345 if (isSerializedFile(InFile))
1346 ProcessSerializedFile(InFile,Diags,FileMgr);
1347 else {
1348 /// Create a SourceManager object. This tracks and owns all the file
1349 /// buffers allocated to a translation unit.
1350 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001351
Ted Kremenek20e97482007-12-12 23:41:08 +00001352 // Initialize language options, inferring file types from input filenames.
1353 LangOptions LangInfo;
1354 InitializeBaseLanguage();
1355 LangKind LK = GetLanguage(InFile);
1356 InitializeLangOptions(LangInfo, LK);
1357 InitializeLanguageStandard(LangInfo, LK);
1358
1359 // Process the -I options and set them in the HeaderInfo.
1360 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001361 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001362 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001363
Ted Kremenek20e97482007-12-12 23:41:08 +00001364 // Set up the preprocessor with these options.
1365 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1366
1367 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001368 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001369 continue;
1370
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001371 ProcessInputFile(PP, InFile);
Ted Kremenek20e97482007-12-12 23:41:08 +00001372 HeaderInfo.ClearFileInfo();
1373
1374 if (Stats)
1375 SourceMgr.PrintStats();
1376 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 }
1378
Chris Lattner11215192008-03-14 06:12:05 +00001379 delete Target;
1380
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1382
1383 if (NumDiagnostics)
1384 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1385 (NumDiagnostics == 1 ? "" : "s"));
1386
1387 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 FileMgr.PrintStats();
1389 fprintf(stderr, "\n");
1390 }
1391
Chris Lattner96f1a642007-07-21 05:40:53 +00001392 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001393}