blob: 714b03eca30745915a0bb21b6fc0bf56dad3f963 [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>
Ted Kremenek339b9c22008-04-17 22:31:54 +000051#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +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 Begemanaabbb122007-12-30 01:38:50 +000061Stats("print-stats",
62 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000063
64enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000065 RewriteObjC, // ObjC->C Rewriter.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000066 RewriteMacros, // Expand macros but not #includes.
Ted Kremenek13e479b2008-03-19 07:53:42 +000067 HTMLTest, // HTML displayer testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000068 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000069 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000070 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000071 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000072 ASTPrint, // Parse ASTs and print them.
73 ASTDump, // Parse ASTs and dump them.
74 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000075 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000076 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000077 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenekd55fe522008-02-15 00:35:38 +000078 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
79 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek2fff37e2008-03-06 00:08:09 +000080 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremenek055c2752007-09-06 23:00:42 +000081 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000082 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000083 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000084 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000085 ParsePrintCallbacks, // Parse and print each callback.
86 ParseSyntaxOnly, // Parse and perform semantic analysis.
87 ParseNoop, // Parse with noop callbacks.
88 RunPreprocessorOnly, // Just lex, no output.
89 PrintPreprocessedInput, // -E mode.
90 DumpTokens // Token dump mode.
91};
92
93static llvm::cl::opt<ProgActions>
94ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
95 llvm::cl::init(ParseSyntaxOnly),
96 llvm::cl::values(
97 clEnumValN(RunPreprocessorOnly, "Eonly",
98 "Just run preprocessor, no output (for timings)"),
99 clEnumValN(PrintPreprocessedInput, "E",
100 "Run preprocessor, emit preprocessed file"),
101 clEnumValN(DumpTokens, "dumptokens",
102 "Run preprocessor, dump internal rep of tokens"),
103 clEnumValN(ParseNoop, "parse-noop",
104 "Run parser with noop callbacks (for timings)"),
105 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
106 "Run parser and perform semantic analysis"),
107 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
108 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000109 clEnumValN(EmitHTML, "emit-html",
110 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000111 clEnumValN(ASTPrint, "ast-print",
112 "Build ASTs and then pretty-print them"),
113 clEnumValN(ASTDump, "ast-dump",
114 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000115 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000116 "Build ASTs and view them with GraphViz"),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000117 clEnumValN(ParseCFGDump, "dump-cfg",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000118 "Run parser, then build and print CFGs"),
Ted Kremenek7dba8602007-08-29 21:56:09 +0000119 clEnumValN(ParseCFGView, "view-cfg",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000120 "Run parser, then build and view CFGs with Graphviz"),
Ted Kremeneke4e63342007-09-06 00:17:54 +0000121 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000122 "Print results of live variable analysis"),
Ted Kremenek786d3372007-09-25 18:05:45 +0000123 clEnumValN(WarnDeadStores, "warn-dead-stores",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000124 "Flag warnings of stores to dead variables"),
Ted Kremenek786d3372007-09-25 18:05:45 +0000125 clEnumValN(WarnUninitVals, "warn-uninit-values",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000126 "Flag warnings of uses of unitialized variables"),
Ted Kremenekd71ed262008-04-10 22:16:52 +0000127 clEnumValN(AnalysisGRSimpleVals, "checker-simple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000128 "Perform path-sensitive constant propagation"),
Ted Kremenekd71ed262008-04-10 22:16:52 +0000129 clEnumValN(CheckerCFRef, "checker-cfref",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000130 "Run the Core Foundation reference count checker"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000131 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000132 "Run prototype serialization code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000133 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000134 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000135 clEnumValN(EmitBC, "emit-llvm-bc",
136 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000137 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000138 "Build ASTs and emit .ast file"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000139 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000140 "Rewrite ObjC into C (code rewriter example)"),
141 clEnumValN(RewriteMacros, "rewrite-macros",
142 "Expand macros without full preprocessing"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 clEnumValEnd));
144
Ted Kremenekccc76472007-12-19 19:47:59 +0000145
146static llvm::cl::opt<std::string>
147OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000148 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000149 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000150
151//===----------------------------------------------------------------------===//
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000152// Code Generator Options
153//===----------------------------------------------------------------------===//
154static llvm::cl::opt<bool>
155GenerateDebugInfo("g",
156 llvm::cl::desc("Generate source level debug information"));
157
158//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000159// Diagnostic Options
160//===----------------------------------------------------------------------===//
161
Ted Kremenek41193e42007-09-26 19:42:19 +0000162static llvm::cl::opt<bool>
163VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000164 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000165
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000166static llvm::cl::opt<std::string>
167HTMLDiag("html-diags",
168 llvm::cl::desc("Generate HTML to report diagnostics"),
169 llvm::cl::value_desc("HTML directory"));
170
Reid Spencer5f016e22007-07-11 17:01:13 +0000171//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000172// Analyzer Options
173//===----------------------------------------------------------------------===//
174
175static llvm::cl::opt<bool>
176VisualizeEG("visualize-egraph",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000177 llvm::cl::desc("Display static analysis Exploded Graph"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000178
179static llvm::cl::opt<bool>
180AnalyzeAll("checker-opt-analyze-headers",
181 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000182 "functions defined in header files"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000183
184//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000185// Language Options
186//===----------------------------------------------------------------------===//
187
188enum LangKind {
189 langkind_unspecified,
190 langkind_c,
191 langkind_c_cpp,
192 langkind_cxx,
193 langkind_cxx_cpp,
194 langkind_objc,
195 langkind_objc_cpp,
196 langkind_objcxx,
197 langkind_objcxx_cpp
198};
199
200/* TODO: GCC also accepts:
201 c-header c++-header objective-c-header objective-c++-header
202 assembler assembler-with-cpp
203 ada, f77*, ratfor (!), f95, java, treelang
204 */
205static llvm::cl::opt<LangKind>
206BaseLang("x", llvm::cl::desc("Base language to compile"),
207 llvm::cl::init(langkind_unspecified),
208 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
209 clEnumValN(langkind_cxx, "c++", "C++"),
210 clEnumValN(langkind_objc, "objective-c", "Objective C"),
211 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
212 clEnumValN(langkind_c_cpp, "c-cpp-output",
213 "Preprocessed C"),
214 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
215 "Preprocessed C++"),
216 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
217 "Preprocessed Objective C"),
218 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
219 "Preprocessed Objective C++"),
220 clEnumValEnd));
221
222static llvm::cl::opt<bool>
223LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
224 llvm::cl::Hidden);
225static llvm::cl::opt<bool>
226LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
227 llvm::cl::Hidden);
228
Ted Kremenek8904f152007-12-05 23:49:08 +0000229/// InitializeBaseLanguage - Handle the -x foo options.
230static void InitializeBaseLanguage() {
231 if (LangObjC)
232 BaseLang = langkind_objc;
233 else if (LangObjCXX)
234 BaseLang = langkind_objcxx;
235}
236
237static LangKind GetLanguage(const std::string &Filename) {
238 if (BaseLang != langkind_unspecified)
239 return BaseLang;
240
241 std::string::size_type DotPos = Filename.rfind('.');
242
243 if (DotPos == std::string::npos) {
244 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000245 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 }
247
Ted Kremenek8904f152007-12-05 23:49:08 +0000248 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
249 // C header: .h
250 // C++ header: .hh or .H;
251 // assembler no preprocessing: .s
252 // assembler: .S
253 if (Ext == "c")
254 return langkind_c;
255 else if (Ext == "i")
256 return langkind_c_cpp;
257 else if (Ext == "ii")
258 return langkind_cxx_cpp;
259 else if (Ext == "m")
260 return langkind_objc;
261 else if (Ext == "mi")
262 return langkind_objc_cpp;
263 else if (Ext == "mm" || Ext == "M")
264 return langkind_objcxx;
265 else if (Ext == "mii")
266 return langkind_objcxx_cpp;
267 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
268 Ext == "c++" || Ext == "cp" || Ext == "cxx")
269 return langkind_cxx;
270 else
271 return langkind_c;
272}
273
274
275static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 // FIXME: implement -fpreprocessed mode.
277 bool NoPreprocess = false;
278
Ted Kremenek8904f152007-12-05 23:49:08 +0000279 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 default: assert(0 && "Unknown language kind!");
281 case langkind_c_cpp:
282 NoPreprocess = true;
283 // FALLTHROUGH
284 case langkind_c:
285 break;
286 case langkind_cxx_cpp:
287 NoPreprocess = true;
288 // FALLTHROUGH
289 case langkind_cxx:
290 Options.CPlusPlus = 1;
291 break;
292 case langkind_objc_cpp:
293 NoPreprocess = true;
294 // FALLTHROUGH
295 case langkind_objc:
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000296 Options.ObjC1 = Options.ObjC2 = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 break;
298 case langkind_objcxx_cpp:
299 NoPreprocess = true;
300 // FALLTHROUGH
301 case langkind_objcxx:
302 Options.ObjC1 = Options.ObjC2 = 1;
303 Options.CPlusPlus = 1;
304 break;
305 }
306}
307
308/// LangStds - Language standards we support.
309enum LangStds {
310 lang_unspecified,
311 lang_c89, lang_c94, lang_c99,
312 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000313 lang_cxx98, lang_gnucxx98,
314 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000315};
316
317static llvm::cl::opt<LangStds>
318LangStd("std", llvm::cl::desc("Language standard to compile for"),
319 llvm::cl::init(lang_unspecified),
320 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
321 clEnumValN(lang_c89, "c90", "ISO C 1990"),
322 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
323 clEnumValN(lang_c94, "iso9899:199409",
324 "ISO C 1990 with amendment 1"),
325 clEnumValN(lang_c99, "c99", "ISO C 1999"),
326// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
327 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
328// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
329 clEnumValN(lang_gnu89, "gnu89",
330 "ISO C 1990 with GNU extensions (default for C)"),
331 clEnumValN(lang_gnu99, "gnu99",
332 "ISO C 1999 with GNU extensions"),
333 clEnumValN(lang_gnu99, "gnu9x",
334 "ISO C 1999 with GNU extensions"),
335 clEnumValN(lang_cxx98, "c++98",
336 "ISO C++ 1998 with amendments"),
337 clEnumValN(lang_gnucxx98, "gnu++98",
338 "ISO C++ 1998 with amendments and GNU "
339 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000340 clEnumValN(lang_cxx0x, "c++0x",
341 "Upcoming ISO C++ 200x with amendments"),
342 clEnumValN(lang_gnucxx0x, "gnu++0x",
343 "Upcoming ISO C++ 200x with amendments and GNU "
344 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 clEnumValEnd));
346
347static llvm::cl::opt<bool>
348NoOperatorNames("fno-operator-names",
349 llvm::cl::desc("Do not treat C++ operator name keywords as "
350 "synonyms for operators"));
351
Anders Carlssonee98ac52007-10-15 02:50:23 +0000352static llvm::cl::opt<bool>
353PascalStrings("fpascal-strings",
354 llvm::cl::desc("Recognize and construct Pascal-style "
355 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000356
357static llvm::cl::opt<bool>
358MSExtensions("fms-extensions",
359 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000360 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000361
362static llvm::cl::opt<bool>
363WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000364 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000365
366static llvm::cl::opt<bool>
367LaxVectorConversions("flax-vector-conversions",
368 llvm::cl::desc("Allow implicit conversions between vectors"
369 " with a different number of elements or "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000370 "different element types"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000371
Reid Spencer5f016e22007-07-11 17:01:13 +0000372// FIXME: add:
373// -ansi
374// -trigraphs
375// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000376// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000377static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 if (LangStd == lang_unspecified) {
379 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000380 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 default: assert(0 && "Unknown base language");
382 case langkind_c:
383 case langkind_c_cpp:
384 case langkind_objc:
385 case langkind_objc_cpp:
386 LangStd = lang_gnu99;
387 break;
388 case langkind_cxx:
389 case langkind_cxx_cpp:
390 case langkind_objcxx:
391 case langkind_objcxx_cpp:
392 LangStd = lang_gnucxx98;
393 break;
394 }
395 }
396
397 switch (LangStd) {
398 default: assert(0 && "Unknown language standard!");
399
400 // Fall through from newer standards to older ones. This isn't really right.
401 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000402 case lang_gnucxx0x:
403 case lang_cxx0x:
404 Options.CPlusPlus0x = 1;
405 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 case lang_gnucxx98:
407 case lang_cxx98:
408 Options.CPlusPlus = 1;
409 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000410 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 // FALL THROUGH.
412 case lang_gnu99:
413 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 Options.C99 = 1;
415 Options.HexFloats = 1;
416 // FALL THROUGH.
417 case lang_gnu89:
418 Options.BCPLComment = 1; // Only for C99/C++.
419 // FALL THROUGH.
420 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000421 Options.Digraphs = 1; // C94, C99, C++.
422 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 case lang_c89:
424 break;
425 }
426
Chris Lattnerd658b562008-04-05 06:32:51 +0000427 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
428 Options.ImplicitInt = 1;
429 else
430 Options.ImplicitInt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 Options.Trigraphs = 1; // -trigraphs or -ansi
432 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000433 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000434 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000435 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000436 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000437}
438
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000439static llvm::cl::opt<bool>
440ObjCExclusiveGC("fobjc-gc-only",
441 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000442 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000443
444static llvm::cl::opt<bool>
445ObjCEnableGC("fobjc-gc",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000446 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000447
448void InitializeGCMode(LangOptions &Options) {
449 if (ObjCExclusiveGC)
450 Options.setGCMode(LangOptions::GCOnly);
451 else if (ObjCEnableGC)
452 Options.setGCMode(LangOptions::HybridGC);
453}
454
455
Reid Spencer5f016e22007-07-11 17:01:13 +0000456//===----------------------------------------------------------------------===//
457// Our DiagnosticClient implementation
458//===----------------------------------------------------------------------===//
459
460// FIXME: Werror should take a list of things, -Werror=foo,bar
461static llvm::cl::opt<bool>
462WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
463
464static llvm::cl::opt<bool>
Chris Lattner5b4681c2008-05-29 15:36:45 +0000465SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
466
467static llvm::cl::opt<bool>
Reid Spencer5f016e22007-07-11 17:01:13 +0000468WarnOnExtensions("pedantic", llvm::cl::init(false),
469 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
470
471static llvm::cl::opt<bool>
472ErrorOnExtensions("pedantic-errors",
473 llvm::cl::desc("Issue an error on uses of GCC extensions"));
474
475static llvm::cl::opt<bool>
476WarnUnusedMacros("Wunused_macros",
477 llvm::cl::desc("Warn for unused macros in the main translation unit"));
478
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000479static llvm::cl::opt<bool>
480WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000481 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000482
Ted Kremenek73da5902007-12-17 17:50:07 +0000483static llvm::cl::opt<bool>
484WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000485 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek73da5902007-12-17 17:50:07 +0000486
Chris Lattner116a4b12008-01-23 17:19:46 +0000487static llvm::cl::opt<bool>
488WarnUndefMacros("Wundef",
489 llvm::cl::desc("Warn on use of undefined macros in #if's"));
490
Chris Lattner37d10842008-05-05 21:18:06 +0000491static llvm::cl::opt<bool>
492WarnImplicitFunctionDeclaration("Wimplicit-function-declaration"
493 "Warn about use of implicitly defined functions");
Chris Lattner116a4b12008-01-23 17:19:46 +0000494
Reid Spencer5f016e22007-07-11 17:01:13 +0000495/// InitializeDiagnostics - Initialize the diagnostic object, based on the
496/// current command line option settings.
497static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner5b4681c2008-05-29 15:36:45 +0000498 Diags.setIgnoreAllWarnings(SilenceWarnings);
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 Diags.setWarningsAsErrors(WarningsAsErrors);
500 Diags.setWarnOnExtensions(WarnOnExtensions);
501 Diags.setErrorOnExtensions(ErrorOnExtensions);
502
503 // Silence the "macro is not used" warning unless requested.
504 if (!WarnUnusedMacros)
505 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000506
507 // Silence "floating point comparison" warnings unless requested.
508 if (!WarnFloatEqual)
509 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000510
511 // Silence "format string is not a string literal" warnings if requested
512 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000513 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
514 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000515 if (!WarnUndefMacros)
516 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000517
Chris Lattner37d10842008-05-05 21:18:06 +0000518 if (!WarnImplicitFunctionDeclaration)
519 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
520 diag::MAP_IGNORE);
521
Steve Naroffe7a37302008-02-11 22:40:08 +0000522 if (MSExtensions) // MS allows unnamed struct/union fields.
523 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner8aedf192008-05-04 23:52:02 +0000524
525 // If -pedantic-errors is set, turn extensions that warn by default into
526 // errors.
527 if (ErrorOnExtensions) {
528 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
529 diag::MAP_ERROR);
530 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
531 diag::MAP_ERROR);
532 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000533}
534
535//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000536// Analysis-specific options.
537//===----------------------------------------------------------------------===//
538
539static llvm::cl::opt<std::string>
540AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000541 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenekcb330932008-02-18 21:21:23 +0000542
Ted Kremenekffe0f432008-03-07 22:58:01 +0000543static llvm::cl::opt<bool>
Ted Kremenekd71ed262008-04-10 22:16:52 +0000544TrimGraph("trim-egraph",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000545 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenekffe0f432008-03-07 22:58:01 +0000546
Ted Kremenekcb330932008-02-18 21:21:23 +0000547//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000548// Target Triple Processing.
549//===----------------------------------------------------------------------===//
550
551static llvm::cl::opt<std::string>
552TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000553 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000554
Chris Lattner42e67372008-03-05 01:18:20 +0000555static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000556Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000557
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000558static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000559 // Initialize base triple. If a -triple option has been specified, use
560 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000561 std::string Triple = TargetTriple;
562 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000563
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000564 // If -arch foo was specified, remove the architecture from the triple we have
565 // so far and replace it with the specified one.
566 if (Arch.empty())
567 return Triple;
568
Ted Kremenekae360762007-12-03 22:06:55 +0000569 // Decompose the base triple into "arch" and suffix.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000570 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000571
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000572 if (FirstDashIdx == std::string::npos) {
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000573 fprintf(stderr,
574 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000575 Triple.c_str());
576 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000577 }
Ted Kremenekae360762007-12-03 22:06:55 +0000578
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000579 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenekae360762007-12-03 22:06:55 +0000580}
581
582//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000583// Preprocessor Initialization
584//===----------------------------------------------------------------------===//
585
586// FIXME: Preprocessor builtins to support.
587// -A... - Play with #assertions
588// -undef - Undefine all predefined macros
589
590static llvm::cl::list<std::string>
591D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
592 llvm::cl::desc("Predefine the specified macro"));
593static llvm::cl::list<std::string>
594U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
595 llvm::cl::desc("Undefine the specified macro"));
596
Chris Lattner64299f82008-01-10 01:53:41 +0000597static llvm::cl::list<std::string>
598ImplicitIncludes("include", llvm::cl::value_desc("file"),
599 llvm::cl::desc("Include file before parsing"));
600
601
Reid Spencer5f016e22007-07-11 17:01:13 +0000602// Append a #define line to Buf for Macro. Macro should be of the form XXX,
603// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
604// "#define XXX Y z W". To get a #define with no value, use "XXX=".
605static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
606 const char *Command = "#define ") {
607 Buf.insert(Buf.end(), Command, Command+strlen(Command));
608 if (const char *Equal = strchr(Macro, '=')) {
609 // Turn the = into ' '.
610 Buf.insert(Buf.end(), Macro, Equal);
611 Buf.push_back(' ');
612 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
613 } else {
614 // Push "macroname 1".
615 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
616 Buf.push_back(' ');
617 Buf.push_back('1');
618 }
619 Buf.push_back('\n');
620}
621
Chris Lattner64299f82008-01-10 01:53:41 +0000622/// AddImplicitInclude - Add an implicit #include of the specified file to the
623/// predefines buffer.
624static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
625 const char *Inc = "#include \"";
626 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
627 Buf.insert(Buf.end(), File.begin(), File.end());
628 Buf.push_back('"');
629 Buf.push_back('\n');
630}
631
Reid Spencer5f016e22007-07-11 17:01:13 +0000632
Chris Lattner53b0dab2007-10-09 22:10:18 +0000633/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000634/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000635///
Chris Lattner51574ea2008-04-19 23:25:44 +0000636static bool InitializePreprocessor(Preprocessor &PP,
637 bool InitializeSourceMgr,
638 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000639 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000640
Chris Lattner53b0dab2007-10-09 22:10:18 +0000641 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000642 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000643
644 if (InitializeSourceMgr) {
645 if (InFile != "-") {
646 const FileEntry *File = FileMgr.getFile(InFile);
647 if (File) SourceMgr.createMainFileID(File, SourceLocation());
648 if (SourceMgr.getMainFileID() == 0) {
649 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner51574ea2008-04-19 23:25:44 +0000650 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000651 }
652 } else {
653 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
654 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
655 if (SourceMgr.getMainFileID() == 0) {
656 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner51574ea2008-04-19 23:25:44 +0000657 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000658 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000659 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000661
Chris Lattneraa391972008-04-19 23:09:31 +0000662 std::vector<char> PredefineBuffer;
663
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000665 unsigned d = 0, D = D_macros.size();
666 unsigned u = 0, U = U_macros.size();
667 while (d < D || u < U) {
668 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
669 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
670 else
671 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
672 }
673
Chris Lattner64299f82008-01-10 01:53:41 +0000674 // FIXME: Read any files specified by -imacros.
675
676 // Add implicit #includes from -include.
677 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
678 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000679
Chris Lattneraa391972008-04-19 23:09:31 +0000680 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000681 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000682 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000683
684 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000685 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000686}
687
688//===----------------------------------------------------------------------===//
689// Preprocessor include path information.
690//===----------------------------------------------------------------------===//
691
692// This tool exports a large number of command line options to control how the
693// preprocessor searches for header files. At root, however, the Preprocessor
694// object takes a very simple interface: a list of directories to search for
695//
696// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000697// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000698//
Chris Lattner64299f82008-01-10 01:53:41 +0000699// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000700
701static llvm::cl::opt<bool>
702nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
703
704// Various command line options. These four add directories to each chain.
705static llvm::cl::list<std::string>
706F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
707 llvm::cl::desc("Add directory to framework include search path"));
708static llvm::cl::list<std::string>
709I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
710 llvm::cl::desc("Add directory to include search path"));
711static llvm::cl::list<std::string>
712idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
713 llvm::cl::desc("Add directory to AFTER include search path"));
714static llvm::cl::list<std::string>
715iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
716 llvm::cl::desc("Add directory to QUOTE include search path"));
717static llvm::cl::list<std::string>
718isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
719 llvm::cl::desc("Add directory to SYSTEM include search path"));
720
721// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
722static llvm::cl::list<std::string>
723iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
724 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
725static llvm::cl::list<std::string>
726iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
727 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
728static llvm::cl::list<std::string>
729iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
730 llvm::cl::Prefix,
731 llvm::cl::desc("Set directory to include search path with prefix"));
732
Chris Lattner0c946412007-08-26 17:47:35 +0000733static llvm::cl::opt<std::string>
734isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
735 llvm::cl::desc("Set the system root directory (usually /)"));
736
Reid Spencer5f016e22007-07-11 17:01:13 +0000737// Finally, implement the code that groks the options above.
738enum IncludeDirGroup {
739 Quoted = 0,
740 Angled,
741 System,
742 After
743};
744
745static std::vector<DirectoryLookup> IncludeGroup[4];
746
747/// AddPath - Add the specified path to the specified group list.
748///
749static void AddPath(const std::string &Path, IncludeDirGroup Group,
750 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000751 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000752 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000753 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000754
Chris Lattnerd6655272007-12-17 05:59:27 +0000755 // Compute the actual path, taking into consideration -isysroot.
756 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000757
Chris Lattnerd6655272007-12-17 05:59:27 +0000758 // Handle isysroot.
759 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000760 // FIXME: Portability. This should be a sys::Path interface, this doesn't
761 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000762 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
763 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 }
765
Chris Lattnerd6655272007-12-17 05:59:27 +0000766 MappedPath.append(Path.begin(), Path.end());
767
768 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 DirectoryLookup::DirType Type;
770 if (Group == Quoted || Group == Angled)
771 Type = DirectoryLookup::NormalHeaderDir;
772 else if (isCXXAware)
773 Type = DirectoryLookup::SystemHeaderDir;
774 else
775 Type = DirectoryLookup::ExternCSystemHeaderDir;
776
Chris Lattnerd6655272007-12-17 05:59:27 +0000777
778 // If the directory exists, add it.
779 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
780 &MappedPath[0]+
781 MappedPath.size())) {
782 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
783 isFramework));
784 return;
785 }
786
Chris Lattnerdf772332007-12-17 07:52:39 +0000787 // Check to see if this is an apple-style headermap (which are not allowed to
788 // be frameworks).
789 if (!isFramework) {
790 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
791 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000792 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
793 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000794 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
795 return;
796 }
Chris Lattner822da612007-12-17 06:36:45 +0000797 }
798 }
799
Chris Lattnerd6655272007-12-17 05:59:27 +0000800 if (Verbose)
801 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000802}
803
804/// RemoveDuplicates - If there are duplicate directory entries in the specified
805/// search list, remove the later (dead) ones.
806static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000807 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000808 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000809 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000811 if (SearchList[i].isNormalDir()) {
812 // If this isn't the first time we've seen this dir, remove it.
813 if (SeenDirs.insert(SearchList[i].getDir()))
814 continue;
815
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 if (Verbose)
817 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
818 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000819 } else if (SearchList[i].isFramework()) {
820 // If this isn't the first time we've seen this framework dir, remove it.
821 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
822 continue;
823
824 if (Verbose)
825 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
826 SearchList[i].getFrameworkDir()->getName());
827
Chris Lattnerb94c7072007-12-17 06:44:29 +0000828 } else {
829 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
830 // If this isn't the first time we've seen this headermap, remove it.
831 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
832 continue;
833
834 if (Verbose)
835 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
836 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000838
839 // This is reached if the current entry is a duplicate.
840 SearchList.erase(SearchList.begin()+i);
841 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 }
843}
844
Chris Lattner5f9eae52008-03-01 08:07:28 +0000845// AddEnvVarPaths - Add a list of paths from an environment variable to a
846// header search list.
847//
848static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
849 const char* at = getenv(Name);
850 if (!at)
851 return;
852
853 const char* delim = strchr(at, llvm::sys::PathSeparator);
854 while (delim != 0) {
855 if (delim-at == 0)
856 AddPath(".", Angled, false, true, false, Headers);
857 else
858 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
859 true, false, Headers);
860 at = delim + 1;
861 delim = strchr(at, llvm::sys::PathSeparator);
862 }
863 if (*at == 0)
864 AddPath(".", Angled, false, true, false, Headers);
865 else
866 AddPath(at, Angled, false, true, false, Headers);
867}
868
Reid Spencer5f016e22007-07-11 17:01:13 +0000869/// InitializeIncludePaths - Process the -I options and set them in the
870/// HeaderSearch object.
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000871static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
872 FileManager &FM, const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 // Handle -F... options.
874 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000875 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000876
877 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000878 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000879 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000880
881 // Handle -idirafter... options.
882 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000883 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000884
885 // Handle -iquote... options.
886 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000887 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000888
889 // Handle -isystem... options.
890 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000891 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000892
893 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
894 // parallel, processing the values in order of occurance to get the right
895 // prefixes.
896 {
897 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
898 unsigned iprefix_idx = 0;
899 unsigned iwithprefix_idx = 0;
900 unsigned iwithprefixbefore_idx = 0;
901 bool iprefix_done = iprefix_vals.empty();
902 bool iwithprefix_done = iwithprefix_vals.empty();
903 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
904 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
905 if (!iprefix_done &&
906 (iwithprefix_done ||
907 iprefix_vals.getPosition(iprefix_idx) <
908 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
909 (iwithprefixbefore_done ||
910 iprefix_vals.getPosition(iprefix_idx) <
911 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
912 Prefix = iprefix_vals[iprefix_idx];
913 ++iprefix_idx;
914 iprefix_done = iprefix_idx == iprefix_vals.size();
915 } else if (!iwithprefix_done &&
916 (iwithprefixbefore_done ||
917 iwithprefix_vals.getPosition(iwithprefix_idx) <
918 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
919 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000920 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 ++iwithprefix_idx;
922 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
923 } else {
924 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000925 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 ++iwithprefixbefore_idx;
927 iwithprefixbefore_done =
928 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
929 }
930 }
931 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000932
933 AddEnvVarPaths("CPATH", Headers);
934 if (Lang.CPlusPlus && Lang.ObjC1)
935 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
936 else if (Lang.CPlusPlus)
937 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
938 else if (Lang.ObjC1)
939 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
940 else
941 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
942
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000943 // Add the clang headers, which are relative to the clang driver.
944 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000945 llvm::sys::Path::GetMainExecutable(Argv0,
946 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000947 if (!MainExecutablePath.isEmpty()) {
948 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
949 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
950 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
951 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
952 }
953
Reid Spencer5f016e22007-07-11 17:01:13 +0000954 // FIXME: temporary hack: hard-coded paths.
955 // FIXME: get these from the target?
956 if (!nostdinc) {
957 if (Lang.CPlusPlus) {
Ted Kremenek1d3cce32008-05-22 15:26:22 +0000958 AddPath("/usr/include/c++/4.2.1", System, true, false, false, Headers);
959 AddPath("/usr/include/c++/4.2.1/i686-apple-darwin10", System, true, false,
960 false, Headers);
961 AddPath("/usr/include/c++/4.2.1/backward", System, true, false, false,
962 Headers);
963
Chris Lattner822da612007-12-17 06:36:45 +0000964 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000965 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000966 false, Headers);
967 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
968 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000969
970 // Ubuntu 7.10 - Gutsy Gibbon
971 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
972 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
973 false, Headers);
974 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
975 Headers);
Chris Lattner04421082008-04-08 04:40:51 +0000976
977 // Fedora 8
978 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
Chris Lattner8ac661c2008-04-16 05:21:09 +0000979 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
980 false, Headers);
981 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false,
982 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000983 }
984
Chris Lattner822da612007-12-17 06:36:45 +0000985 AddPath("/usr/local/include", System, false, false, false, Headers);
Ted Kremenek1d3cce32008-05-22 15:26:22 +0000986
987 AddPath("/usr/lib/gcc/i686-apple-darwin10/4.2.1/include", System,
988 false, false, false, Headers);
989 AddPath("/usr/lib/gcc/powerpc-apple-darwin10/4.2.1/include",
990 System, false, false, false, Headers);
991
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 // leopard
993 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000994 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000995 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000996 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
998 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000999 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001000
1001 // tiger
1002 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +00001003 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001004 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +00001005 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001006 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
1007 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +00001008 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001009
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +00001010 // Ubuntu 7.10 - Gutsy Gibbon
1011 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001012 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +00001013
Chris Lattner04421082008-04-08 04:40:51 +00001014 // Fedora 8
1015 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
1016 false, false, false, Headers);
1017
Andrew Lenharth92d56b72008-03-24 21:25:48 +00001018 //Debian testing/lenny x86
1019 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
1020 false, false, false, Headers);
Andrew Lenharthf24964c2008-03-24 21:39:05 +00001021
1022 //Debian testing/lenny amd64
1023 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
1024 false, false, false, Headers);
Andrew Lenharth92d56b72008-03-24 21:25:48 +00001025
Chris Lattner822da612007-12-17 06:36:45 +00001026 AddPath("/usr/include", System, false, false, false, Headers);
1027 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
1028 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001029 }
1030
1031 // Now that we have collected all of the include paths, merge them all
1032 // together and tell the preprocessor about them.
1033
1034 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
1035 std::vector<DirectoryLookup> SearchList;
1036 SearchList = IncludeGroup[Angled];
1037 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
1038 IncludeGroup[System].end());
1039 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
1040 IncludeGroup[After].end());
1041 RemoveDuplicates(SearchList);
1042 RemoveDuplicates(IncludeGroup[Quoted]);
1043
1044 // Prepend QUOTED list on the search list.
1045 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
1046 IncludeGroup[Quoted].end());
1047
1048
1049 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
1050 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
1051 DontSearchCurDir);
1052
1053 // If verbose, print the list of directories that will be searched.
1054 if (Verbose) {
1055 fprintf(stderr, "#include \"...\" search starts here:\n");
1056 unsigned QuotedIdx = IncludeGroup[Quoted].size();
1057 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
1058 if (i == QuotedIdx)
1059 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +00001060 const char *Name = SearchList[i].getName();
1061 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +00001062 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +00001063 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +00001064 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +00001065 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +00001066 else {
1067 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +00001068 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +00001069 }
Chris Lattner3af66a92007-12-17 17:57:27 +00001070 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 }
Chris Lattner80e17152007-12-15 23:11:06 +00001072 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 }
1074}
1075
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001076//===----------------------------------------------------------------------===//
1077// Driver PreprocessorFactory - For lazily generating preprocessors ...
1078//===----------------------------------------------------------------------===//
1079
1080namespace {
1081class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001082 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001083 Diagnostic &Diags;
1084 const LangOptions &LangInfo;
1085 TargetInfo &Target;
1086 SourceManager &SourceMgr;
1087 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001088 bool InitializeSourceMgr;
1089
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001090public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001091 DriverPreprocessorFactory(const std::string &infile,
1092 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001093 TargetInfo &target, SourceManager &SM,
1094 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001095 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1096 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1097
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001098
1099 virtual ~DriverPreprocessorFactory() {}
1100
1101 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001102 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1103 SourceMgr, HeaderInfo);
1104
Chris Lattner51574ea2008-04-19 23:25:44 +00001105 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001106 delete PP;
1107 return NULL;
1108 }
1109
1110 InitializeSourceMgr = false;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001111 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001112 }
1113};
1114}
Reid Spencer5f016e22007-07-11 17:01:13 +00001115
Reid Spencer5f016e22007-07-11 17:01:13 +00001116//===----------------------------------------------------------------------===//
1117// Basic Parser driver
1118//===----------------------------------------------------------------------===//
1119
Chris Lattner51574ea2008-04-19 23:25:44 +00001120static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001121 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001122 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001123
1124 // Parsing the specified input file.
1125 P.ParseTranslationUnit();
1126 delete PA;
1127}
1128
1129//===----------------------------------------------------------------------===//
1130// Main driver
1131//===----------------------------------------------------------------------===//
1132
Ted Kremenekdb094a22007-12-05 18:27:04 +00001133/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1134/// action. These consumers can operate on both ASTs that are freshly
1135/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001136static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001137 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001138 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001139 Preprocessor *PP,
Ted Kremenek339b9c22008-04-17 22:31:54 +00001140 PreprocessorFactory *PPF,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001141 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001142 switch (ProgAction) {
1143 default:
1144 return NULL;
1145
1146 case ASTPrint:
1147 return CreateASTPrinter();
1148
1149 case ASTDump:
1150 return CreateASTDumper();
1151
1152 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001153 return CreateASTViewer();
1154
1155 case EmitHTML:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001156 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001157
1158 case ParseCFGDump:
1159 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001160 return CreateCFGDumper(ProgAction == ParseCFGView,
1161 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001162
1163 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001164 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001165
1166 case WarnDeadStores:
1167 return CreateDeadStoreChecker(Diag);
1168
1169 case WarnUninitVals:
1170 return CreateUnitValsChecker(Diag);
1171
Ted Kremeneke01c9872008-02-14 22:36:46 +00001172 case AnalysisGRSimpleVals:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001173 return CreateGRSimpleVals(Diag, PP, PPF, AnalyzeSpecificFunction,
1174 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001175
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001176 case CheckerCFRef:
Ted Kremeneke5c30122008-04-29 05:13:59 +00001177 return CreateCFRefChecker(Diag, PP, PPF, LangOpts,
1178 AnalyzeSpecificFunction,
Ted Kremenek339b9c22008-04-17 22:31:54 +00001179 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001180
Ted Kremenekdb094a22007-12-05 18:27:04 +00001181 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001182 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001183
1184 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001185 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001186 DestModule = new llvm::Module(InFile);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +00001187 return CreateLLVMCodeGen(Diag, LangOpts, DestModule, GenerateDebugInfo);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001188
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001189 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001190 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001191 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001192
Steve Naroffb29b4272008-04-14 22:03:09 +00001193 case RewriteObjC:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001194 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001195 }
1196}
1197
Reid Spencer5f016e22007-07-11 17:01:13 +00001198/// ProcessInputFile - Process a single input file with the specified state.
1199///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001200static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1201 const std::string &InFile) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001202
1203 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001204 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001205 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001206
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 switch (ProgAction) {
1208 default:
Chris Lattner3245a0a2008-04-16 06:11:58 +00001209 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
1210 PP.getFileManager(), PP.getLangOptions(), &PP,
Ted Kremenek339b9c22008-04-17 22:31:54 +00001211 &PPF, CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001212
1213 if (!Consumer) {
1214 fprintf(stderr, "Unexpected program action!\n");
1215 return;
1216 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001217
Ted Kremenekdb094a22007-12-05 18:27:04 +00001218 break;
1219
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001221 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001222 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001223 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 do {
1225 PP.Lex(Tok);
1226 PP.DumpToken(Tok, true);
1227 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001228 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001229 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 break;
1231 }
1232 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001233 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001235 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 do {
1237 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001238 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001239 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 break;
1241 }
1242
1243 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001244 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001245 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001247
Reid Spencer5f016e22007-07-11 17:01:13 +00001248 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001249 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001250 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 break;
1252
1253 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001254 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001255 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001257
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001258 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001259 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001260 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001261
1262 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001263 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001264 ClearSourceMgr = true;
1265 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001266 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001267
1268 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001269 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001270 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001271
1272 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001273 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001275
1276 // If running the code generator, finish up now.
1277 if (CodeGenModule) {
1278 std::ostream *Out;
1279 if (OutputFile == "-") {
1280 Out = llvm::cout.stream();
1281 } else if (!OutputFile.empty()) {
1282 Out = new std::ofstream(OutputFile.c_str(),
1283 std::ios_base::binary|std::ios_base::out);
1284 } else if (InFile == "-") {
1285 Out = llvm::cout.stream();
1286 } else {
1287 llvm::sys::Path Path(InFile);
1288 Path.eraseSuffix();
1289 if (ProgAction == EmitLLVM)
1290 Path.appendSuffix("ll");
1291 else if (ProgAction == EmitBC)
1292 Path.appendSuffix("bc");
1293 else
1294 assert(0 && "Unknown action");
1295 Out = new std::ofstream(Path.toString().c_str(),
1296 std::ios_base::binary|std::ios_base::out);
1297 }
1298
1299 if (ProgAction == EmitLLVM) {
1300 CodeGenModule->print(*Out);
1301 } else {
1302 assert(ProgAction == EmitBC);
1303 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1304 }
1305
1306 if (Out != llvm::cout.stream())
1307 delete Out;
1308 delete CodeGenModule;
1309 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001310
1311 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001312 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001313 PP.PrintStats();
1314 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001315 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001316 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001317 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 fprintf(stderr, "\n");
1319 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001320
1321 // For a multi-file compilation, some things are ok with nuking the source
1322 // manager tables, other require stable fileid/macroid's across multiple
1323 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001324 if (ClearSourceMgr)
1325 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001326}
1327
Ted Kremenek20e97482007-12-12 23:41:08 +00001328static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1329 FileManager& FileMgr) {
1330
1331 if (VerifyDiagnostics) {
1332 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1333 exit (1);
1334 }
1335
1336 llvm::sys::Path Filename(InFile);
1337
1338 if (!Filename.isValid()) {
1339 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1340 exit (1);
1341 }
1342
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001343 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001344
1345 if (!TU) {
1346 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1347 InFile.c_str());
1348 exit (1);
1349 }
1350
Ted Kremenek63ea8632007-12-19 19:27:38 +00001351 // Observe that we use the source file name stored in the deserialized
1352 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001353 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001354 llvm::OwningPtr<ASTConsumer>
Ted Kremenek339b9c22008-04-17 22:31:54 +00001355 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(), 0, 0,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001356 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001357
1358 if (!Consumer) {
1359 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1360 exit (1);
1361 }
1362
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001363 Consumer->Initialize(TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001364
Chris Lattnere66b65c2008-02-06 01:42:25 +00001365 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001366 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1367 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001368}
1369
1370
Reid Spencer5f016e22007-07-11 17:01:13 +00001371static llvm::cl::list<std::string>
1372InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1373
Ted Kremenek20e97482007-12-12 23:41:08 +00001374static bool isSerializedFile(const std::string& InFile) {
1375 if (InFile.size() < 4)
1376 return false;
1377
1378 const char* s = InFile.c_str()+InFile.size()-4;
1379
1380 return s[0] == '.' &&
1381 s[1] == 'a' &&
1382 s[2] == 's' &&
1383 s[3] == 't';
1384}
1385
Reid Spencer5f016e22007-07-11 17:01:13 +00001386
1387int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001388 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 llvm::sys::PrintStackTraceOnErrorSignal();
1390
1391 // If no input was specified, read from stdin.
1392 if (InputFilenames.empty())
1393 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001394
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 // Create a file manager object to provide access to and cache the filesystem.
1396 FileManager FileMgr;
1397
Ted Kremenek31e703b2007-12-11 23:28:38 +00001398 // Create the diagnostic client for reporting errors or for
1399 // implementing -verify.
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001400 std::auto_ptr<DiagnosticClient> DiagClient;
1401 TextDiagnostics* TextDiagClient = NULL;
1402
1403 if (!HTMLDiag.empty()) {
Ted Kremeneka760f5f2008-04-16 16:53:18 +00001404
1405 // FIXME: The HTMLDiagnosticClient uses the Preprocessor for
1406 // (optional) syntax highlighting, but we don't have a preprocessor yet.
1407 // Fix this dependency later.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001408 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, 0, 0));
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001409 }
1410 else { // Use Text diagnostics.
1411 if (!VerifyDiagnostics) {
1412 // Print diagnostics to stderr by default.
1413 TextDiagClient = new TextDiagnosticPrinter();
1414 } else {
1415 // When checking diagnostics, just buffer them up.
1416 TextDiagClient = new TextDiagnosticBuffer();
1417
1418 if (InputFilenames.size() != 1) {
1419 fprintf(stderr,
1420 "-verify only works on single input files for now.\n");
1421 return 1;
1422 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 }
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001424
1425 assert (TextDiagClient);
1426 DiagClient.reset(TextDiagClient);
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 }
1428
1429 // Configure our handling of diagnostics.
1430 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001431 InitializeDiagnostics(Diags);
1432
Chris Lattner4f037832007-12-05 23:24:17 +00001433 // -I- is a deprecated GCC feature, scan for it and reject it.
1434 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1435 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001436 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001437 I_dirs.erase(I_dirs.begin()+i);
1438 --i;
1439 }
1440 }
Chris Lattner11215192008-03-14 06:12:05 +00001441
1442 // Get information about the target being compiled for.
1443 std::string Triple = CreateTargetTriple();
1444 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1445 if (Target == 0) {
1446 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1447 Triple.c_str());
1448 fprintf(stderr, "Please use -triple or -arch.\n");
1449 exit(1);
1450 }
Chris Lattner4f037832007-12-05 23:24:17 +00001451
Reid Spencer5f016e22007-07-11 17:01:13 +00001452 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001453 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001454
Ted Kremenek20e97482007-12-12 23:41:08 +00001455 if (isSerializedFile(InFile))
1456 ProcessSerializedFile(InFile,Diags,FileMgr);
1457 else {
1458 /// Create a SourceManager object. This tracks and owns all the file
1459 /// buffers allocated to a translation unit.
1460 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001461
Ted Kremenek20e97482007-12-12 23:41:08 +00001462 // Initialize language options, inferring file types from input filenames.
1463 LangOptions LangInfo;
1464 InitializeBaseLanguage();
1465 LangKind LK = GetLanguage(InFile);
1466 InitializeLangOptions(LangInfo, LK);
1467 InitializeLanguageStandard(LangInfo, LK);
Ted Kremenek01d9dbf2008-04-29 04:37:03 +00001468 InitializeGCMode(LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001469
1470 // Process the -I options and set them in the HeaderInfo.
1471 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001472 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001473 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001474
Ted Kremenek20e97482007-12-12 23:41:08 +00001475 // Set up the preprocessor with these options.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001476 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001477 SourceMgr, HeaderInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001478
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001479 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1480
Ted Kremenek339b9c22008-04-17 22:31:54 +00001481 if (!PP)
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001482 continue;
1483
Ted Kremenek339b9c22008-04-17 22:31:54 +00001484 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek20e97482007-12-12 23:41:08 +00001485 HeaderInfo.ClearFileInfo();
1486
1487 if (Stats)
1488 SourceMgr.PrintStats();
1489 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 }
1491
Chris Lattner11215192008-03-14 06:12:05 +00001492 delete Target;
1493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1495
1496 if (NumDiagnostics)
1497 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1498 (NumDiagnostics == 1 ? "" : "s"));
1499
1500 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 FileMgr.PrintStats();
1502 fprintf(stderr, "\n");
1503 }
1504
Chris Lattner96f1a642007-07-21 05:40:53 +00001505 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001506}