blob: 344fe08bffd6a0f882beecf62d4f4b7c8215c81c [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000029#include "HTMLDiagnostics.h"
30#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenekac881932007-12-18 21:34:28 +000031#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000032#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000033#include "clang/Sema/ParseAST.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000034#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000035#include "clang/Parse/Parser.h"
36#include "clang/Lex/HeaderSearch.h"
37#include "clang/Basic/FileManager.h"
38#include "clang/Basic/SourceManager.h"
39#include "clang/Basic/TargetInfo.h"
Chris Lattner8d72ee02008-02-06 01:42:25 +000040#include "llvm/Module.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000041#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner8d72ee02008-02-06 01:42:25 +000042#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner4b009652007-07-25 00:24:17 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/MemoryBuffer.h"
45#include "llvm/System/Signals.h"
Ted Kremenek40499482007-12-03 22:06:55 +000046#include "llvm/Config/config.h"
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +000047#include "llvm/ADT/OwningPtr.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000048#include "llvm/System/Path.h"
Chris Lattner4b009652007-07-25 00:24:17 +000049#include <memory>
Chris Lattner8d72ee02008-02-06 01:42:25 +000050#include <fstream>
Ted Kremenek4e9899f2008-04-17 22:31:54 +000051#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000052using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Global options.
56//===----------------------------------------------------------------------===//
57
58static llvm::cl::opt<bool>
59Verbose("v", llvm::cl::desc("Enable verbose output"));
60static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000061Stats("print-stats",
62 llvm::cl::desc("Print performance metrics and statistics"));
Chris Lattner4b009652007-07-25 00:24:17 +000063
64enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000065 RewriteObjC, // ObjC->C Rewriter.
Chris Lattner1665a9f2008-05-08 06:52:13 +000066 RewriteMacros, // Expand macros but not #includes.
Ted Kremeneke1a79d82008-03-19 07:53:42 +000067 HTMLTest, // HTML displayer testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000068 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000069 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000070 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000071 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-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 Kremenek97f75312007-08-21 21:42:03 +000075 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000076 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremenekaa04c512007-09-06 00:17:54 +000077 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek1da5b142008-02-15 00:35:38 +000078 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
79 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000080 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000081 ParsePrintCallbacks, // Parse and print each callback.
82 ParseSyntaxOnly, // Parse and perform semantic analysis.
83 ParseNoop, // Parse with noop callbacks.
84 RunPreprocessorOnly, // Just lex, no output.
85 PrintPreprocessedInput, // -E mode.
Ted Kremenek81ea7992008-07-02 00:03:09 +000086 DumpTokens, // Token dump mode.
87 RunAnalysis // Run one or more source code analyses.
Chris Lattner4b009652007-07-25 00:24:17 +000088};
89
90static llvm::cl::opt<ProgActions>
91ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
92 llvm::cl::init(ParseSyntaxOnly),
93 llvm::cl::values(
94 clEnumValN(RunPreprocessorOnly, "Eonly",
95 "Just run preprocessor, no output (for timings)"),
96 clEnumValN(PrintPreprocessedInput, "E",
97 "Run preprocessor, emit preprocessed file"),
98 clEnumValN(DumpTokens, "dumptokens",
99 "Run preprocessor, dump internal rep of tokens"),
100 clEnumValN(ParseNoop, "parse-noop",
101 "Run parser with noop callbacks (for timings)"),
102 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
103 "Run parser and perform semantic analysis"),
104 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
105 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000106 clEnumValN(EmitHTML, "emit-html",
107 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000108 clEnumValN(ASTPrint, "ast-print",
109 "Build ASTs and then pretty-print them"),
110 clEnumValN(ASTDump, "ast-dump",
111 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000112 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000113 "Build ASTs and view them with GraphViz"),
Ted Kremenek97f75312007-08-21 21:42:03 +0000114 clEnumValN(ParseCFGDump, "dump-cfg",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000115 "Run parser, then build and print CFGs"),
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000116 clEnumValN(ParseCFGView, "view-cfg",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000117 "Run parser, then build and view CFGs with Graphviz"),
Ted Kremenekaa04c512007-09-06 00:17:54 +0000118 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000119 "Print results of live variable analysis"),
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000120 clEnumValN(AnalysisGRSimpleVals, "checker-simple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000121 "Perform path-sensitive constant propagation"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000122 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000123 "Run prototype serialization code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000124 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000125 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000126 clEnumValN(EmitBC, "emit-llvm-bc",
127 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000128 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000129 "Build ASTs and emit .ast file"),
Steve Naroff44e81222008-04-14 22:03:09 +0000130 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000131 "Rewrite ObjC into C (code rewriter example)"),
132 clEnumValN(RewriteMacros, "rewrite-macros",
133 "Expand macros without full preprocessing"),
Chris Lattner4b009652007-07-25 00:24:17 +0000134 clEnumValEnd));
135
Ted Kremenekd01eae62007-12-19 19:47:59 +0000136
137static llvm::cl::opt<std::string>
138OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000139 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000140 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000141
142//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000143// Code Generator Options
144//===----------------------------------------------------------------------===//
145static llvm::cl::opt<bool>
146GenerateDebugInfo("g",
147 llvm::cl::desc("Generate source level debug information"));
148
149//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000150// Diagnostic Options
151//===----------------------------------------------------------------------===//
152
Ted Kremenek10389cf2007-09-26 19:42:19 +0000153static llvm::cl::opt<bool>
154VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000155 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000156
Ted Kremenekfd75e312008-03-27 06:17:42 +0000157static llvm::cl::opt<std::string>
158HTMLDiag("html-diags",
159 llvm::cl::desc("Generate HTML to report diagnostics"),
160 llvm::cl::value_desc("HTML directory"));
161
Chris Lattner4b009652007-07-25 00:24:17 +0000162//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000163// Analyzer Options
164//===----------------------------------------------------------------------===//
165
166static llvm::cl::opt<bool>
167VisualizeEG("visualize-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000168 llvm::cl::desc("Display static analysis Exploded Graph"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000169
170static llvm::cl::opt<bool>
171AnalyzeAll("checker-opt-analyze-headers",
172 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000173 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000174
Ted Kremenek81ea7992008-07-02 00:03:09 +0000175static llvm::cl::list<Analyses>
176AnalysisList(llvm::cl::desc("Available Source Code Analyses:"),
177llvm::cl::values(
178clEnumValN(WarnDeadStores, "warn-dead-stores",
179 "Flag warnings of stores to dead variables"),
180clEnumValN(WarnUninitVals, "warn-uninit-values",
181 "Flag warnings of uses of unitialized variables"),
Ted Kremenek1c6cd212008-07-02 00:44:58 +0000182clEnumValN(CheckerCFRef, "checker-cfref",
183 "Run the [Core] Foundation reference count checker"),
Ted Kremenek81ea7992008-07-02 00:03:09 +0000184clEnumValEnd));
185
Ted Kremenek517cb512008-04-14 18:40:58 +0000186//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000187// Language Options
188//===----------------------------------------------------------------------===//
189
190enum LangKind {
191 langkind_unspecified,
192 langkind_c,
193 langkind_c_cpp,
194 langkind_cxx,
195 langkind_cxx_cpp,
196 langkind_objc,
197 langkind_objc_cpp,
198 langkind_objcxx,
199 langkind_objcxx_cpp
200};
201
202/* TODO: GCC also accepts:
203 c-header c++-header objective-c-header objective-c++-header
204 assembler assembler-with-cpp
205 ada, f77*, ratfor (!), f95, java, treelang
206 */
207static llvm::cl::opt<LangKind>
208BaseLang("x", llvm::cl::desc("Base language to compile"),
209 llvm::cl::init(langkind_unspecified),
210 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
211 clEnumValN(langkind_cxx, "c++", "C++"),
212 clEnumValN(langkind_objc, "objective-c", "Objective C"),
213 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
214 clEnumValN(langkind_c_cpp, "c-cpp-output",
215 "Preprocessed C"),
216 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
217 "Preprocessed C++"),
218 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
219 "Preprocessed Objective C"),
220 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
221 "Preprocessed Objective C++"),
222 clEnumValEnd));
223
224static llvm::cl::opt<bool>
225LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
226 llvm::cl::Hidden);
227static llvm::cl::opt<bool>
228LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
229 llvm::cl::Hidden);
230
Ted Kremenek11ad8952007-12-05 23:49:08 +0000231/// InitializeBaseLanguage - Handle the -x foo options.
232static void InitializeBaseLanguage() {
233 if (LangObjC)
234 BaseLang = langkind_objc;
235 else if (LangObjCXX)
236 BaseLang = langkind_objcxx;
237}
238
239static LangKind GetLanguage(const std::string &Filename) {
240 if (BaseLang != langkind_unspecified)
241 return BaseLang;
242
243 std::string::size_type DotPos = Filename.rfind('.');
244
245 if (DotPos == std::string::npos) {
246 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000247 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000248 }
249
Ted Kremenek11ad8952007-12-05 23:49:08 +0000250 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
251 // C header: .h
252 // C++ header: .hh or .H;
253 // assembler no preprocessing: .s
254 // assembler: .S
255 if (Ext == "c")
256 return langkind_c;
257 else if (Ext == "i")
258 return langkind_c_cpp;
259 else if (Ext == "ii")
260 return langkind_cxx_cpp;
261 else if (Ext == "m")
262 return langkind_objc;
263 else if (Ext == "mi")
264 return langkind_objc_cpp;
265 else if (Ext == "mm" || Ext == "M")
266 return langkind_objcxx;
267 else if (Ext == "mii")
268 return langkind_objcxx_cpp;
269 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
270 Ext == "c++" || Ext == "cp" || Ext == "cxx")
271 return langkind_cxx;
272 else
273 return langkind_c;
274}
275
276
277static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000278 // FIXME: implement -fpreprocessed mode.
279 bool NoPreprocess = false;
280
Ted Kremenek11ad8952007-12-05 23:49:08 +0000281 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000282 default: assert(0 && "Unknown language kind!");
283 case langkind_c_cpp:
284 NoPreprocess = true;
285 // FALLTHROUGH
286 case langkind_c:
287 break;
288 case langkind_cxx_cpp:
289 NoPreprocess = true;
290 // FALLTHROUGH
291 case langkind_cxx:
292 Options.CPlusPlus = 1;
293 break;
294 case langkind_objc_cpp:
295 NoPreprocess = true;
296 // FALLTHROUGH
297 case langkind_objc:
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000298 Options.ObjC1 = Options.ObjC2 = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000299 break;
300 case langkind_objcxx_cpp:
301 NoPreprocess = true;
302 // FALLTHROUGH
303 case langkind_objcxx:
304 Options.ObjC1 = Options.ObjC2 = 1;
305 Options.CPlusPlus = 1;
306 break;
307 }
308}
309
310/// LangStds - Language standards we support.
311enum LangStds {
312 lang_unspecified,
313 lang_c89, lang_c94, lang_c99,
314 lang_gnu89, lang_gnu99,
315 lang_cxx98, lang_gnucxx98,
316 lang_cxx0x, lang_gnucxx0x
317};
318
319static llvm::cl::opt<LangStds>
320LangStd("std", llvm::cl::desc("Language standard to compile for"),
321 llvm::cl::init(lang_unspecified),
322 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
323 clEnumValN(lang_c89, "c90", "ISO C 1990"),
324 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
325 clEnumValN(lang_c94, "iso9899:199409",
326 "ISO C 1990 with amendment 1"),
327 clEnumValN(lang_c99, "c99", "ISO C 1999"),
328// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
329 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
330// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
331 clEnumValN(lang_gnu89, "gnu89",
332 "ISO C 1990 with GNU extensions (default for C)"),
333 clEnumValN(lang_gnu99, "gnu99",
334 "ISO C 1999 with GNU extensions"),
335 clEnumValN(lang_gnu99, "gnu9x",
336 "ISO C 1999 with GNU extensions"),
337 clEnumValN(lang_cxx98, "c++98",
338 "ISO C++ 1998 with amendments"),
339 clEnumValN(lang_gnucxx98, "gnu++98",
340 "ISO C++ 1998 with amendments and GNU "
341 "extensions (default for C++)"),
342 clEnumValN(lang_cxx0x, "c++0x",
343 "Upcoming ISO C++ 200x with amendments"),
344 clEnumValN(lang_gnucxx0x, "gnu++0x",
345 "Upcoming ISO C++ 200x with amendments and GNU "
346 "extensions (default for C++)"),
347 clEnumValEnd));
348
349static llvm::cl::opt<bool>
350NoOperatorNames("fno-operator-names",
351 llvm::cl::desc("Do not treat C++ operator name keywords as "
352 "synonyms for operators"));
353
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000354static llvm::cl::opt<bool>
355PascalStrings("fpascal-strings",
356 llvm::cl::desc("Recognize and construct Pascal-style "
357 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000358
359static llvm::cl::opt<bool>
360MSExtensions("fms-extensions",
361 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000362 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000363
364static llvm::cl::opt<bool>
365WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000366 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000367
368static llvm::cl::opt<bool>
369LaxVectorConversions("flax-vector-conversions",
370 llvm::cl::desc("Allow implicit conversions between vectors"
371 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000372 "different element types"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000373
Chris Lattner4b009652007-07-25 00:24:17 +0000374// FIXME: add:
375// -ansi
376// -trigraphs
377// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000378// -fpascal-strings
Ted Kremenek11ad8952007-12-05 23:49:08 +0000379static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000380 if (LangStd == lang_unspecified) {
381 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000382 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000383 default: assert(0 && "Unknown base language");
384 case langkind_c:
385 case langkind_c_cpp:
386 case langkind_objc:
387 case langkind_objc_cpp:
388 LangStd = lang_gnu99;
389 break;
390 case langkind_cxx:
391 case langkind_cxx_cpp:
392 case langkind_objcxx:
393 case langkind_objcxx_cpp:
394 LangStd = lang_gnucxx98;
395 break;
396 }
397 }
398
399 switch (LangStd) {
400 default: assert(0 && "Unknown language standard!");
401
402 // Fall through from newer standards to older ones. This isn't really right.
403 // FIXME: Enable specifically the right features based on the language stds.
404 case lang_gnucxx0x:
405 case lang_cxx0x:
406 Options.CPlusPlus0x = 1;
407 // FALL THROUGH
408 case lang_gnucxx98:
409 case lang_cxx98:
410 Options.CPlusPlus = 1;
411 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000412 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000413 // FALL THROUGH.
414 case lang_gnu99:
415 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000416 Options.C99 = 1;
417 Options.HexFloats = 1;
418 // FALL THROUGH.
419 case lang_gnu89:
420 Options.BCPLComment = 1; // Only for C99/C++.
421 // FALL THROUGH.
422 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000423 Options.Digraphs = 1; // C94, C99, C++.
424 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000425 case lang_c89:
426 break;
427 }
428
Chris Lattner6ab935b2008-04-05 06:32:51 +0000429 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
430 Options.ImplicitInt = 1;
431 else
432 Options.ImplicitInt = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000433 Options.Trigraphs = 1; // -trigraphs or -ansi
434 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000435 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000436 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000437 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000438 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000439}
440
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000441static llvm::cl::opt<bool>
442ObjCExclusiveGC("fobjc-gc-only",
443 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000444 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000445
446static llvm::cl::opt<bool>
447ObjCEnableGC("fobjc-gc",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000448 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000449
450void InitializeGCMode(LangOptions &Options) {
451 if (ObjCExclusiveGC)
452 Options.setGCMode(LangOptions::GCOnly);
453 else if (ObjCEnableGC)
454 Options.setGCMode(LangOptions::HybridGC);
455}
456
457
Chris Lattner4b009652007-07-25 00:24:17 +0000458//===----------------------------------------------------------------------===//
459// Our DiagnosticClient implementation
460//===----------------------------------------------------------------------===//
461
462// FIXME: Werror should take a list of things, -Werror=foo,bar
463static llvm::cl::opt<bool>
464WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
465
466static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000467SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
468
469static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000470WarnOnExtensions("pedantic", llvm::cl::init(false),
471 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
472
473static llvm::cl::opt<bool>
474ErrorOnExtensions("pedantic-errors",
475 llvm::cl::desc("Issue an error on uses of GCC extensions"));
476
477static llvm::cl::opt<bool>
478WarnUnusedMacros("Wunused_macros",
479 llvm::cl::desc("Warn for unused macros in the main translation unit"));
480
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000481static llvm::cl::opt<bool>
482WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000483 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000484
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000485static llvm::cl::opt<bool>
486WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000487 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000488
Chris Lattnera616ee32008-01-23 17:19:46 +0000489static llvm::cl::opt<bool>
490WarnUndefMacros("Wundef",
491 llvm::cl::desc("Warn on use of undefined macros in #if's"));
492
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000493static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000494WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
495 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000496
Chris Lattner4b009652007-07-25 00:24:17 +0000497/// InitializeDiagnostics - Initialize the diagnostic object, based on the
498/// current command line option settings.
499static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000500 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000501 Diags.setWarningsAsErrors(WarningsAsErrors);
502 Diags.setWarnOnExtensions(WarnOnExtensions);
503 Diags.setErrorOnExtensions(ErrorOnExtensions);
504
505 // Silence the "macro is not used" warning unless requested.
506 if (!WarnUnusedMacros)
507 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000508
509 // Silence "floating point comparison" warnings unless requested.
510 if (!WarnFloatEqual)
511 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000512
513 // Silence "format string is not a string literal" warnings if requested
514 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000515 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
516 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000517 if (!WarnUndefMacros)
518 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000519
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000520 if (!WarnImplicitFunctionDeclaration)
521 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
522 diag::MAP_IGNORE);
523
Steve Naroff606f7072008-02-11 22:40:08 +0000524 if (MSExtensions) // MS allows unnamed struct/union fields.
525 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner057a2f52008-05-04 23:52:02 +0000526
527 // If -pedantic-errors is set, turn extensions that warn by default into
528 // errors.
529 if (ErrorOnExtensions) {
530 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
531 diag::MAP_ERROR);
532 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
533 diag::MAP_ERROR);
534 }
Chris Lattner4b009652007-07-25 00:24:17 +0000535}
536
537//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000538// Analysis-specific options.
539//===----------------------------------------------------------------------===//
540
541static llvm::cl::opt<std::string>
542AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000543 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000544
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000545static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000546TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000547 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000548
Ted Kremenek0118bb52008-02-18 21:21:23 +0000549//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000550// Target Triple Processing.
551//===----------------------------------------------------------------------===//
552
553static llvm::cl::opt<std::string>
554TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000555 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000556
Chris Lattnerfc457002008-03-05 01:18:20 +0000557static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000558Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000559
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000560static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000561 // Initialize base triple. If a -triple option has been specified, use
562 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000563 std::string Triple = TargetTriple;
564 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000565
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000566 // If -arch foo was specified, remove the architecture from the triple we have
567 // so far and replace it with the specified one.
568 if (Arch.empty())
569 return Triple;
570
Ted Kremenek40499482007-12-03 22:06:55 +0000571 // Decompose the base triple into "arch" and suffix.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000572 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000573
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000574 if (FirstDashIdx == std::string::npos) {
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000575 fprintf(stderr,
576 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner210c0cc2007-12-12 05:01:48 +0000577 Triple.c_str());
578 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000579 }
Ted Kremenek40499482007-12-03 22:06:55 +0000580
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000581 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenek40499482007-12-03 22:06:55 +0000582}
583
584//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000585// Preprocessor Initialization
586//===----------------------------------------------------------------------===//
587
588// FIXME: Preprocessor builtins to support.
589// -A... - Play with #assertions
590// -undef - Undefine all predefined macros
591
592static llvm::cl::list<std::string>
593D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
594 llvm::cl::desc("Predefine the specified macro"));
595static llvm::cl::list<std::string>
596U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
597 llvm::cl::desc("Undefine the specified macro"));
598
Chris Lattner008da782008-01-10 01:53:41 +0000599static llvm::cl::list<std::string>
600ImplicitIncludes("include", llvm::cl::value_desc("file"),
601 llvm::cl::desc("Include file before parsing"));
602
603
Chris Lattner4b009652007-07-25 00:24:17 +0000604// Append a #define line to Buf for Macro. Macro should be of the form XXX,
605// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
606// "#define XXX Y z W". To get a #define with no value, use "XXX=".
607static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
608 const char *Command = "#define ") {
609 Buf.insert(Buf.end(), Command, Command+strlen(Command));
610 if (const char *Equal = strchr(Macro, '=')) {
611 // Turn the = into ' '.
612 Buf.insert(Buf.end(), Macro, Equal);
613 Buf.push_back(' ');
614 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
615 } else {
616 // Push "macroname 1".
617 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
618 Buf.push_back(' ');
619 Buf.push_back('1');
620 }
621 Buf.push_back('\n');
622}
623
Chris Lattner008da782008-01-10 01:53:41 +0000624/// AddImplicitInclude - Add an implicit #include of the specified file to the
625/// predefines buffer.
626static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
627 const char *Inc = "#include \"";
628 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
629 Buf.insert(Buf.end(), File.begin(), File.end());
630 Buf.push_back('"');
631 Buf.push_back('\n');
632}
633
Chris Lattner4b009652007-07-25 00:24:17 +0000634
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000635/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000636/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000637///
Chris Lattner9d818a22008-04-19 23:25:44 +0000638static bool InitializePreprocessor(Preprocessor &PP,
639 bool InitializeSourceMgr,
640 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000641 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000642
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000643 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000644 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000645
646 if (InitializeSourceMgr) {
647 if (InFile != "-") {
648 const FileEntry *File = FileMgr.getFile(InFile);
649 if (File) SourceMgr.createMainFileID(File, SourceLocation());
650 if (SourceMgr.getMainFileID() == 0) {
651 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000652 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000653 }
654 } else {
655 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
656 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
657 if (SourceMgr.getMainFileID() == 0) {
658 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000659 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000660 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000661 }
Chris Lattner4b009652007-07-25 00:24:17 +0000662 }
Sam Bishop61a20782008-04-14 14:41:57 +0000663
Chris Lattner47b6a162008-04-19 23:09:31 +0000664 std::vector<char> PredefineBuffer;
665
Chris Lattner4b009652007-07-25 00:24:17 +0000666 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000667 unsigned d = 0, D = D_macros.size();
668 unsigned u = 0, U = U_macros.size();
669 while (d < D || u < U) {
670 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
671 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
672 else
673 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
674 }
675
Chris Lattner008da782008-01-10 01:53:41 +0000676 // FIXME: Read any files specified by -imacros.
677
678 // Add implicit #includes from -include.
679 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
680 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000681
Chris Lattner47b6a162008-04-19 23:09:31 +0000682 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000683 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000684 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000685
686 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000687 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000688}
689
690//===----------------------------------------------------------------------===//
691// Preprocessor include path information.
692//===----------------------------------------------------------------------===//
693
694// This tool exports a large number of command line options to control how the
695// preprocessor searches for header files. At root, however, the Preprocessor
696// object takes a very simple interface: a list of directories to search for
697//
698// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000699// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000700//
Chris Lattner008da782008-01-10 01:53:41 +0000701// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000702
703static llvm::cl::opt<bool>
704nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
705
706// Various command line options. These four add directories to each chain.
707static llvm::cl::list<std::string>
708F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
709 llvm::cl::desc("Add directory to framework include search path"));
710static llvm::cl::list<std::string>
711I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
712 llvm::cl::desc("Add directory to include search path"));
713static llvm::cl::list<std::string>
714idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
715 llvm::cl::desc("Add directory to AFTER include search path"));
716static llvm::cl::list<std::string>
717iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
718 llvm::cl::desc("Add directory to QUOTE include search path"));
719static llvm::cl::list<std::string>
720isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
721 llvm::cl::desc("Add directory to SYSTEM include search path"));
722
723// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
724static llvm::cl::list<std::string>
725iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
726 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
727static llvm::cl::list<std::string>
728iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
729 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
730static llvm::cl::list<std::string>
731iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
732 llvm::cl::Prefix,
733 llvm::cl::desc("Set directory to include search path with prefix"));
734
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000735static llvm::cl::opt<std::string>
736isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
737 llvm::cl::desc("Set the system root directory (usually /)"));
738
Chris Lattner4b009652007-07-25 00:24:17 +0000739// Finally, implement the code that groks the options above.
740enum IncludeDirGroup {
741 Quoted = 0,
742 Angled,
743 System,
744 After
745};
746
747static std::vector<DirectoryLookup> IncludeGroup[4];
748
749/// AddPath - Add the specified path to the specified group list.
750///
751static void AddPath(const std::string &Path, IncludeDirGroup Group,
752 bool isCXXAware, bool isUserSupplied,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000753 bool isFramework, HeaderSearch &HS) {
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000754 assert(!Path.empty() && "can't handle empty path here");
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000755 FileManager &FM = HS.getFileMgr();
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000756
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000757 // Compute the actual path, taking into consideration -isysroot.
758 llvm::SmallString<256> MappedPath;
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000759
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000760 // Handle isysroot.
761 if (Group == System) {
Chris Lattner2a2702a2007-12-17 06:51:34 +0000762 // FIXME: Portability. This should be a sys::Path interface, this doesn't
763 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000764 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
765 MappedPath.append(isysroot.begin(), isysroot.end());
Chris Lattner4b009652007-07-25 00:24:17 +0000766 }
767
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000768 MappedPath.append(Path.begin(), Path.end());
769
770 // Compute the DirectoryLookup type.
Chris Lattner4b009652007-07-25 00:24:17 +0000771 DirectoryLookup::DirType Type;
772 if (Group == Quoted || Group == Angled)
773 Type = DirectoryLookup::NormalHeaderDir;
774 else if (isCXXAware)
775 Type = DirectoryLookup::SystemHeaderDir;
776 else
777 Type = DirectoryLookup::ExternCSystemHeaderDir;
778
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000779
780 // If the directory exists, add it.
781 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
782 &MappedPath[0]+
783 MappedPath.size())) {
784 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
785 isFramework));
786 return;
787 }
788
Chris Lattnerb7426782007-12-17 07:52:39 +0000789 // Check to see if this is an apple-style headermap (which are not allowed to
790 // be frameworks).
791 if (!isFramework) {
792 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
793 &MappedPath[0]+MappedPath.size())) {
Chris Lattner9af36d32007-12-17 18:34:53 +0000794 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
795 // It is a headermap, add it to the search path.
Chris Lattnerb7426782007-12-17 07:52:39 +0000796 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
797 return;
798 }
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000799 }
800 }
801
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000802 if (Verbose)
803 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000804}
805
806/// RemoveDuplicates - If there are duplicate directory entries in the specified
807/// search list, remove the later (dead) ones.
808static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattnerac139d22007-12-15 23:20:07 +0000809 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerb7426782007-12-17 07:52:39 +0000810 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnercf33e932007-12-17 06:44:29 +0000811 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Chris Lattner4b009652007-07-25 00:24:17 +0000812 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnercf33e932007-12-17 06:44:29 +0000813 if (SearchList[i].isNormalDir()) {
814 // If this isn't the first time we've seen this dir, remove it.
815 if (SeenDirs.insert(SearchList[i].getDir()))
816 continue;
817
Chris Lattner4b009652007-07-25 00:24:17 +0000818 if (Verbose)
819 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
820 SearchList[i].getDir()->getName());
Chris Lattnerb7426782007-12-17 07:52:39 +0000821 } else if (SearchList[i].isFramework()) {
822 // If this isn't the first time we've seen this framework dir, remove it.
823 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
824 continue;
825
826 if (Verbose)
827 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
828 SearchList[i].getFrameworkDir()->getName());
829
Chris Lattnercf33e932007-12-17 06:44:29 +0000830 } else {
831 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
832 // If this isn't the first time we've seen this headermap, remove it.
833 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
834 continue;
835
836 if (Verbose)
837 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
838 SearchList[i].getDir()->getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000839 }
Chris Lattnercf33e932007-12-17 06:44:29 +0000840
841 // This is reached if the current entry is a duplicate.
842 SearchList.erase(SearchList.begin()+i);
843 --i;
Chris Lattner4b009652007-07-25 00:24:17 +0000844 }
845}
846
Chris Lattner4f022a72008-03-01 08:07:28 +0000847// AddEnvVarPaths - Add a list of paths from an environment variable to a
848// header search list.
849//
850static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
851 const char* at = getenv(Name);
852 if (!at)
853 return;
854
855 const char* delim = strchr(at, llvm::sys::PathSeparator);
856 while (delim != 0) {
857 if (delim-at == 0)
858 AddPath(".", Angled, false, true, false, Headers);
859 else
860 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
861 true, false, Headers);
862 at = delim + 1;
863 delim = strchr(at, llvm::sys::PathSeparator);
864 }
865 if (*at == 0)
866 AddPath(".", Angled, false, true, false, Headers);
867 else
868 AddPath(at, Angled, false, true, false, Headers);
869}
870
Chris Lattner4b009652007-07-25 00:24:17 +0000871/// InitializeIncludePaths - Process the -I options and set them in the
872/// HeaderSearch object.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000873static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
874 FileManager &FM, const LangOptions &Lang) {
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000875 // Handle -I... and -F... options, walking the lists in parallel.
876 unsigned Iidx = 0, Fidx = 0;
877 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
878 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
879 AddPath(I_dirs[Iidx], Angled, false, true, false, Headers);
880 ++Iidx;
881 } else {
882 AddPath(F_dirs[Fidx], Angled, false, true, true, Headers);
883 ++Fidx;
884 }
885 }
Chris Lattner4b009652007-07-25 00:24:17 +0000886
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000887 // Consume what's left from whatever list was longer.
888 for (; Iidx != I_dirs.size(); ++Iidx)
889 AddPath(I_dirs[Iidx], Angled, false, true, false, Headers);
890 for (; Fidx != F_dirs.size(); ++Fidx)
891 AddPath(F_dirs[Fidx], Angled, false, true, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000892
893 // Handle -idirafter... options.
894 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000895 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000896
897 // Handle -iquote... options.
898 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000899 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000900
901 // Handle -isystem... options.
902 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000903 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000904
905 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
906 // parallel, processing the values in order of occurance to get the right
907 // prefixes.
908 {
909 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
910 unsigned iprefix_idx = 0;
911 unsigned iwithprefix_idx = 0;
912 unsigned iwithprefixbefore_idx = 0;
913 bool iprefix_done = iprefix_vals.empty();
914 bool iwithprefix_done = iwithprefix_vals.empty();
915 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
916 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
917 if (!iprefix_done &&
918 (iwithprefix_done ||
919 iprefix_vals.getPosition(iprefix_idx) <
920 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
921 (iwithprefixbefore_done ||
922 iprefix_vals.getPosition(iprefix_idx) <
923 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
924 Prefix = iprefix_vals[iprefix_idx];
925 ++iprefix_idx;
926 iprefix_done = iprefix_idx == iprefix_vals.size();
927 } else if (!iwithprefix_done &&
928 (iwithprefixbefore_done ||
929 iwithprefix_vals.getPosition(iwithprefix_idx) <
930 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
931 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000932 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000933 ++iwithprefix_idx;
934 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
935 } else {
936 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000937 Angled, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000938 ++iwithprefixbefore_idx;
939 iwithprefixbefore_done =
940 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
941 }
942 }
943 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000944
945 AddEnvVarPaths("CPATH", Headers);
946 if (Lang.CPlusPlus && Lang.ObjC1)
947 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
948 else if (Lang.CPlusPlus)
949 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
950 else if (Lang.ObjC1)
951 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
952 else
953 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
954
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000955 // Add the clang headers, which are relative to the clang driver.
956 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000957 llvm::sys::Path::GetMainExecutable(Argv0,
958 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000959 if (!MainExecutablePath.isEmpty()) {
960 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
961 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
962 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
963 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
964 }
965
Chris Lattner4b009652007-07-25 00:24:17 +0000966 // FIXME: temporary hack: hard-coded paths.
967 // FIXME: get these from the target?
968 if (!nostdinc) {
969 if (Lang.CPlusPlus) {
Ted Kremenek6032d722008-05-22 15:26:22 +0000970 AddPath("/usr/include/c++/4.2.1", System, true, false, false, Headers);
971 AddPath("/usr/include/c++/4.2.1/i686-apple-darwin10", System, true, false,
972 false, Headers);
973 AddPath("/usr/include/c++/4.2.1/backward", System, true, false, false,
974 Headers);
975
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000976 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000977 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000978 false, Headers);
979 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
980 Headers);
Lauro Ramos Venanciof6a66272008-02-15 22:36:38 +0000981
982 // Ubuntu 7.10 - Gutsy Gibbon
983 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
984 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
985 false, Headers);
986 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
987 Headers);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000988
989 // Fedora 8
990 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
Chris Lattner5fdcc302008-04-16 05:21:09 +0000991 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
992 false, Headers);
993 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false,
994 Headers);
Ted Kremenek0cb803a2008-06-24 03:33:47 +0000995
996 // Arch Linux 2008-06-24
997 AddPath("/usr/include/c++/4.3.1", System, true, false, false, Headers);
998 AddPath("/usr/include/c++/4.3.1/i686-pc-linux-gnu", System, true, false,
999 false, Headers);
1000 AddPath("/usr/include/c++/4.3.1/backward", System, true, false, false,
1001 Headers);
1002 AddPath("/usr/include/c++/4.3.1/x86_64-unknown-linux-gnu", System, true,
1003 false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001004 }
1005
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001006 AddPath("/usr/local/include", System, false, false, false, Headers);
Ted Kremenek6032d722008-05-22 15:26:22 +00001007
1008 AddPath("/usr/lib/gcc/i686-apple-darwin10/4.2.1/include", System,
1009 false, false, false, Headers);
1010 AddPath("/usr/lib/gcc/powerpc-apple-darwin10/4.2.1/include",
1011 System, false, false, false, Headers);
1012
Chris Lattner4b009652007-07-25 00:24:17 +00001013 // leopard
1014 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001015 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001016 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001017 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001018 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
1019 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001020 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001021
1022 // tiger
1023 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001024 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001025 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001026 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001027 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
1028 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001029 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001030
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +00001031 // Ubuntu 7.10 - Gutsy Gibbon
1032 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattner43b885f2008-02-25 21:04:36 +00001033 false, false, false, Headers);
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +00001034
Chris Lattner3e254fb2008-04-08 04:40:51 +00001035 // Fedora 8
1036 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
1037 false, false, false, Headers);
1038
Andrew Lenharth6961ec42008-03-24 21:25:48 +00001039 //Debian testing/lenny x86
1040 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
1041 false, false, false, Headers);
Andrew Lenharthfccd7be2008-03-24 21:39:05 +00001042
1043 //Debian testing/lenny amd64
1044 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
1045 false, false, false, Headers);
Andrew Lenharth6961ec42008-03-24 21:25:48 +00001046
Ted Kremenek0cb803a2008-06-24 03:33:47 +00001047 // Arch Linux 2008-06-24
1048 AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.3.1/include", System,
1049 false, false, false, Headers);
1050 AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.3.1/include-fixed", System,
1051 false, false, false, Headers);
1052 AddPath("/usr/lib/gcc/x86_64-unknown-linux-gnu/4.3.1/include", System,
1053 false, false, false, Headers);
1054 AddPath("/usr/lib/gcc/x86_64-unknown-linux-gnu/4.3.1/include-fixed",
1055 System, false, false, false, Headers);
1056
Matthijs Kooijman25349e42008-06-26 08:39:30 +00001057 // Debian testing/lenny ppc32
1058 AddPath("/usr/lib/gcc/powerpc-linux-gnu/4.2.3/include", System,
1059 false, false, false, Headers);
1060
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001061 AddPath("/usr/include", System, false, false, false, Headers);
1062 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
1063 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001064 }
1065
1066 // Now that we have collected all of the include paths, merge them all
1067 // together and tell the preprocessor about them.
1068
1069 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
1070 std::vector<DirectoryLookup> SearchList;
1071 SearchList = IncludeGroup[Angled];
1072 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
1073 IncludeGroup[System].end());
1074 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
1075 IncludeGroup[After].end());
1076 RemoveDuplicates(SearchList);
1077 RemoveDuplicates(IncludeGroup[Quoted]);
1078
1079 // Prepend QUOTED list on the search list.
1080 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
1081 IncludeGroup[Quoted].end());
1082
1083
1084 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
1085 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
1086 DontSearchCurDir);
1087
1088 // If verbose, print the list of directories that will be searched.
1089 if (Verbose) {
1090 fprintf(stderr, "#include \"...\" search starts here:\n");
1091 unsigned QuotedIdx = IncludeGroup[Quoted].size();
1092 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
1093 if (i == QuotedIdx)
1094 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner1df68f92007-12-17 17:57:27 +00001095 const char *Name = SearchList[i].getName();
1096 const char *Suffix;
Chris Lattner0f64f652007-12-17 17:42:26 +00001097 if (SearchList[i].isNormalDir())
Chris Lattner1df68f92007-12-17 17:57:27 +00001098 Suffix = "";
Chris Lattner0f64f652007-12-17 17:42:26 +00001099 else if (SearchList[i].isFramework())
Chris Lattner1df68f92007-12-17 17:57:27 +00001100 Suffix = " (framework directory)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001101 else {
1102 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner1df68f92007-12-17 17:57:27 +00001103 Suffix = " (headermap)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001104 }
Chris Lattner1df68f92007-12-17 17:57:27 +00001105 fprintf(stderr, " %s%s\n", Name, Suffix);
Chris Lattner4b009652007-07-25 00:24:17 +00001106 }
Chris Lattnerac553842007-12-15 23:11:06 +00001107 fprintf(stderr, "End of search list.\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001108 }
1109}
1110
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001111//===----------------------------------------------------------------------===//
1112// Driver PreprocessorFactory - For lazily generating preprocessors ...
1113//===----------------------------------------------------------------------===//
1114
1115namespace {
1116class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001117 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001118 Diagnostic &Diags;
1119 const LangOptions &LangInfo;
1120 TargetInfo &Target;
1121 SourceManager &SourceMgr;
1122 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001123 bool InitializeSourceMgr;
1124
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001125public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001126 DriverPreprocessorFactory(const std::string &infile,
1127 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001128 TargetInfo &target, SourceManager &SM,
1129 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001130 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1131 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1132
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001133
1134 virtual ~DriverPreprocessorFactory() {}
1135
1136 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001137 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1138 SourceMgr, HeaderInfo);
1139
Chris Lattner9d818a22008-04-19 23:25:44 +00001140 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001141 delete PP;
1142 return NULL;
1143 }
1144
1145 InitializeSourceMgr = false;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001146 return PP;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001147 }
1148};
1149}
Chris Lattner4b009652007-07-25 00:24:17 +00001150
Chris Lattner4b009652007-07-25 00:24:17 +00001151//===----------------------------------------------------------------------===//
1152// Basic Parser driver
1153//===----------------------------------------------------------------------===//
1154
Chris Lattner9d818a22008-04-19 23:25:44 +00001155static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001156 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001157 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001158
1159 // Parsing the specified input file.
1160 P.ParseTranslationUnit();
1161 delete PA;
Argiris Kirtzidis8d833762008-06-13 12:15:34 +00001162
1163 if (VerifyDiagnostics)
1164 exit(CheckDiagnostics(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001165}
1166
1167//===----------------------------------------------------------------------===//
1168// Main driver
1169//===----------------------------------------------------------------------===//
1170
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001171/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1172/// action. These consumers can operate on both ASTs that are freshly
1173/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001174static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001175 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001176 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001177 Preprocessor *PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001178 PreprocessorFactory *PPF,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001179 llvm::Module *&DestModule) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001180 switch (ProgAction) {
1181 default:
1182 return NULL;
1183
1184 case ASTPrint:
1185 return CreateASTPrinter();
1186
1187 case ASTDump:
1188 return CreateASTDumper();
1189
1190 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001191 return CreateASTViewer();
1192
1193 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001194 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001195
1196 case ParseCFGDump:
1197 case ParseCFGView:
Ted Kremenek83390ec2008-02-22 20:00:31 +00001198 return CreateCFGDumper(ProgAction == ParseCFGView,
1199 AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001200
1201 case AnalysisLiveVariables:
Ted Kremenekb278abb2008-02-22 20:13:09 +00001202 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001203
Ted Kremenek3862eb12008-02-14 22:36:46 +00001204 case AnalysisGRSimpleVals:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001205 return CreateGRSimpleVals(Diag, PP, PPF, AnalyzeSpecificFunction,
1206 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek1da5b142008-02-15 00:35:38 +00001207
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001208 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001209 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001210
1211 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001212 case EmitBC:
Chris Lattner8d72ee02008-02-06 01:42:25 +00001213 DestModule = new llvm::Module(InFile);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +00001214 return CreateLLVMCodeGen(Diag, LangOpts, DestModule, GenerateDebugInfo);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001215
Ted Kremenekbde30332007-12-19 17:25:59 +00001216 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001217 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001218 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001219
Steve Naroff44e81222008-04-14 22:03:09 +00001220 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001221 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001222
1223 case RunAnalysis:
1224 assert (!AnalysisList.empty());
1225 return CreateAnalysisConsumer(&AnalysisList[0],
1226 &AnalysisList[0]+AnalysisList.size(),
1227 Diag, PP, PPF, LangOpts,
1228 AnalyzeSpecificFunction,
1229 OutputFile, VisualizeEG, TrimGraph,
1230 AnalyzeAll);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001231 }
1232}
1233
Chris Lattner4b009652007-07-25 00:24:17 +00001234/// ProcessInputFile - Process a single input file with the specified state.
1235///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001236static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1237 const std::string &InFile) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001238
1239 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +00001240 bool ClearSourceMgr = false;
Chris Lattner8d72ee02008-02-06 01:42:25 +00001241 llvm::Module *CodeGenModule = 0;
Ted Kremenek6856c632007-09-26 18:39:29 +00001242
Chris Lattner4b009652007-07-25 00:24:17 +00001243 switch (ProgAction) {
1244 default:
Chris Lattner21f72d62008-04-16 06:11:58 +00001245 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
1246 PP.getFileManager(), PP.getLangOptions(), &PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001247 &PPF, CodeGenModule);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001248
1249 if (!Consumer) {
1250 fprintf(stderr, "Unexpected program action!\n");
1251 return;
1252 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001253
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001254 break;
1255
Chris Lattner4b009652007-07-25 00:24:17 +00001256 case DumpTokens: { // Token dump mode.
1257 Token Tok;
1258 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001259 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001260 do {
1261 PP.Lex(Tok);
1262 PP.DumpToken(Tok, true);
1263 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001264 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001265 ClearSourceMgr = true;
1266 break;
1267 }
1268 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1269 Token Tok;
1270 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001271 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001272 do {
1273 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001274 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001275 ClearSourceMgr = true;
1276 break;
1277 }
1278
1279 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001280 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001281 ClearSourceMgr = true;
1282 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001283
Chris Lattner4b009652007-07-25 00:24:17 +00001284 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001285 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001286 ClearSourceMgr = true;
1287 break;
1288
1289 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001290 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001291 ClearSourceMgr = true;
1292 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001293
Ted Kremenek6856c632007-09-26 18:39:29 +00001294 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +00001295 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001296 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001297
1298 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001299 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001300 ClearSourceMgr = true;
1301 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001302 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001303
1304 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001305 if (VerifyDiagnostics)
Ted Kremenek17861c52007-12-19 22:51:13 +00001306 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001307
1308 // This deletes Consumer.
Ted Kremenek17861c52007-12-19 22:51:13 +00001309 ParseAST(PP, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001310 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001311
1312 // If running the code generator, finish up now.
1313 if (CodeGenModule) {
1314 std::ostream *Out;
1315 if (OutputFile == "-") {
1316 Out = llvm::cout.stream();
1317 } else if (!OutputFile.empty()) {
1318 Out = new std::ofstream(OutputFile.c_str(),
1319 std::ios_base::binary|std::ios_base::out);
1320 } else if (InFile == "-") {
1321 Out = llvm::cout.stream();
1322 } else {
1323 llvm::sys::Path Path(InFile);
1324 Path.eraseSuffix();
1325 if (ProgAction == EmitLLVM)
1326 Path.appendSuffix("ll");
1327 else if (ProgAction == EmitBC)
1328 Path.appendSuffix("bc");
1329 else
1330 assert(0 && "Unknown action");
1331 Out = new std::ofstream(Path.toString().c_str(),
1332 std::ios_base::binary|std::ios_base::out);
1333 }
1334
1335 if (ProgAction == EmitLLVM) {
1336 CodeGenModule->print(*Out);
1337 } else {
1338 assert(ProgAction == EmitBC);
1339 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1340 }
1341
1342 if (Out != llvm::cout.stream())
1343 delete Out;
1344 delete CodeGenModule;
1345 }
Chris Lattner4b009652007-07-25 00:24:17 +00001346
1347 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001348 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001349 PP.PrintStats();
1350 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001351 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001352 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001353 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001354 fprintf(stderr, "\n");
1355 }
1356
1357 // For a multi-file compilation, some things are ok with nuking the source
1358 // manager tables, other require stable fileid/macroid's across multiple
1359 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001360 if (ClearSourceMgr)
1361 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001362}
1363
Ted Kremenek80d53372007-12-12 23:41:08 +00001364static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1365 FileManager& FileMgr) {
1366
1367 if (VerifyDiagnostics) {
1368 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1369 exit (1);
1370 }
1371
1372 llvm::sys::Path Filename(InFile);
1373
1374 if (!Filename.isValid()) {
1375 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1376 exit (1);
1377 }
1378
Ted Kremenek863b01f2008-04-23 16:25:39 +00001379 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001380
1381 if (!TU) {
1382 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1383 InFile.c_str());
1384 exit (1);
1385 }
1386
Ted Kremenekab749372007-12-19 19:27:38 +00001387 // Observe that we use the source file name stored in the deserialized
1388 // translation unit, rather than InFile.
Chris Lattner8d72ee02008-02-06 01:42:25 +00001389 llvm::Module *DestModule;
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001390 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001391 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
1392 0, 0, DestModule));
Ted Kremenek80d53372007-12-12 23:41:08 +00001393
1394 if (!Consumer) {
1395 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1396 exit (1);
1397 }
1398
Ted Kremenek863b01f2008-04-23 16:25:39 +00001399 Consumer->Initialize(TU->getContext());
Ted Kremenek80d53372007-12-12 23:41:08 +00001400
Chris Lattner8d72ee02008-02-06 01:42:25 +00001401 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001402 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1403 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001404}
1405
1406
Chris Lattner4b009652007-07-25 00:24:17 +00001407static llvm::cl::list<std::string>
1408InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1409
Ted Kremenek80d53372007-12-12 23:41:08 +00001410static bool isSerializedFile(const std::string& InFile) {
1411 if (InFile.size() < 4)
1412 return false;
1413
1414 const char* s = InFile.c_str()+InFile.size()-4;
1415
1416 return s[0] == '.' &&
1417 s[1] == 'a' &&
1418 s[2] == 's' &&
1419 s[3] == 't';
1420}
1421
Chris Lattner4b009652007-07-25 00:24:17 +00001422
1423int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001424 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001425 llvm::sys::PrintStackTraceOnErrorSignal();
1426
1427 // If no input was specified, read from stdin.
1428 if (InputFilenames.empty())
1429 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001430
Chris Lattner4b009652007-07-25 00:24:17 +00001431 // Create a file manager object to provide access to and cache the filesystem.
1432 FileManager FileMgr;
1433
Ted Kremenekb240e822007-12-11 23:28:38 +00001434 // Create the diagnostic client for reporting errors or for
1435 // implementing -verify.
Ted Kremenekfd75e312008-03-27 06:17:42 +00001436 std::auto_ptr<DiagnosticClient> DiagClient;
1437 TextDiagnostics* TextDiagClient = NULL;
1438
1439 if (!HTMLDiag.empty()) {
Ted Kremenek675ac6f2008-04-16 16:53:18 +00001440
1441 // FIXME: The HTMLDiagnosticClient uses the Preprocessor for
1442 // (optional) syntax highlighting, but we don't have a preprocessor yet.
1443 // Fix this dependency later.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001444 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, 0, 0));
Ted Kremenekfd75e312008-03-27 06:17:42 +00001445 }
1446 else { // Use Text diagnostics.
1447 if (!VerifyDiagnostics) {
1448 // Print diagnostics to stderr by default.
1449 TextDiagClient = new TextDiagnosticPrinter();
1450 } else {
1451 // When checking diagnostics, just buffer them up.
1452 TextDiagClient = new TextDiagnosticBuffer();
1453
1454 if (InputFilenames.size() != 1) {
1455 fprintf(stderr,
1456 "-verify only works on single input files for now.\n");
1457 return 1;
1458 }
Chris Lattner4b009652007-07-25 00:24:17 +00001459 }
Ted Kremenekfd75e312008-03-27 06:17:42 +00001460
1461 assert (TextDiagClient);
1462 DiagClient.reset(TextDiagClient);
Chris Lattner4b009652007-07-25 00:24:17 +00001463 }
1464
1465 // Configure our handling of diagnostics.
1466 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +00001467 InitializeDiagnostics(Diags);
1468
Chris Lattner45a56e02007-12-05 23:24:17 +00001469 // -I- is a deprecated GCC feature, scan for it and reject it.
1470 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1471 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001472 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001473 I_dirs.erase(I_dirs.begin()+i);
1474 --i;
1475 }
1476 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001477
1478 // Get information about the target being compiled for.
1479 std::string Triple = CreateTargetTriple();
1480 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1481 if (Target == 0) {
1482 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1483 Triple.c_str());
1484 fprintf(stderr, "Please use -triple or -arch.\n");
1485 exit(1);
1486 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001487
Ted Kremenek81ea7992008-07-02 00:03:09 +00001488 // Are we invoking one or more source analyses?
1489 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1490 ProgAction = RunAnalysis;
1491
1492
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001493 llvm::OwningPtr<SourceManager> SourceMgr;
1494
Chris Lattner4b009652007-07-25 00:24:17 +00001495 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001496 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001497
Ted Kremenek80d53372007-12-12 23:41:08 +00001498 if (isSerializedFile(InFile))
1499 ProcessSerializedFile(InFile,Diags,FileMgr);
1500 else {
1501 /// Create a SourceManager object. This tracks and owns all the file
1502 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001503 if (!SourceMgr)
1504 SourceMgr.reset(new SourceManager());
1505 else
1506 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001507
Ted Kremenek80d53372007-12-12 23:41:08 +00001508 // Initialize language options, inferring file types from input filenames.
1509 LangOptions LangInfo;
1510 InitializeBaseLanguage();
1511 LangKind LK = GetLanguage(InFile);
1512 InitializeLangOptions(LangInfo, LK);
1513 InitializeLanguageStandard(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001514 InitializeGCMode(LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001515
1516 // Process the -I options and set them in the HeaderInfo.
1517 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekfd75e312008-03-27 06:17:42 +00001518 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Ted Kremenek649465c2008-06-06 01:47:30 +00001519
1520 // FIXME: Sink IncludeGroup into this loop.
1521 IncludeGroup[0].clear();
1522 IncludeGroup[1].clear();
1523 IncludeGroup[2].clear();
1524 IncludeGroup[3].clear();
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001525 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001526
Ted Kremenek80d53372007-12-12 23:41:08 +00001527 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001528 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001529 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001530
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001531 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1532
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001533 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001534 continue;
1535
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001536 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001537 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001538
1539 if (Stats)
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001540 SourceMgr->PrintStats();
Ted Kremenek80d53372007-12-12 23:41:08 +00001541 }
Chris Lattner4b009652007-07-25 00:24:17 +00001542 }
1543
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001544
Chris Lattner2c77d852008-03-14 06:12:05 +00001545 delete Target;
1546
Chris Lattner4b009652007-07-25 00:24:17 +00001547 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1548
1549 if (NumDiagnostics)
1550 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1551 (NumDiagnostics == 1 ? "" : "s"));
1552
1553 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001554 FileMgr.PrintStats();
1555 fprintf(stderr, "\n");
1556 }
1557
1558 return Diags.getNumErrors() != 0;
1559}