blob: 5eec67ca87921d52337843239c60efd25be2b445 [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>
Ted Kremenek358256d2008-05-30 16:42:02 +0000492WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
493 llvm::cl::desc("Warn about uses 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) {
Ted Kremenekf3721112008-05-31 00:27:00 +0000873 // Handle -I... and -F... options, walking the lists in parallel.
874 unsigned Iidx = 0, Fidx = 0;
875 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
876 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
877 AddPath(I_dirs[Iidx], Angled, false, true, false, Headers);
878 ++Iidx;
879 } else {
880 AddPath(F_dirs[Fidx], Angled, false, true, true, Headers);
881 ++Fidx;
882 }
883 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000884
Ted Kremenekf3721112008-05-31 00:27:00 +0000885 // Consume what's left from whatever list was longer.
886 for (; Iidx != I_dirs.size(); ++Iidx)
887 AddPath(I_dirs[Iidx], Angled, false, true, false, Headers);
888 for (; Fidx != F_dirs.size(); ++Fidx)
889 AddPath(F_dirs[Fidx], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000890
891 // Handle -idirafter... options.
892 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000893 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000894
895 // Handle -iquote... options.
896 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000897 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000898
899 // Handle -isystem... options.
900 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000901 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000902
903 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
904 // parallel, processing the values in order of occurance to get the right
905 // prefixes.
906 {
907 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
908 unsigned iprefix_idx = 0;
909 unsigned iwithprefix_idx = 0;
910 unsigned iwithprefixbefore_idx = 0;
911 bool iprefix_done = iprefix_vals.empty();
912 bool iwithprefix_done = iwithprefix_vals.empty();
913 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
914 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
915 if (!iprefix_done &&
916 (iwithprefix_done ||
917 iprefix_vals.getPosition(iprefix_idx) <
918 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
919 (iwithprefixbefore_done ||
920 iprefix_vals.getPosition(iprefix_idx) <
921 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
922 Prefix = iprefix_vals[iprefix_idx];
923 ++iprefix_idx;
924 iprefix_done = iprefix_idx == iprefix_vals.size();
925 } else if (!iwithprefix_done &&
926 (iwithprefixbefore_done ||
927 iwithprefix_vals.getPosition(iwithprefix_idx) <
928 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
929 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000930 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000931 ++iwithprefix_idx;
932 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
933 } else {
934 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000935 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 ++iwithprefixbefore_idx;
937 iwithprefixbefore_done =
938 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
939 }
940 }
941 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000942
943 AddEnvVarPaths("CPATH", Headers);
944 if (Lang.CPlusPlus && Lang.ObjC1)
945 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
946 else if (Lang.CPlusPlus)
947 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
948 else if (Lang.ObjC1)
949 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
950 else
951 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
952
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000953 // Add the clang headers, which are relative to the clang driver.
954 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000955 llvm::sys::Path::GetMainExecutable(Argv0,
956 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000957 if (!MainExecutablePath.isEmpty()) {
958 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
959 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
960 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
961 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
962 }
963
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 // FIXME: temporary hack: hard-coded paths.
965 // FIXME: get these from the target?
966 if (!nostdinc) {
967 if (Lang.CPlusPlus) {
Ted Kremenek1d3cce32008-05-22 15:26:22 +0000968 AddPath("/usr/include/c++/4.2.1", System, true, false, false, Headers);
969 AddPath("/usr/include/c++/4.2.1/i686-apple-darwin10", System, true, false,
970 false, Headers);
971 AddPath("/usr/include/c++/4.2.1/backward", System, true, false, false,
972 Headers);
973
Chris Lattner822da612007-12-17 06:36:45 +0000974 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000976 false, Headers);
977 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
978 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000979
980 // Ubuntu 7.10 - Gutsy Gibbon
981 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
982 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
983 false, Headers);
984 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
985 Headers);
Chris Lattner04421082008-04-08 04:40:51 +0000986
987 // Fedora 8
988 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
Chris Lattner8ac661c2008-04-16 05:21:09 +0000989 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
990 false, Headers);
991 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false,
992 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 }
994
Chris Lattner822da612007-12-17 06:36:45 +0000995 AddPath("/usr/local/include", System, false, false, false, Headers);
Ted Kremenek1d3cce32008-05-22 15:26:22 +0000996
997 AddPath("/usr/lib/gcc/i686-apple-darwin10/4.2.1/include", System,
998 false, false, false, Headers);
999 AddPath("/usr/lib/gcc/powerpc-apple-darwin10/4.2.1/include",
1000 System, false, false, false, Headers);
1001
Reid Spencer5f016e22007-07-11 17:01:13 +00001002 // leopard
1003 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +00001004 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001005 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +00001006 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001007 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
1008 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +00001009 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001010
1011 // tiger
1012 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +00001013 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001014 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +00001015 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001016 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
1017 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +00001018 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001019
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +00001020 // Ubuntu 7.10 - Gutsy Gibbon
1021 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001022 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +00001023
Chris Lattner04421082008-04-08 04:40:51 +00001024 // Fedora 8
1025 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
1026 false, false, false, Headers);
1027
Andrew Lenharth92d56b72008-03-24 21:25:48 +00001028 //Debian testing/lenny x86
1029 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
1030 false, false, false, Headers);
Andrew Lenharthf24964c2008-03-24 21:39:05 +00001031
1032 //Debian testing/lenny amd64
1033 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
1034 false, false, false, Headers);
Andrew Lenharth92d56b72008-03-24 21:25:48 +00001035
Chris Lattner822da612007-12-17 06:36:45 +00001036 AddPath("/usr/include", System, false, false, false, Headers);
1037 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
1038 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001039 }
1040
1041 // Now that we have collected all of the include paths, merge them all
1042 // together and tell the preprocessor about them.
1043
1044 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
1045 std::vector<DirectoryLookup> SearchList;
1046 SearchList = IncludeGroup[Angled];
1047 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
1048 IncludeGroup[System].end());
1049 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
1050 IncludeGroup[After].end());
1051 RemoveDuplicates(SearchList);
1052 RemoveDuplicates(IncludeGroup[Quoted]);
1053
1054 // Prepend QUOTED list on the search list.
1055 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
1056 IncludeGroup[Quoted].end());
1057
1058
1059 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
1060 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
1061 DontSearchCurDir);
1062
1063 // If verbose, print the list of directories that will be searched.
1064 if (Verbose) {
1065 fprintf(stderr, "#include \"...\" search starts here:\n");
1066 unsigned QuotedIdx = IncludeGroup[Quoted].size();
1067 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
1068 if (i == QuotedIdx)
1069 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +00001070 const char *Name = SearchList[i].getName();
1071 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +00001072 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +00001073 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +00001074 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +00001075 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +00001076 else {
1077 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +00001078 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +00001079 }
Chris Lattner3af66a92007-12-17 17:57:27 +00001080 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +00001081 }
Chris Lattner80e17152007-12-15 23:11:06 +00001082 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 }
1084}
1085
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001086//===----------------------------------------------------------------------===//
1087// Driver PreprocessorFactory - For lazily generating preprocessors ...
1088//===----------------------------------------------------------------------===//
1089
1090namespace {
1091class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001092 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001093 Diagnostic &Diags;
1094 const LangOptions &LangInfo;
1095 TargetInfo &Target;
1096 SourceManager &SourceMgr;
1097 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001098 bool InitializeSourceMgr;
1099
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001100public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001101 DriverPreprocessorFactory(const std::string &infile,
1102 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001103 TargetInfo &target, SourceManager &SM,
1104 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001105 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1106 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1107
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001108
1109 virtual ~DriverPreprocessorFactory() {}
1110
1111 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001112 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1113 SourceMgr, HeaderInfo);
1114
Chris Lattner51574ea2008-04-19 23:25:44 +00001115 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001116 delete PP;
1117 return NULL;
1118 }
1119
1120 InitializeSourceMgr = false;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001121 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001122 }
1123};
1124}
Reid Spencer5f016e22007-07-11 17:01:13 +00001125
Reid Spencer5f016e22007-07-11 17:01:13 +00001126//===----------------------------------------------------------------------===//
1127// Basic Parser driver
1128//===----------------------------------------------------------------------===//
1129
Chris Lattner51574ea2008-04-19 23:25:44 +00001130static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001132 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001133
1134 // Parsing the specified input file.
1135 P.ParseTranslationUnit();
1136 delete PA;
1137}
1138
1139//===----------------------------------------------------------------------===//
1140// Main driver
1141//===----------------------------------------------------------------------===//
1142
Ted Kremenekdb094a22007-12-05 18:27:04 +00001143/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1144/// action. These consumers can operate on both ASTs that are freshly
1145/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001146static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001147 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001148 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001149 Preprocessor *PP,
Ted Kremenek339b9c22008-04-17 22:31:54 +00001150 PreprocessorFactory *PPF,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001151 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001152 switch (ProgAction) {
1153 default:
1154 return NULL;
1155
1156 case ASTPrint:
1157 return CreateASTPrinter();
1158
1159 case ASTDump:
1160 return CreateASTDumper();
1161
1162 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001163 return CreateASTViewer();
1164
1165 case EmitHTML:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001166 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001167
1168 case ParseCFGDump:
1169 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001170 return CreateCFGDumper(ProgAction == ParseCFGView,
1171 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001172
1173 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001174 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001175
1176 case WarnDeadStores:
1177 return CreateDeadStoreChecker(Diag);
1178
1179 case WarnUninitVals:
1180 return CreateUnitValsChecker(Diag);
1181
Ted Kremeneke01c9872008-02-14 22:36:46 +00001182 case AnalysisGRSimpleVals:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001183 return CreateGRSimpleVals(Diag, PP, PPF, AnalyzeSpecificFunction,
1184 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001185
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001186 case CheckerCFRef:
Ted Kremeneke5c30122008-04-29 05:13:59 +00001187 return CreateCFRefChecker(Diag, PP, PPF, LangOpts,
1188 AnalyzeSpecificFunction,
Ted Kremenek339b9c22008-04-17 22:31:54 +00001189 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001190
Ted Kremenekdb094a22007-12-05 18:27:04 +00001191 case TestSerialization:
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001192 return CreateSerializationTest(Diag, FileMgr);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001193
1194 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001195 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001196 DestModule = new llvm::Module(InFile);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +00001197 return CreateLLVMCodeGen(Diag, LangOpts, DestModule, GenerateDebugInfo);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001198
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001199 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001200 // FIXME: Allow user to tailor where the file is written.
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001201 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001202
Steve Naroffb29b4272008-04-14 22:03:09 +00001203 case RewriteObjC:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001204 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001205 }
1206}
1207
Reid Spencer5f016e22007-07-11 17:01:13 +00001208/// ProcessInputFile - Process a single input file with the specified state.
1209///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001210static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1211 const std::string &InFile) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001212
1213 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001214 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001215 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001216
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 switch (ProgAction) {
1218 default:
Chris Lattner3245a0a2008-04-16 06:11:58 +00001219 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
1220 PP.getFileManager(), PP.getLangOptions(), &PP,
Ted Kremenek339b9c22008-04-17 22:31:54 +00001221 &PPF, CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001222
1223 if (!Consumer) {
1224 fprintf(stderr, "Unexpected program action!\n");
1225 return;
1226 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001227
Ted Kremenekdb094a22007-12-05 18:27:04 +00001228 break;
1229
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001231 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001232 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001233 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 do {
1235 PP.Lex(Tok);
1236 PP.DumpToken(Tok, true);
1237 fprintf(stderr, "\n");
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 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001243 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001245 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 do {
1247 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001248 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001249 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 break;
1251 }
1252
1253 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001254 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001255 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001257
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001259 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001260 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 break;
1262
1263 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001264 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001265 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001267
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001268 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001269 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001270 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001271
1272 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001273 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001274 ClearSourceMgr = true;
1275 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001276 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001277
1278 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001279 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001280 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001281
1282 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001283 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001285
1286 // If running the code generator, finish up now.
1287 if (CodeGenModule) {
1288 std::ostream *Out;
1289 if (OutputFile == "-") {
1290 Out = llvm::cout.stream();
1291 } else if (!OutputFile.empty()) {
1292 Out = new std::ofstream(OutputFile.c_str(),
1293 std::ios_base::binary|std::ios_base::out);
1294 } else if (InFile == "-") {
1295 Out = llvm::cout.stream();
1296 } else {
1297 llvm::sys::Path Path(InFile);
1298 Path.eraseSuffix();
1299 if (ProgAction == EmitLLVM)
1300 Path.appendSuffix("ll");
1301 else if (ProgAction == EmitBC)
1302 Path.appendSuffix("bc");
1303 else
1304 assert(0 && "Unknown action");
1305 Out = new std::ofstream(Path.toString().c_str(),
1306 std::ios_base::binary|std::ios_base::out);
1307 }
1308
1309 if (ProgAction == EmitLLVM) {
1310 CodeGenModule->print(*Out);
1311 } else {
1312 assert(ProgAction == EmitBC);
1313 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1314 }
1315
1316 if (Out != llvm::cout.stream())
1317 delete Out;
1318 delete CodeGenModule;
1319 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001320
1321 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001322 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 PP.PrintStats();
1324 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001325 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001326 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001327 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 fprintf(stderr, "\n");
1329 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001330
1331 // For a multi-file compilation, some things are ok with nuking the source
1332 // manager tables, other require stable fileid/macroid's across multiple
1333 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001334 if (ClearSourceMgr)
1335 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001336}
1337
Ted Kremenek20e97482007-12-12 23:41:08 +00001338static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1339 FileManager& FileMgr) {
1340
1341 if (VerifyDiagnostics) {
1342 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1343 exit (1);
1344 }
1345
1346 llvm::sys::Path Filename(InFile);
1347
1348 if (!Filename.isValid()) {
1349 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1350 exit (1);
1351 }
1352
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001353 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001354
1355 if (!TU) {
1356 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1357 InFile.c_str());
1358 exit (1);
1359 }
1360
Ted Kremenek63ea8632007-12-19 19:27:38 +00001361 // Observe that we use the source file name stored in the deserialized
1362 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001363 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001364 llvm::OwningPtr<ASTConsumer>
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001365 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
1366 0, 0, DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001367
1368 if (!Consumer) {
1369 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1370 exit (1);
1371 }
1372
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001373 Consumer->Initialize(TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001374
Chris Lattnere66b65c2008-02-06 01:42:25 +00001375 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001376 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1377 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001378}
1379
1380
Reid Spencer5f016e22007-07-11 17:01:13 +00001381static llvm::cl::list<std::string>
1382InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1383
Ted Kremenek20e97482007-12-12 23:41:08 +00001384static bool isSerializedFile(const std::string& InFile) {
1385 if (InFile.size() < 4)
1386 return false;
1387
1388 const char* s = InFile.c_str()+InFile.size()-4;
1389
1390 return s[0] == '.' &&
1391 s[1] == 'a' &&
1392 s[2] == 's' &&
1393 s[3] == 't';
1394}
1395
Reid Spencer5f016e22007-07-11 17:01:13 +00001396
1397int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001398 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 llvm::sys::PrintStackTraceOnErrorSignal();
1400
1401 // If no input was specified, read from stdin.
1402 if (InputFilenames.empty())
1403 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001404
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 // Create a file manager object to provide access to and cache the filesystem.
1406 FileManager FileMgr;
1407
Ted Kremenek31e703b2007-12-11 23:28:38 +00001408 // Create the diagnostic client for reporting errors or for
1409 // implementing -verify.
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001410 std::auto_ptr<DiagnosticClient> DiagClient;
1411 TextDiagnostics* TextDiagClient = NULL;
1412
1413 if (!HTMLDiag.empty()) {
Ted Kremeneka760f5f2008-04-16 16:53:18 +00001414
1415 // FIXME: The HTMLDiagnosticClient uses the Preprocessor for
1416 // (optional) syntax highlighting, but we don't have a preprocessor yet.
1417 // Fix this dependency later.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001418 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, 0, 0));
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001419 }
1420 else { // Use Text diagnostics.
1421 if (!VerifyDiagnostics) {
1422 // Print diagnostics to stderr by default.
1423 TextDiagClient = new TextDiagnosticPrinter();
1424 } else {
1425 // When checking diagnostics, just buffer them up.
1426 TextDiagClient = new TextDiagnosticBuffer();
1427
1428 if (InputFilenames.size() != 1) {
1429 fprintf(stderr,
1430 "-verify only works on single input files for now.\n");
1431 return 1;
1432 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 }
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001434
1435 assert (TextDiagClient);
1436 DiagClient.reset(TextDiagClient);
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 }
1438
1439 // Configure our handling of diagnostics.
1440 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001441 InitializeDiagnostics(Diags);
1442
Chris Lattner4f037832007-12-05 23:24:17 +00001443 // -I- is a deprecated GCC feature, scan for it and reject it.
1444 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1445 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001446 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001447 I_dirs.erase(I_dirs.begin()+i);
1448 --i;
1449 }
1450 }
Chris Lattner11215192008-03-14 06:12:05 +00001451
1452 // Get information about the target being compiled for.
1453 std::string Triple = CreateTargetTriple();
1454 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1455 if (Target == 0) {
1456 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1457 Triple.c_str());
1458 fprintf(stderr, "Please use -triple or -arch.\n");
1459 exit(1);
1460 }
Chris Lattner4f037832007-12-05 23:24:17 +00001461
Reid Spencer5f016e22007-07-11 17:01:13 +00001462 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001463 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001464
Ted Kremenek20e97482007-12-12 23:41:08 +00001465 if (isSerializedFile(InFile))
1466 ProcessSerializedFile(InFile,Diags,FileMgr);
1467 else {
1468 /// Create a SourceManager object. This tracks and owns all the file
1469 /// buffers allocated to a translation unit.
1470 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001471
Ted Kremenek20e97482007-12-12 23:41:08 +00001472 // Initialize language options, inferring file types from input filenames.
1473 LangOptions LangInfo;
1474 InitializeBaseLanguage();
1475 LangKind LK = GetLanguage(InFile);
1476 InitializeLangOptions(LangInfo, LK);
1477 InitializeLanguageStandard(LangInfo, LK);
Ted Kremenek01d9dbf2008-04-29 04:37:03 +00001478 InitializeGCMode(LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001479
1480 // Process the -I options and set them in the HeaderInfo.
1481 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001482 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Ted Kremenekc68ecb52008-06-06 01:47:30 +00001483
1484 // FIXME: Sink IncludeGroup into this loop.
1485 IncludeGroup[0].clear();
1486 IncludeGroup[1].clear();
1487 IncludeGroup[2].clear();
1488 IncludeGroup[3].clear();
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001489 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001490
Ted Kremenek20e97482007-12-12 23:41:08 +00001491 // Set up the preprocessor with these options.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001492 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001493 SourceMgr, HeaderInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001494
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001495 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1496
Ted Kremenek339b9c22008-04-17 22:31:54 +00001497 if (!PP)
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001498 continue;
1499
Ted Kremenek339b9c22008-04-17 22:31:54 +00001500 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek20e97482007-12-12 23:41:08 +00001501 HeaderInfo.ClearFileInfo();
1502
1503 if (Stats)
1504 SourceMgr.PrintStats();
1505 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 }
1507
Chris Lattner11215192008-03-14 06:12:05 +00001508 delete Target;
1509
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1511
1512 if (NumDiagnostics)
1513 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1514 (NumDiagnostics == 1 ? "" : "s"));
1515
1516 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 FileMgr.PrintStats();
1518 fprintf(stderr, "\n");
1519 }
1520
Chris Lattner96f1a642007-07-21 05:40:53 +00001521 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001522}