blob: 1a6db481b617e782996cde1539472a7014498d2a [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000029#include "HTMLDiagnostics.h"
30#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenekac881932007-12-18 21:34:28 +000031#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000032#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000033#include "clang/Sema/ParseAST.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000034#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner8d72ee02008-02-06 01:42:25 +000040#include "llvm/Module.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000041#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner8d72ee02008-02-06 01:42:25 +000042#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner4b009652007-07-25 00:24:17 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/MemoryBuffer.h"
45#include "llvm/System/Signals.h"
Ted Kremenek40499482007-12-03 22:06:55 +000046#include "llvm/Config/config.h"
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +000047#include "llvm/ADT/OwningPtr.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000048#include "llvm/System/Path.h"
Chris Lattner4b009652007-07-25 00:24:17 +000049#include <memory>
Chris Lattner8d72ee02008-02-06 01:42:25 +000050#include <fstream>
Ted Kremenek4e9899f2008-04-17 22:31:54 +000051#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000052using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Global options.
56//===----------------------------------------------------------------------===//
57
58static llvm::cl::opt<bool>
59Verbose("v", llvm::cl::desc("Enable verbose output"));
60static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000061Stats("print-stats",
62 llvm::cl::desc("Print performance metrics and statistics"));
Chris Lattner4b009652007-07-25 00:24:17 +000063
64enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000065 RewriteObjC, // ObjC->C Rewriter.
Ted Kremeneke1a79d82008-03-19 07:53:42 +000066 HTMLTest, // HTML displayer testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000067 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000068 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000069 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000070 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000071 ASTPrint, // Parse ASTs and print them.
72 ASTDump, // Parse ASTs and dump them.
73 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenek97f75312007-08-21 21:42:03 +000074 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000075 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremenekaa04c512007-09-06 00:17:54 +000076 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek1da5b142008-02-15 00:35:38 +000077 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
78 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek827f93b2008-03-06 00:08:09 +000079 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000080 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek0841c702007-09-25 18:37:20 +000081 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek0a03ce62007-09-17 20:49:30 +000082 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000083 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000084 ParsePrintCallbacks, // Parse and print each callback.
85 ParseSyntaxOnly, // Parse and perform semantic analysis.
86 ParseNoop, // Parse with noop callbacks.
87 RunPreprocessorOnly, // Just lex, no output.
88 PrintPreprocessedInput, // -E mode.
89 DumpTokens // Token dump mode.
90};
91
92static llvm::cl::opt<ProgActions>
93ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
94 llvm::cl::init(ParseSyntaxOnly),
95 llvm::cl::values(
96 clEnumValN(RunPreprocessorOnly, "Eonly",
97 "Just run preprocessor, no output (for timings)"),
98 clEnumValN(PrintPreprocessedInput, "E",
99 "Run preprocessor, emit preprocessed file"),
100 clEnumValN(DumpTokens, "dumptokens",
101 "Run preprocessor, dump internal rep of tokens"),
102 clEnumValN(ParseNoop, "parse-noop",
103 "Run parser with noop callbacks (for timings)"),
104 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
105 "Run parser and perform semantic analysis"),
106 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
107 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000108 clEnumValN(EmitHTML, "emit-html",
109 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000110 clEnumValN(ASTPrint, "ast-print",
111 "Build ASTs and then pretty-print them"),
112 clEnumValN(ASTDump, "ast-dump",
113 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000114 clEnumValN(ASTView, "ast-view",
Chris Lattner4045a8a2007-10-11 00:18:28 +0000115 "Build ASTs and view them with GraphViz."),
Ted Kremenek97f75312007-08-21 21:42:03 +0000116 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000117 "Run parser, then build and print CFGs."),
118 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremenekaa04c512007-09-06 00:17:54 +0000119 "Run parser, then build and view CFGs with Graphviz."),
120 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek05334682007-09-06 21:26:58 +0000121 "Print results of live variable analysis."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000122 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremeneke805c4a2007-09-06 23:00:42 +0000123 "Flag warnings of stores to dead variables."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000124 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000125 "Flag warnings of uses of unitialized variables."),
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000126 clEnumValN(AnalysisGRSimpleVals, "checker-simple",
Chris Lattner2528b5e2008-01-10 01:41:55 +0000127 "Perform path-sensitive constant propagation."),
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000128 clEnumValN(CheckerCFRef, "checker-cfref",
Ted Kremenek827f93b2008-03-06 00:08:09 +0000129 "Run the Core Foundation reference count checker."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000130 clEnumValN(TestSerialization, "test-pickling",
Chris Lattnerc04cf132008-03-09 05:25:01 +0000131 "Run prototype serialization code."),
Chris Lattner4b009652007-07-25 00:24:17 +0000132 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000133 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000134 clEnumValN(EmitBC, "emit-llvm-bc",
135 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000136 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000137 "Build ASTs and emit .ast file"),
Steve Naroff44e81222008-04-14 22:03:09 +0000138 clEnumValN(RewriteObjC, "rewrite-objc",
Ted Kremenek33245d32008-04-16 04:38:45 +0000139 "Playground for the code rewriter"),
Chris Lattner4b009652007-07-25 00:24:17 +0000140 clEnumValEnd));
141
Ted Kremenekd01eae62007-12-19 19:47:59 +0000142
143static llvm::cl::opt<std::string>
144OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000145 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000146 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000147
148//===----------------------------------------------------------------------===//
149// Diagnostic Options
150//===----------------------------------------------------------------------===//
151
Ted Kremenek10389cf2007-09-26 19:42:19 +0000152static llvm::cl::opt<bool>
153VerifyDiagnostics("verify",
154 llvm::cl::desc("Verify emitted diagnostics and warnings."));
155
Ted Kremenekfd75e312008-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
Chris Lattner4b009652007-07-25 00:24:17 +0000161//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000162// Analyzer Options
163//===----------------------------------------------------------------------===//
164
165static llvm::cl::opt<bool>
166VisualizeEG("visualize-egraph",
167 llvm::cl::desc("Display static analysis Exploded Graph."));
168
169static llvm::cl::opt<bool>
170AnalyzeAll("checker-opt-analyze-headers",
171 llvm::cl::desc("Force the static analyzer to analyze "
172 "functions defined in header files."));
173
174//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000175// Language Options
176//===----------------------------------------------------------------------===//
177
178enum LangKind {
179 langkind_unspecified,
180 langkind_c,
181 langkind_c_cpp,
182 langkind_cxx,
183 langkind_cxx_cpp,
184 langkind_objc,
185 langkind_objc_cpp,
186 langkind_objcxx,
187 langkind_objcxx_cpp
188};
189
190/* TODO: GCC also accepts:
191 c-header c++-header objective-c-header objective-c++-header
192 assembler assembler-with-cpp
193 ada, f77*, ratfor (!), f95, java, treelang
194 */
195static llvm::cl::opt<LangKind>
196BaseLang("x", llvm::cl::desc("Base language to compile"),
197 llvm::cl::init(langkind_unspecified),
198 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
199 clEnumValN(langkind_cxx, "c++", "C++"),
200 clEnumValN(langkind_objc, "objective-c", "Objective C"),
201 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
202 clEnumValN(langkind_c_cpp, "c-cpp-output",
203 "Preprocessed C"),
204 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
205 "Preprocessed C++"),
206 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
207 "Preprocessed Objective C"),
208 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
209 "Preprocessed Objective C++"),
210 clEnumValEnd));
211
212static llvm::cl::opt<bool>
213LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
214 llvm::cl::Hidden);
215static llvm::cl::opt<bool>
216LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
217 llvm::cl::Hidden);
218
Ted Kremenek11ad8952007-12-05 23:49:08 +0000219/// InitializeBaseLanguage - Handle the -x foo options.
220static void InitializeBaseLanguage() {
221 if (LangObjC)
222 BaseLang = langkind_objc;
223 else if (LangObjCXX)
224 BaseLang = langkind_objcxx;
225}
226
227static LangKind GetLanguage(const std::string &Filename) {
228 if (BaseLang != langkind_unspecified)
229 return BaseLang;
230
231 std::string::size_type DotPos = Filename.rfind('.');
232
233 if (DotPos == std::string::npos) {
234 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000235 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000236 }
237
Ted Kremenek11ad8952007-12-05 23:49:08 +0000238 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
239 // C header: .h
240 // C++ header: .hh or .H;
241 // assembler no preprocessing: .s
242 // assembler: .S
243 if (Ext == "c")
244 return langkind_c;
245 else if (Ext == "i")
246 return langkind_c_cpp;
247 else if (Ext == "ii")
248 return langkind_cxx_cpp;
249 else if (Ext == "m")
250 return langkind_objc;
251 else if (Ext == "mi")
252 return langkind_objc_cpp;
253 else if (Ext == "mm" || Ext == "M")
254 return langkind_objcxx;
255 else if (Ext == "mii")
256 return langkind_objcxx_cpp;
257 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
258 Ext == "c++" || Ext == "cp" || Ext == "cxx")
259 return langkind_cxx;
260 else
261 return langkind_c;
262}
263
264
265static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000266 // FIXME: implement -fpreprocessed mode.
267 bool NoPreprocess = false;
268
Ted Kremenek11ad8952007-12-05 23:49:08 +0000269 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000270 default: assert(0 && "Unknown language kind!");
271 case langkind_c_cpp:
272 NoPreprocess = true;
273 // FALLTHROUGH
274 case langkind_c:
275 break;
276 case langkind_cxx_cpp:
277 NoPreprocess = true;
278 // FALLTHROUGH
279 case langkind_cxx:
280 Options.CPlusPlus = 1;
281 break;
282 case langkind_objc_cpp:
283 NoPreprocess = true;
284 // FALLTHROUGH
285 case langkind_objc:
286 Options.ObjC1 = Options.ObjC2 = 1;
287 break;
288 case langkind_objcxx_cpp:
289 NoPreprocess = true;
290 // FALLTHROUGH
291 case langkind_objcxx:
292 Options.ObjC1 = Options.ObjC2 = 1;
293 Options.CPlusPlus = 1;
294 break;
295 }
296}
297
298/// LangStds - Language standards we support.
299enum LangStds {
300 lang_unspecified,
301 lang_c89, lang_c94, lang_c99,
302 lang_gnu89, lang_gnu99,
303 lang_cxx98, lang_gnucxx98,
304 lang_cxx0x, lang_gnucxx0x
305};
306
307static llvm::cl::opt<LangStds>
308LangStd("std", llvm::cl::desc("Language standard to compile for"),
309 llvm::cl::init(lang_unspecified),
310 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
311 clEnumValN(lang_c89, "c90", "ISO C 1990"),
312 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
313 clEnumValN(lang_c94, "iso9899:199409",
314 "ISO C 1990 with amendment 1"),
315 clEnumValN(lang_c99, "c99", "ISO C 1999"),
316// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
317 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
318// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
319 clEnumValN(lang_gnu89, "gnu89",
320 "ISO C 1990 with GNU extensions (default for C)"),
321 clEnumValN(lang_gnu99, "gnu99",
322 "ISO C 1999 with GNU extensions"),
323 clEnumValN(lang_gnu99, "gnu9x",
324 "ISO C 1999 with GNU extensions"),
325 clEnumValN(lang_cxx98, "c++98",
326 "ISO C++ 1998 with amendments"),
327 clEnumValN(lang_gnucxx98, "gnu++98",
328 "ISO C++ 1998 with amendments and GNU "
329 "extensions (default for C++)"),
330 clEnumValN(lang_cxx0x, "c++0x",
331 "Upcoming ISO C++ 200x with amendments"),
332 clEnumValN(lang_gnucxx0x, "gnu++0x",
333 "Upcoming ISO C++ 200x with amendments and GNU "
334 "extensions (default for C++)"),
335 clEnumValEnd));
336
337static llvm::cl::opt<bool>
338NoOperatorNames("fno-operator-names",
339 llvm::cl::desc("Do not treat C++ operator name keywords as "
340 "synonyms for operators"));
341
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000342static llvm::cl::opt<bool>
343PascalStrings("fpascal-strings",
344 llvm::cl::desc("Recognize and construct Pascal-style "
345 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000346
347static llvm::cl::opt<bool>
348MSExtensions("fms-extensions",
349 llvm::cl::desc("Accept some non-standard constructs used in "
350 "Microsoft header files. "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000351
352static llvm::cl::opt<bool>
353WritableStrings("fwritable-strings",
354 llvm::cl::desc("Store string literals as writable data."));
Anders Carlssone87cd982007-11-30 04:21:22 +0000355
356static llvm::cl::opt<bool>
357LaxVectorConversions("flax-vector-conversions",
358 llvm::cl::desc("Allow implicit conversions between vectors"
359 " with a different number of elements or "
360 "different element types."));
Chris Lattner4b009652007-07-25 00:24:17 +0000361// FIXME: add:
362// -ansi
363// -trigraphs
364// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000365// -fpascal-strings
Ted Kremenek11ad8952007-12-05 23:49:08 +0000366static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000367 if (LangStd == lang_unspecified) {
368 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000369 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000370 default: assert(0 && "Unknown base language");
371 case langkind_c:
372 case langkind_c_cpp:
373 case langkind_objc:
374 case langkind_objc_cpp:
375 LangStd = lang_gnu99;
376 break;
377 case langkind_cxx:
378 case langkind_cxx_cpp:
379 case langkind_objcxx:
380 case langkind_objcxx_cpp:
381 LangStd = lang_gnucxx98;
382 break;
383 }
384 }
385
386 switch (LangStd) {
387 default: assert(0 && "Unknown language standard!");
388
389 // Fall through from newer standards to older ones. This isn't really right.
390 // FIXME: Enable specifically the right features based on the language stds.
391 case lang_gnucxx0x:
392 case lang_cxx0x:
393 Options.CPlusPlus0x = 1;
394 // FALL THROUGH
395 case lang_gnucxx98:
396 case lang_cxx98:
397 Options.CPlusPlus = 1;
398 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000399 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000400 // FALL THROUGH.
401 case lang_gnu99:
402 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000403 Options.C99 = 1;
404 Options.HexFloats = 1;
405 // FALL THROUGH.
406 case lang_gnu89:
407 Options.BCPLComment = 1; // Only for C99/C++.
408 // FALL THROUGH.
409 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000410 Options.Digraphs = 1; // C94, C99, C++.
411 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000412 case lang_c89:
413 break;
414 }
415
Chris Lattner6ab935b2008-04-05 06:32:51 +0000416 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
417 Options.ImplicitInt = 1;
418 else
419 Options.ImplicitInt = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000420 Options.Trigraphs = 1; // -trigraphs or -ansi
421 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000422 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000423 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000424 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000425 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000426}
427
428//===----------------------------------------------------------------------===//
429// Our DiagnosticClient implementation
430//===----------------------------------------------------------------------===//
431
432// FIXME: Werror should take a list of things, -Werror=foo,bar
433static llvm::cl::opt<bool>
434WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
435
436static llvm::cl::opt<bool>
437WarnOnExtensions("pedantic", llvm::cl::init(false),
438 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
439
440static llvm::cl::opt<bool>
441ErrorOnExtensions("pedantic-errors",
442 llvm::cl::desc("Issue an error on uses of GCC extensions"));
443
444static llvm::cl::opt<bool>
445WarnUnusedMacros("Wunused_macros",
446 llvm::cl::desc("Warn for unused macros in the main translation unit"));
447
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000448static llvm::cl::opt<bool>
449WarnFloatEqual("Wfloat-equal",
450 llvm::cl::desc("Warn about equality comparisons of floating point values."));
451
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000452static llvm::cl::opt<bool>
453WarnNoFormatNonLiteral("Wno-format-nonliteral",
454 llvm::cl::desc("Do not warn about non-literal format strings."));
455
Chris Lattnera616ee32008-01-23 17:19:46 +0000456static llvm::cl::opt<bool>
457WarnUndefMacros("Wundef",
458 llvm::cl::desc("Warn on use of undefined macros in #if's"));
459
460
Chris Lattner4b009652007-07-25 00:24:17 +0000461/// InitializeDiagnostics - Initialize the diagnostic object, based on the
462/// current command line option settings.
463static void InitializeDiagnostics(Diagnostic &Diags) {
464 Diags.setWarningsAsErrors(WarningsAsErrors);
465 Diags.setWarnOnExtensions(WarnOnExtensions);
466 Diags.setErrorOnExtensions(ErrorOnExtensions);
467
468 // Silence the "macro is not used" warning unless requested.
469 if (!WarnUnusedMacros)
470 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000471
472 // Silence "floating point comparison" warnings unless requested.
473 if (!WarnFloatEqual)
474 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000475
476 // Silence "format string is not a string literal" warnings if requested
477 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000478 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
479 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000480 if (!WarnUndefMacros)
481 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000482
483 if (MSExtensions) // MS allows unnamed struct/union fields.
484 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner4b009652007-07-25 00:24:17 +0000485}
486
487//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000488// Analysis-specific options.
489//===----------------------------------------------------------------------===//
490
491static llvm::cl::opt<std::string>
492AnalyzeSpecificFunction("analyze-function",
493 llvm::cl::desc("Run analysis on specific function."));
494
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000495static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000496TrimGraph("trim-egraph",
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000497 llvm::cl::desc("Only show error-related paths in the analysis graph."));
498
Ted Kremenek0118bb52008-02-18 21:21:23 +0000499//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000500// Target Triple Processing.
501//===----------------------------------------------------------------------===//
502
503static llvm::cl::opt<std::string>
504TargetTriple("triple",
505 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
506
Chris Lattnerfc457002008-03-05 01:18:20 +0000507static llvm::cl::opt<std::string>
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000508Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)."));
Ted Kremenek40499482007-12-03 22:06:55 +0000509
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000510static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000511 // Initialize base triple. If a -triple option has been specified, use
512 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000513 std::string Triple = TargetTriple;
514 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000515
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000516 // If -arch foo was specified, remove the architecture from the triple we have
517 // so far and replace it with the specified one.
518 if (Arch.empty())
519 return Triple;
520
Ted Kremenek40499482007-12-03 22:06:55 +0000521 // Decompose the base triple into "arch" and suffix.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000522 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000523
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000524 if (FirstDashIdx == std::string::npos) {
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000525 fprintf(stderr,
526 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner210c0cc2007-12-12 05:01:48 +0000527 Triple.c_str());
528 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000529 }
Ted Kremenek40499482007-12-03 22:06:55 +0000530
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000531 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenek40499482007-12-03 22:06:55 +0000532}
533
534//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000535// Preprocessor Initialization
536//===----------------------------------------------------------------------===//
537
538// FIXME: Preprocessor builtins to support.
539// -A... - Play with #assertions
540// -undef - Undefine all predefined macros
541
542static llvm::cl::list<std::string>
543D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
544 llvm::cl::desc("Predefine the specified macro"));
545static llvm::cl::list<std::string>
546U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
547 llvm::cl::desc("Undefine the specified macro"));
548
Chris Lattner008da782008-01-10 01:53:41 +0000549static llvm::cl::list<std::string>
550ImplicitIncludes("include", llvm::cl::value_desc("file"),
551 llvm::cl::desc("Include file before parsing"));
552
553
Chris Lattner4b009652007-07-25 00:24:17 +0000554// Append a #define line to Buf for Macro. Macro should be of the form XXX,
555// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
556// "#define XXX Y z W". To get a #define with no value, use "XXX=".
557static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
558 const char *Command = "#define ") {
559 Buf.insert(Buf.end(), Command, Command+strlen(Command));
560 if (const char *Equal = strchr(Macro, '=')) {
561 // Turn the = into ' '.
562 Buf.insert(Buf.end(), Macro, Equal);
563 Buf.push_back(' ');
564 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
565 } else {
566 // Push "macroname 1".
567 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
568 Buf.push_back(' ');
569 Buf.push_back('1');
570 }
571 Buf.push_back('\n');
572}
573
Chris Lattner008da782008-01-10 01:53:41 +0000574/// AddImplicitInclude - Add an implicit #include of the specified file to the
575/// predefines buffer.
576static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
577 const char *Inc = "#include \"";
578 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
579 Buf.insert(Buf.end(), File.begin(), File.end());
580 Buf.push_back('"');
581 Buf.push_back('\n');
582}
583
Chris Lattner4b009652007-07-25 00:24:17 +0000584
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000585/// InitializePreprocessor - Initialize the preprocessor getting it and the
586/// environment ready to process a single file. This returns the file ID for the
587/// input file. If a failure happens, it returns 0.
588///
589static unsigned InitializePreprocessor(Preprocessor &PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000590 bool InitializeSourceMgr,
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000591 const std::string &InFile,
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000592 std::vector<char> &PredefineBuffer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000593
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000594
Chris Lattner968982d2007-12-15 20:48:40 +0000595 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000596
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000597 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000598 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000599
600 if (InitializeSourceMgr) {
601 if (InFile != "-") {
602 const FileEntry *File = FileMgr.getFile(InFile);
603 if (File) SourceMgr.createMainFileID(File, SourceLocation());
604 if (SourceMgr.getMainFileID() == 0) {
605 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
606 return 0;
607 }
608 } else {
609 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
610 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
611 if (SourceMgr.getMainFileID() == 0) {
612 fprintf(stderr, "Error reading standard input! Empty?\n");
613 return 0;
614 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000615 }
Chris Lattner4b009652007-07-25 00:24:17 +0000616 }
Sam Bishop61a20782008-04-14 14:41:57 +0000617
Chris Lattner4b009652007-07-25 00:24:17 +0000618 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000619 unsigned d = 0, D = D_macros.size();
620 unsigned u = 0, U = U_macros.size();
621 while (d < D || u < U) {
622 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
623 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
624 else
625 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
626 }
627
Chris Lattner008da782008-01-10 01:53:41 +0000628 // FIXME: Read any files specified by -imacros.
629
630 // Add implicit #includes from -include.
631 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
632 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000633
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000634 // Null terminate PredefinedBuffer and add it. We actually need to make a
635 // copy because PP will own the string.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000636 PredefineBuffer.push_back(0);
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000637
638 char* predefines = new char[PredefineBuffer.size()];
639 std::copy(PredefineBuffer.begin(), PredefineBuffer.end(), predefines);
640 PP.setPredefines(predefines);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000641
642 // Once we've read this, we're done.
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +0000643 return SourceMgr.getMainFileID();
Chris Lattner4b009652007-07-25 00:24:17 +0000644}
645
646//===----------------------------------------------------------------------===//
647// Preprocessor include path information.
648//===----------------------------------------------------------------------===//
649
650// This tool exports a large number of command line options to control how the
651// preprocessor searches for header files. At root, however, the Preprocessor
652// object takes a very simple interface: a list of directories to search for
653//
654// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000655// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000656//
Chris Lattner008da782008-01-10 01:53:41 +0000657// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000658
659static llvm::cl::opt<bool>
660nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
661
662// Various command line options. These four add directories to each chain.
663static llvm::cl::list<std::string>
664F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
665 llvm::cl::desc("Add directory to framework include search path"));
666static llvm::cl::list<std::string>
667I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
668 llvm::cl::desc("Add directory to include search path"));
669static llvm::cl::list<std::string>
670idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
671 llvm::cl::desc("Add directory to AFTER include search path"));
672static llvm::cl::list<std::string>
673iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
674 llvm::cl::desc("Add directory to QUOTE include search path"));
675static llvm::cl::list<std::string>
676isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
677 llvm::cl::desc("Add directory to SYSTEM include search path"));
678
679// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
680static llvm::cl::list<std::string>
681iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
682 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
683static llvm::cl::list<std::string>
684iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
685 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
686static llvm::cl::list<std::string>
687iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
688 llvm::cl::Prefix,
689 llvm::cl::desc("Set directory to include search path with prefix"));
690
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000691static llvm::cl::opt<std::string>
692isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
693 llvm::cl::desc("Set the system root directory (usually /)"));
694
Chris Lattner4b009652007-07-25 00:24:17 +0000695// Finally, implement the code that groks the options above.
696enum IncludeDirGroup {
697 Quoted = 0,
698 Angled,
699 System,
700 After
701};
702
703static std::vector<DirectoryLookup> IncludeGroup[4];
704
705/// AddPath - Add the specified path to the specified group list.
706///
707static void AddPath(const std::string &Path, IncludeDirGroup Group,
708 bool isCXXAware, bool isUserSupplied,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000709 bool isFramework, HeaderSearch &HS) {
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000710 assert(!Path.empty() && "can't handle empty path here");
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000711 FileManager &FM = HS.getFileMgr();
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000712
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000713 // Compute the actual path, taking into consideration -isysroot.
714 llvm::SmallString<256> MappedPath;
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000715
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000716 // Handle isysroot.
717 if (Group == System) {
Chris Lattner2a2702a2007-12-17 06:51:34 +0000718 // FIXME: Portability. This should be a sys::Path interface, this doesn't
719 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000720 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
721 MappedPath.append(isysroot.begin(), isysroot.end());
Chris Lattner4b009652007-07-25 00:24:17 +0000722 }
723
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000724 MappedPath.append(Path.begin(), Path.end());
725
726 // Compute the DirectoryLookup type.
Chris Lattner4b009652007-07-25 00:24:17 +0000727 DirectoryLookup::DirType Type;
728 if (Group == Quoted || Group == Angled)
729 Type = DirectoryLookup::NormalHeaderDir;
730 else if (isCXXAware)
731 Type = DirectoryLookup::SystemHeaderDir;
732 else
733 Type = DirectoryLookup::ExternCSystemHeaderDir;
734
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000735
736 // If the directory exists, add it.
737 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
738 &MappedPath[0]+
739 MappedPath.size())) {
740 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
741 isFramework));
742 return;
743 }
744
Chris Lattnerb7426782007-12-17 07:52:39 +0000745 // Check to see if this is an apple-style headermap (which are not allowed to
746 // be frameworks).
747 if (!isFramework) {
748 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
749 &MappedPath[0]+MappedPath.size())) {
Chris Lattner9af36d32007-12-17 18:34:53 +0000750 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
751 // It is a headermap, add it to the search path.
Chris Lattnerb7426782007-12-17 07:52:39 +0000752 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
753 return;
754 }
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000755 }
756 }
757
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000758 if (Verbose)
759 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000760}
761
762/// RemoveDuplicates - If there are duplicate directory entries in the specified
763/// search list, remove the later (dead) ones.
764static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattnerac139d22007-12-15 23:20:07 +0000765 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerb7426782007-12-17 07:52:39 +0000766 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnercf33e932007-12-17 06:44:29 +0000767 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Chris Lattner4b009652007-07-25 00:24:17 +0000768 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnercf33e932007-12-17 06:44:29 +0000769 if (SearchList[i].isNormalDir()) {
770 // If this isn't the first time we've seen this dir, remove it.
771 if (SeenDirs.insert(SearchList[i].getDir()))
772 continue;
773
Chris Lattner4b009652007-07-25 00:24:17 +0000774 if (Verbose)
775 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
776 SearchList[i].getDir()->getName());
Chris Lattnerb7426782007-12-17 07:52:39 +0000777 } else if (SearchList[i].isFramework()) {
778 // If this isn't the first time we've seen this framework dir, remove it.
779 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
780 continue;
781
782 if (Verbose)
783 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
784 SearchList[i].getFrameworkDir()->getName());
785
Chris Lattnercf33e932007-12-17 06:44:29 +0000786 } else {
787 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
788 // If this isn't the first time we've seen this headermap, remove it.
789 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
790 continue;
791
792 if (Verbose)
793 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
794 SearchList[i].getDir()->getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000795 }
Chris Lattnercf33e932007-12-17 06:44:29 +0000796
797 // This is reached if the current entry is a duplicate.
798 SearchList.erase(SearchList.begin()+i);
799 --i;
Chris Lattner4b009652007-07-25 00:24:17 +0000800 }
801}
802
Chris Lattner4f022a72008-03-01 08:07:28 +0000803// AddEnvVarPaths - Add a list of paths from an environment variable to a
804// header search list.
805//
806static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
807 const char* at = getenv(Name);
808 if (!at)
809 return;
810
811 const char* delim = strchr(at, llvm::sys::PathSeparator);
812 while (delim != 0) {
813 if (delim-at == 0)
814 AddPath(".", Angled, false, true, false, Headers);
815 else
816 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
817 true, false, Headers);
818 at = delim + 1;
819 delim = strchr(at, llvm::sys::PathSeparator);
820 }
821 if (*at == 0)
822 AddPath(".", Angled, false, true, false, Headers);
823 else
824 AddPath(at, Angled, false, true, false, Headers);
825}
826
Chris Lattner4b009652007-07-25 00:24:17 +0000827/// InitializeIncludePaths - Process the -I options and set them in the
828/// HeaderSearch object.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000829static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
830 FileManager &FM, const LangOptions &Lang) {
Chris Lattner4b009652007-07-25 00:24:17 +0000831 // Handle -F... options.
832 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000833 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000834
835 // Handle -I... options.
Chris Lattner45a56e02007-12-05 23:24:17 +0000836 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000837 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000838
839 // Handle -idirafter... options.
840 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000841 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000842
843 // Handle -iquote... options.
844 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000845 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000846
847 // Handle -isystem... options.
848 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000849 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000850
851 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
852 // parallel, processing the values in order of occurance to get the right
853 // prefixes.
854 {
855 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
856 unsigned iprefix_idx = 0;
857 unsigned iwithprefix_idx = 0;
858 unsigned iwithprefixbefore_idx = 0;
859 bool iprefix_done = iprefix_vals.empty();
860 bool iwithprefix_done = iwithprefix_vals.empty();
861 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
862 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
863 if (!iprefix_done &&
864 (iwithprefix_done ||
865 iprefix_vals.getPosition(iprefix_idx) <
866 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
867 (iwithprefixbefore_done ||
868 iprefix_vals.getPosition(iprefix_idx) <
869 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
870 Prefix = iprefix_vals[iprefix_idx];
871 ++iprefix_idx;
872 iprefix_done = iprefix_idx == iprefix_vals.size();
873 } else if (!iwithprefix_done &&
874 (iwithprefixbefore_done ||
875 iwithprefix_vals.getPosition(iwithprefix_idx) <
876 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
877 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000878 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000879 ++iwithprefix_idx;
880 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
881 } else {
882 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000883 Angled, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000884 ++iwithprefixbefore_idx;
885 iwithprefixbefore_done =
886 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
887 }
888 }
889 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000890
891 AddEnvVarPaths("CPATH", Headers);
892 if (Lang.CPlusPlus && Lang.ObjC1)
893 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
894 else if (Lang.CPlusPlus)
895 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
896 else if (Lang.ObjC1)
897 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
898 else
899 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
900
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000901 // Add the clang headers, which are relative to the clang driver.
902 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000903 llvm::sys::Path::GetMainExecutable(Argv0,
904 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000905 if (!MainExecutablePath.isEmpty()) {
906 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
907 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
908 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
909 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
910 }
911
Chris Lattner4b009652007-07-25 00:24:17 +0000912 // FIXME: temporary hack: hard-coded paths.
913 // FIXME: get these from the target?
914 if (!nostdinc) {
915 if (Lang.CPlusPlus) {
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000916 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000917 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000918 false, Headers);
919 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
920 Headers);
Lauro Ramos Venanciof6a66272008-02-15 22:36:38 +0000921
922 // Ubuntu 7.10 - Gutsy Gibbon
923 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
924 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
925 false, Headers);
926 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
927 Headers);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000928
929 // Fedora 8
930 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
Chris Lattner5fdcc302008-04-16 05:21:09 +0000931 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
932 false, Headers);
933 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false,
934 Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000935 }
936
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000937 AddPath("/usr/local/include", System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000938 // leopard
939 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000940 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000941 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000942 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000943 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
944 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000945 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000946
947 // tiger
948 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000949 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000950 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000951 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000952 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
953 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000954 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000955
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000956 // Ubuntu 7.10 - Gutsy Gibbon
957 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattner43b885f2008-02-25 21:04:36 +0000958 false, false, false, Headers);
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000959
Chris Lattner3e254fb2008-04-08 04:40:51 +0000960 // Fedora 8
961 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
962 false, false, false, Headers);
963
Andrew Lenharth6961ec42008-03-24 21:25:48 +0000964 //Debian testing/lenny x86
965 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
966 false, false, false, Headers);
Andrew Lenharthfccd7be2008-03-24 21:39:05 +0000967
968 //Debian testing/lenny amd64
969 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
970 false, false, false, Headers);
Andrew Lenharth6961ec42008-03-24 21:25:48 +0000971
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000972 AddPath("/usr/include", System, false, false, false, Headers);
973 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
974 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000975 }
976
977 // Now that we have collected all of the include paths, merge them all
978 // together and tell the preprocessor about them.
979
980 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
981 std::vector<DirectoryLookup> SearchList;
982 SearchList = IncludeGroup[Angled];
983 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
984 IncludeGroup[System].end());
985 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
986 IncludeGroup[After].end());
987 RemoveDuplicates(SearchList);
988 RemoveDuplicates(IncludeGroup[Quoted]);
989
990 // Prepend QUOTED list on the search list.
991 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
992 IncludeGroup[Quoted].end());
993
994
995 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
996 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
997 DontSearchCurDir);
998
999 // If verbose, print the list of directories that will be searched.
1000 if (Verbose) {
1001 fprintf(stderr, "#include \"...\" search starts here:\n");
1002 unsigned QuotedIdx = IncludeGroup[Quoted].size();
1003 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
1004 if (i == QuotedIdx)
1005 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner1df68f92007-12-17 17:57:27 +00001006 const char *Name = SearchList[i].getName();
1007 const char *Suffix;
Chris Lattner0f64f652007-12-17 17:42:26 +00001008 if (SearchList[i].isNormalDir())
Chris Lattner1df68f92007-12-17 17:57:27 +00001009 Suffix = "";
Chris Lattner0f64f652007-12-17 17:42:26 +00001010 else if (SearchList[i].isFramework())
Chris Lattner1df68f92007-12-17 17:57:27 +00001011 Suffix = " (framework directory)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001012 else {
1013 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner1df68f92007-12-17 17:57:27 +00001014 Suffix = " (headermap)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001015 }
Chris Lattner1df68f92007-12-17 17:57:27 +00001016 fprintf(stderr, " %s%s\n", Name, Suffix);
Chris Lattner4b009652007-07-25 00:24:17 +00001017 }
Chris Lattnerac553842007-12-15 23:11:06 +00001018 fprintf(stderr, "End of search list.\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001019 }
1020}
1021
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001022//===----------------------------------------------------------------------===//
1023// Driver PreprocessorFactory - For lazily generating preprocessors ...
1024//===----------------------------------------------------------------------===//
1025
1026namespace {
1027class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001028 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001029 Diagnostic &Diags;
1030 const LangOptions &LangInfo;
1031 TargetInfo &Target;
1032 SourceManager &SourceMgr;
1033 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001034 std::vector<char> PredefineBuffer;
1035 bool InitializeSourceMgr;
1036
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001037public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001038 DriverPreprocessorFactory(const std::string &infile,
1039 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001040 TargetInfo &target, SourceManager &SM,
1041 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001042 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1043 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1044
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001045
1046 virtual ~DriverPreprocessorFactory() {}
1047
1048 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001049 PredefineBuffer.clear();
1050
1051 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1052 SourceMgr, HeaderInfo);
1053
1054 if (!InitializePreprocessor(*PP, InitializeSourceMgr, InFile,
1055 PredefineBuffer)) {
1056 delete PP;
1057 return NULL;
1058 }
1059
1060 InitializeSourceMgr = false;
1061
1062 return PP;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001063 }
1064};
1065}
Chris Lattner4b009652007-07-25 00:24:17 +00001066
Chris Lattner4b009652007-07-25 00:24:17 +00001067//===----------------------------------------------------------------------===//
1068// Basic Parser driver
1069//===----------------------------------------------------------------------===//
1070
Ted Kremenek17861c52007-12-19 22:51:13 +00001071static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Chris Lattner4b009652007-07-25 00:24:17 +00001072 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001073 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001074
1075 // Parsing the specified input file.
1076 P.ParseTranslationUnit();
1077 delete PA;
1078}
1079
1080//===----------------------------------------------------------------------===//
1081// Main driver
1082//===----------------------------------------------------------------------===//
1083
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001084/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1085/// action. These consumers can operate on both ASTs that are freshly
1086/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001087static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001088 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001089 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001090 Preprocessor *PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001091 PreprocessorFactory *PPF,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001092 llvm::Module *&DestModule) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001093 switch (ProgAction) {
1094 default:
1095 return NULL;
1096
1097 case ASTPrint:
1098 return CreateASTPrinter();
1099
1100 case ASTDump:
1101 return CreateASTDumper();
1102
1103 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001104 return CreateASTViewer();
1105
1106 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001107 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001108
1109 case ParseCFGDump:
1110 case ParseCFGView:
Ted Kremenek83390ec2008-02-22 20:00:31 +00001111 return CreateCFGDumper(ProgAction == ParseCFGView,
1112 AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001113
1114 case AnalysisLiveVariables:
Ted Kremenekb278abb2008-02-22 20:13:09 +00001115 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001116
1117 case WarnDeadStores:
1118 return CreateDeadStoreChecker(Diag);
1119
1120 case WarnUninitVals:
1121 return CreateUnitValsChecker(Diag);
1122
Ted Kremenek3862eb12008-02-14 22:36:46 +00001123 case AnalysisGRSimpleVals:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001124 return CreateGRSimpleVals(Diag, PP, PPF, AnalyzeSpecificFunction,
1125 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek1da5b142008-02-15 00:35:38 +00001126
Ted Kremenek827f93b2008-03-06 00:08:09 +00001127 case CheckerCFRef:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001128 return CreateCFRefChecker(Diag, PP, PPF, AnalyzeSpecificFunction,
1129 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001130
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001131 case TestSerialization:
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001132 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001133
1134 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001135 case EmitBC:
Chris Lattner8d72ee02008-02-06 01:42:25 +00001136 DestModule = new llvm::Module(InFile);
1137 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001138
Ted Kremenekbde30332007-12-19 17:25:59 +00001139 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001140 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +00001141 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek397de012007-12-13 00:37:31 +00001142
Steve Naroff44e81222008-04-14 22:03:09 +00001143 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001144 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001145 }
1146}
1147
Chris Lattner4b009652007-07-25 00:24:17 +00001148/// ProcessInputFile - Process a single input file with the specified state.
1149///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001150static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1151 const std::string &InFile) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001152
1153 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +00001154 bool ClearSourceMgr = false;
Chris Lattner8d72ee02008-02-06 01:42:25 +00001155 llvm::Module *CodeGenModule = 0;
Ted Kremenek6856c632007-09-26 18:39:29 +00001156
Chris Lattner4b009652007-07-25 00:24:17 +00001157 switch (ProgAction) {
1158 default:
Chris Lattner21f72d62008-04-16 06:11:58 +00001159 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
1160 PP.getFileManager(), PP.getLangOptions(), &PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001161 &PPF, CodeGenModule);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001162
1163 if (!Consumer) {
1164 fprintf(stderr, "Unexpected program action!\n");
1165 return;
1166 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001167
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001168 break;
1169
Chris Lattner4b009652007-07-25 00:24:17 +00001170 case DumpTokens: { // Token dump mode.
1171 Token Tok;
1172 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001173 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001174 do {
1175 PP.Lex(Tok);
1176 PP.DumpToken(Tok, true);
1177 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001178 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001179 ClearSourceMgr = true;
1180 break;
1181 }
1182 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1183 Token Tok;
1184 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001185 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001186 do {
1187 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001188 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001189 ClearSourceMgr = true;
1190 break;
1191 }
1192
1193 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001194 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001195 ClearSourceMgr = true;
1196 break;
1197
1198 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001199 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001200 ClearSourceMgr = true;
1201 break;
1202
1203 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001204 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001205 ClearSourceMgr = true;
1206 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001207
Ted Kremenek6856c632007-09-26 18:39:29 +00001208 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +00001209 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001210 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001211 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001212
1213 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001214 if (VerifyDiagnostics)
Ted Kremenek17861c52007-12-19 22:51:13 +00001215 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001216
1217 // This deletes Consumer.
Ted Kremenek17861c52007-12-19 22:51:13 +00001218 ParseAST(PP, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001219 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001220
1221 // If running the code generator, finish up now.
1222 if (CodeGenModule) {
1223 std::ostream *Out;
1224 if (OutputFile == "-") {
1225 Out = llvm::cout.stream();
1226 } else if (!OutputFile.empty()) {
1227 Out = new std::ofstream(OutputFile.c_str(),
1228 std::ios_base::binary|std::ios_base::out);
1229 } else if (InFile == "-") {
1230 Out = llvm::cout.stream();
1231 } else {
1232 llvm::sys::Path Path(InFile);
1233 Path.eraseSuffix();
1234 if (ProgAction == EmitLLVM)
1235 Path.appendSuffix("ll");
1236 else if (ProgAction == EmitBC)
1237 Path.appendSuffix("bc");
1238 else
1239 assert(0 && "Unknown action");
1240 Out = new std::ofstream(Path.toString().c_str(),
1241 std::ios_base::binary|std::ios_base::out);
1242 }
1243
1244 if (ProgAction == EmitLLVM) {
1245 CodeGenModule->print(*Out);
1246 } else {
1247 assert(ProgAction == EmitBC);
1248 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1249 }
1250
1251 if (Out != llvm::cout.stream())
1252 delete Out;
1253 delete CodeGenModule;
1254 }
Chris Lattner4b009652007-07-25 00:24:17 +00001255
1256 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001257 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001258 PP.PrintStats();
1259 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001260 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001261 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001262 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001263 fprintf(stderr, "\n");
1264 }
1265
1266 // For a multi-file compilation, some things are ok with nuking the source
1267 // manager tables, other require stable fileid/macroid's across multiple
1268 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001269 if (ClearSourceMgr)
1270 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001271}
1272
Ted Kremenek80d53372007-12-12 23:41:08 +00001273static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1274 FileManager& FileMgr) {
1275
1276 if (VerifyDiagnostics) {
1277 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1278 exit (1);
1279 }
1280
1281 llvm::sys::Path Filename(InFile);
1282
1283 if (!Filename.isValid()) {
1284 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1285 exit (1);
1286 }
1287
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001288 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001289
1290 if (!TU) {
1291 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1292 InFile.c_str());
1293 exit (1);
1294 }
1295
Ted Kremenekab749372007-12-19 19:27:38 +00001296 // Observe that we use the source file name stored in the deserialized
1297 // translation unit, rather than InFile.
Chris Lattner8d72ee02008-02-06 01:42:25 +00001298 llvm::Module *DestModule;
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001299 llvm::OwningPtr<ASTConsumer>
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001300 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(), 0, 0,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001301 DestModule));
Ted Kremenek80d53372007-12-12 23:41:08 +00001302
1303 if (!Consumer) {
1304 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1305 exit (1);
1306 }
1307
Ted Kremenek17861c52007-12-19 22:51:13 +00001308 Consumer->Initialize(*TU->getContext());
Ted Kremenek80d53372007-12-12 23:41:08 +00001309
Chris Lattner8d72ee02008-02-06 01:42:25 +00001310 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001311 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1312 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001313}
1314
1315
Chris Lattner4b009652007-07-25 00:24:17 +00001316static llvm::cl::list<std::string>
1317InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1318
Ted Kremenek80d53372007-12-12 23:41:08 +00001319static bool isSerializedFile(const std::string& InFile) {
1320 if (InFile.size() < 4)
1321 return false;
1322
1323 const char* s = InFile.c_str()+InFile.size()-4;
1324
1325 return s[0] == '.' &&
1326 s[1] == 'a' &&
1327 s[2] == 's' &&
1328 s[3] == 't';
1329}
1330
Chris Lattner4b009652007-07-25 00:24:17 +00001331
1332int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001333 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001334 llvm::sys::PrintStackTraceOnErrorSignal();
1335
1336 // If no input was specified, read from stdin.
1337 if (InputFilenames.empty())
1338 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001339
Chris Lattner4b009652007-07-25 00:24:17 +00001340 // Create a file manager object to provide access to and cache the filesystem.
1341 FileManager FileMgr;
1342
Ted Kremenekb240e822007-12-11 23:28:38 +00001343 // Create the diagnostic client for reporting errors or for
1344 // implementing -verify.
Ted Kremenekfd75e312008-03-27 06:17:42 +00001345 std::auto_ptr<DiagnosticClient> DiagClient;
1346 TextDiagnostics* TextDiagClient = NULL;
1347
1348 if (!HTMLDiag.empty()) {
Ted Kremenek675ac6f2008-04-16 16:53:18 +00001349
1350 // FIXME: The HTMLDiagnosticClient uses the Preprocessor for
1351 // (optional) syntax highlighting, but we don't have a preprocessor yet.
1352 // Fix this dependency later.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001353 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, 0, 0));
Ted Kremenekfd75e312008-03-27 06:17:42 +00001354 }
1355 else { // Use Text diagnostics.
1356 if (!VerifyDiagnostics) {
1357 // Print diagnostics to stderr by default.
1358 TextDiagClient = new TextDiagnosticPrinter();
1359 } else {
1360 // When checking diagnostics, just buffer them up.
1361 TextDiagClient = new TextDiagnosticBuffer();
1362
1363 if (InputFilenames.size() != 1) {
1364 fprintf(stderr,
1365 "-verify only works on single input files for now.\n");
1366 return 1;
1367 }
Chris Lattner4b009652007-07-25 00:24:17 +00001368 }
Ted Kremenekfd75e312008-03-27 06:17:42 +00001369
1370 assert (TextDiagClient);
1371 DiagClient.reset(TextDiagClient);
Chris Lattner4b009652007-07-25 00:24:17 +00001372 }
1373
1374 // Configure our handling of diagnostics.
1375 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +00001376 InitializeDiagnostics(Diags);
1377
Chris Lattner45a56e02007-12-05 23:24:17 +00001378 // -I- is a deprecated GCC feature, scan for it and reject it.
1379 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1380 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001381 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001382 I_dirs.erase(I_dirs.begin()+i);
1383 --i;
1384 }
1385 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001386
1387 // Get information about the target being compiled for.
1388 std::string Triple = CreateTargetTriple();
1389 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1390 if (Target == 0) {
1391 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1392 Triple.c_str());
1393 fprintf(stderr, "Please use -triple or -arch.\n");
1394 exit(1);
1395 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001396
Chris Lattner4b009652007-07-25 00:24:17 +00001397 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001398 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001399
Ted Kremenek80d53372007-12-12 23:41:08 +00001400 if (isSerializedFile(InFile))
1401 ProcessSerializedFile(InFile,Diags,FileMgr);
1402 else {
1403 /// Create a SourceManager object. This tracks and owns all the file
1404 /// buffers allocated to a translation unit.
1405 SourceManager SourceMgr;
Ted Kremenekb240e822007-12-11 23:28:38 +00001406
Ted Kremenek80d53372007-12-12 23:41:08 +00001407 // Initialize language options, inferring file types from input filenames.
1408 LangOptions LangInfo;
1409 InitializeBaseLanguage();
1410 LangKind LK = GetLanguage(InFile);
1411 InitializeLangOptions(LangInfo, LK);
1412 InitializeLanguageStandard(LangInfo, LK);
1413
1414 // Process the -I options and set them in the HeaderInfo.
1415 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekfd75e312008-03-27 06:17:42 +00001416 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001417 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001418
Ted Kremenek80d53372007-12-12 23:41:08 +00001419 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001420 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001421 SourceMgr, HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001422
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001423 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1424
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001425 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001426 continue;
1427
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001428 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek80d53372007-12-12 23:41:08 +00001429 HeaderInfo.ClearFileInfo();
1430
1431 if (Stats)
1432 SourceMgr.PrintStats();
1433 }
Chris Lattner4b009652007-07-25 00:24:17 +00001434 }
1435
Chris Lattner2c77d852008-03-14 06:12:05 +00001436 delete Target;
1437
Chris Lattner4b009652007-07-25 00:24:17 +00001438 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1439
1440 if (NumDiagnostics)
1441 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1442 (NumDiagnostics == 1 ? "" : "s"));
1443
1444 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001445 FileMgr.PrintStats();
1446 fprintf(stderr, "\n");
1447 }
1448
1449 return Diags.getNumErrors() != 0;
1450}