blob: 0816f52fa46708899e2348d75efa8b5f42496bbf [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 Kremenek221bb8d2007-10-16 23:37:27 +000077 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000078 ParsePrintCallbacks, // Parse and print each callback.
79 ParseSyntaxOnly, // Parse and perform semantic analysis.
80 ParseNoop, // Parse with noop callbacks.
81 RunPreprocessorOnly, // Just lex, no output.
82 PrintPreprocessedInput, // -E mode.
Ted Kremenek81ea7992008-07-02 00:03:09 +000083 DumpTokens, // Token dump mode.
84 RunAnalysis // Run one or more source code analyses.
Chris Lattner4b009652007-07-25 00:24:17 +000085};
86
87static llvm::cl::opt<ProgActions>
88ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
89 llvm::cl::init(ParseSyntaxOnly),
90 llvm::cl::values(
91 clEnumValN(RunPreprocessorOnly, "Eonly",
92 "Just run preprocessor, no output (for timings)"),
93 clEnumValN(PrintPreprocessedInput, "E",
94 "Run preprocessor, emit preprocessed file"),
95 clEnumValN(DumpTokens, "dumptokens",
96 "Run preprocessor, dump internal rep of tokens"),
97 clEnumValN(ParseNoop, "parse-noop",
98 "Run parser with noop callbacks (for timings)"),
99 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
100 "Run parser and perform semantic analysis"),
101 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
102 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000103 clEnumValN(EmitHTML, "emit-html",
104 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000105 clEnumValN(ASTPrint, "ast-print",
106 "Build ASTs and then pretty-print them"),
107 clEnumValN(ASTDump, "ast-dump",
108 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000109 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000110 "Build ASTs and view them with GraphViz"),
Ted Kremenek97f75312007-08-21 21:42:03 +0000111 clEnumValN(ParseCFGDump, "dump-cfg",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000112 "Run parser, then build and print CFGs"),
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000113 clEnumValN(ParseCFGView, "view-cfg",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000114 "Run parser, then build and view CFGs with Graphviz"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000115 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000116 "Run prototype serialization code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000117 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000118 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000119 clEnumValN(EmitBC, "emit-llvm-bc",
120 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000121 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000122 "Build ASTs and emit .ast file"),
Steve Naroff44e81222008-04-14 22:03:09 +0000123 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000124 "Rewrite ObjC into C (code rewriter example)"),
125 clEnumValN(RewriteMacros, "rewrite-macros",
126 "Expand macros without full preprocessing"),
Chris Lattner4b009652007-07-25 00:24:17 +0000127 clEnumValEnd));
128
Ted Kremenekd01eae62007-12-19 19:47:59 +0000129
130static llvm::cl::opt<std::string>
131OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000132 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000133 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000134
135//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000136// Code Generator Options
137//===----------------------------------------------------------------------===//
138static llvm::cl::opt<bool>
139GenerateDebugInfo("g",
140 llvm::cl::desc("Generate source level debug information"));
141
142//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000143// Diagnostic Options
144//===----------------------------------------------------------------------===//
145
Ted Kremenek10389cf2007-09-26 19:42:19 +0000146static llvm::cl::opt<bool>
147VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000148 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000149
Ted Kremenekfd75e312008-03-27 06:17:42 +0000150static llvm::cl::opt<std::string>
151HTMLDiag("html-diags",
152 llvm::cl::desc("Generate HTML to report diagnostics"),
153 llvm::cl::value_desc("HTML directory"));
154
Chris Lattner4b009652007-07-25 00:24:17 +0000155//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000156// Analyzer Options
157//===----------------------------------------------------------------------===//
158
159static llvm::cl::opt<bool>
160VisualizeEG("visualize-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000161 llvm::cl::desc("Display static analysis Exploded Graph"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000162
163static llvm::cl::opt<bool>
164AnalyzeAll("checker-opt-analyze-headers",
165 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000166 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000167
Ted Kremenek81ea7992008-07-02 00:03:09 +0000168static llvm::cl::list<Analyses>
169AnalysisList(llvm::cl::desc("Available Source Code Analyses:"),
170llvm::cl::values(
Ted Kremenekd899b0f2008-07-02 18:11:29 +0000171clEnumValN(DisplayLiveVariables, "dump-live-variables",
172 "Print results of live variable analysis"),
Ted Kremenek81ea7992008-07-02 00:03:09 +0000173clEnumValN(WarnDeadStores, "warn-dead-stores",
174 "Flag warnings of stores to dead variables"),
175clEnumValN(WarnUninitVals, "warn-uninit-values",
176 "Flag warnings of uses of unitialized variables"),
Ted Kremenekc8a5fd42008-07-02 16:35:50 +0000177clEnumValN(CheckerSimple, "checker-simple",
178 "Perform simple path-sensitive checks."),
Ted Kremenek1c6cd212008-07-02 00:44:58 +0000179clEnumValN(CheckerCFRef, "checker-cfref",
Ted Kremenekc8a5fd42008-07-02 16:35:50 +0000180 "Run the [Core] Foundation reference count checker"),
Ted Kremenek81ea7992008-07-02 00:03:09 +0000181clEnumValEnd));
182
Ted Kremenek517cb512008-04-14 18:40:58 +0000183//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000184// Language Options
185//===----------------------------------------------------------------------===//
186
187enum LangKind {
188 langkind_unspecified,
189 langkind_c,
190 langkind_c_cpp,
191 langkind_cxx,
192 langkind_cxx_cpp,
193 langkind_objc,
194 langkind_objc_cpp,
195 langkind_objcxx,
196 langkind_objcxx_cpp
197};
198
199/* TODO: GCC also accepts:
200 c-header c++-header objective-c-header objective-c++-header
201 assembler assembler-with-cpp
202 ada, f77*, ratfor (!), f95, java, treelang
203 */
204static llvm::cl::opt<LangKind>
205BaseLang("x", llvm::cl::desc("Base language to compile"),
206 llvm::cl::init(langkind_unspecified),
207 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
208 clEnumValN(langkind_cxx, "c++", "C++"),
209 clEnumValN(langkind_objc, "objective-c", "Objective C"),
210 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
211 clEnumValN(langkind_c_cpp, "c-cpp-output",
212 "Preprocessed C"),
213 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
214 "Preprocessed C++"),
215 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
216 "Preprocessed Objective C"),
217 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
218 "Preprocessed Objective C++"),
219 clEnumValEnd));
220
221static llvm::cl::opt<bool>
222LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
223 llvm::cl::Hidden);
224static llvm::cl::opt<bool>
225LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
226 llvm::cl::Hidden);
227
Ted Kremenek11ad8952007-12-05 23:49:08 +0000228/// InitializeBaseLanguage - Handle the -x foo options.
229static void InitializeBaseLanguage() {
230 if (LangObjC)
231 BaseLang = langkind_objc;
232 else if (LangObjCXX)
233 BaseLang = langkind_objcxx;
234}
235
236static LangKind GetLanguage(const std::string &Filename) {
237 if (BaseLang != langkind_unspecified)
238 return BaseLang;
239
240 std::string::size_type DotPos = Filename.rfind('.');
241
242 if (DotPos == std::string::npos) {
243 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000244 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000245 }
246
Ted Kremenek11ad8952007-12-05 23:49:08 +0000247 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
248 // C header: .h
249 // C++ header: .hh or .H;
250 // assembler no preprocessing: .s
251 // assembler: .S
252 if (Ext == "c")
253 return langkind_c;
254 else if (Ext == "i")
255 return langkind_c_cpp;
256 else if (Ext == "ii")
257 return langkind_cxx_cpp;
258 else if (Ext == "m")
259 return langkind_objc;
260 else if (Ext == "mi")
261 return langkind_objc_cpp;
262 else if (Ext == "mm" || Ext == "M")
263 return langkind_objcxx;
264 else if (Ext == "mii")
265 return langkind_objcxx_cpp;
266 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
267 Ext == "c++" || Ext == "cp" || Ext == "cxx")
268 return langkind_cxx;
269 else
270 return langkind_c;
271}
272
273
274static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000275 // FIXME: implement -fpreprocessed mode.
276 bool NoPreprocess = false;
277
Ted Kremenek11ad8952007-12-05 23:49:08 +0000278 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000279 default: assert(0 && "Unknown language kind!");
280 case langkind_c_cpp:
281 NoPreprocess = true;
282 // FALLTHROUGH
283 case langkind_c:
284 break;
285 case langkind_cxx_cpp:
286 NoPreprocess = true;
287 // FALLTHROUGH
288 case langkind_cxx:
289 Options.CPlusPlus = 1;
290 break;
291 case langkind_objc_cpp:
292 NoPreprocess = true;
293 // FALLTHROUGH
294 case langkind_objc:
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000295 Options.ObjC1 = Options.ObjC2 = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000296 break;
297 case langkind_objcxx_cpp:
298 NoPreprocess = true;
299 // FALLTHROUGH
300 case langkind_objcxx:
301 Options.ObjC1 = Options.ObjC2 = 1;
302 Options.CPlusPlus = 1;
303 break;
304 }
305}
306
307/// LangStds - Language standards we support.
308enum LangStds {
309 lang_unspecified,
310 lang_c89, lang_c94, lang_c99,
311 lang_gnu89, lang_gnu99,
312 lang_cxx98, lang_gnucxx98,
313 lang_cxx0x, lang_gnucxx0x
314};
315
316static llvm::cl::opt<LangStds>
317LangStd("std", llvm::cl::desc("Language standard to compile for"),
318 llvm::cl::init(lang_unspecified),
319 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
320 clEnumValN(lang_c89, "c90", "ISO C 1990"),
321 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
322 clEnumValN(lang_c94, "iso9899:199409",
323 "ISO C 1990 with amendment 1"),
324 clEnumValN(lang_c99, "c99", "ISO C 1999"),
325// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
326 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
327// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
328 clEnumValN(lang_gnu89, "gnu89",
329 "ISO C 1990 with GNU extensions (default for C)"),
330 clEnumValN(lang_gnu99, "gnu99",
331 "ISO C 1999 with GNU extensions"),
332 clEnumValN(lang_gnu99, "gnu9x",
333 "ISO C 1999 with GNU extensions"),
334 clEnumValN(lang_cxx98, "c++98",
335 "ISO C++ 1998 with amendments"),
336 clEnumValN(lang_gnucxx98, "gnu++98",
337 "ISO C++ 1998 with amendments and GNU "
338 "extensions (default for C++)"),
339 clEnumValN(lang_cxx0x, "c++0x",
340 "Upcoming ISO C++ 200x with amendments"),
341 clEnumValN(lang_gnucxx0x, "gnu++0x",
342 "Upcoming ISO C++ 200x with amendments and GNU "
343 "extensions (default for C++)"),
344 clEnumValEnd));
345
346static llvm::cl::opt<bool>
347NoOperatorNames("fno-operator-names",
348 llvm::cl::desc("Do not treat C++ operator name keywords as "
349 "synonyms for operators"));
350
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000351static llvm::cl::opt<bool>
352PascalStrings("fpascal-strings",
353 llvm::cl::desc("Recognize and construct Pascal-style "
354 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000355
356static llvm::cl::opt<bool>
357MSExtensions("fms-extensions",
358 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000359 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000360
361static llvm::cl::opt<bool>
362WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000363 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000364
365static llvm::cl::opt<bool>
366LaxVectorConversions("flax-vector-conversions",
367 llvm::cl::desc("Allow implicit conversions between vectors"
368 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000369 "different element types"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000370
Chris Lattner4b009652007-07-25 00:24:17 +0000371// FIXME: add:
372// -ansi
373// -trigraphs
374// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000375// -fpascal-strings
Ted Kremenek11ad8952007-12-05 23:49:08 +0000376static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000377 if (LangStd == lang_unspecified) {
378 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000379 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000380 default: assert(0 && "Unknown base language");
381 case langkind_c:
382 case langkind_c_cpp:
383 case langkind_objc:
384 case langkind_objc_cpp:
385 LangStd = lang_gnu99;
386 break;
387 case langkind_cxx:
388 case langkind_cxx_cpp:
389 case langkind_objcxx:
390 case langkind_objcxx_cpp:
391 LangStd = lang_gnucxx98;
392 break;
393 }
394 }
395
396 switch (LangStd) {
397 default: assert(0 && "Unknown language standard!");
398
399 // Fall through from newer standards to older ones. This isn't really right.
400 // FIXME: Enable specifically the right features based on the language stds.
401 case lang_gnucxx0x:
402 case lang_cxx0x:
403 Options.CPlusPlus0x = 1;
404 // FALL THROUGH
405 case lang_gnucxx98:
406 case lang_cxx98:
407 Options.CPlusPlus = 1;
408 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000409 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000410 // FALL THROUGH.
411 case lang_gnu99:
412 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000413 Options.C99 = 1;
414 Options.HexFloats = 1;
415 // FALL THROUGH.
416 case lang_gnu89:
417 Options.BCPLComment = 1; // Only for C99/C++.
418 // FALL THROUGH.
419 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000420 Options.Digraphs = 1; // C94, C99, C++.
421 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000422 case lang_c89:
423 break;
424 }
425
Chris Lattner6ab935b2008-04-05 06:32:51 +0000426 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
427 Options.ImplicitInt = 1;
428 else
429 Options.ImplicitInt = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000430 Options.Trigraphs = 1; // -trigraphs or -ansi
431 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000432 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000433 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000434 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000435 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000436}
437
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000438static llvm::cl::opt<bool>
439ObjCExclusiveGC("fobjc-gc-only",
440 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000441 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000442
443static llvm::cl::opt<bool>
444ObjCEnableGC("fobjc-gc",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000445 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000446
447void InitializeGCMode(LangOptions &Options) {
448 if (ObjCExclusiveGC)
449 Options.setGCMode(LangOptions::GCOnly);
450 else if (ObjCEnableGC)
451 Options.setGCMode(LangOptions::HybridGC);
452}
453
454
Chris Lattner4b009652007-07-25 00:24:17 +0000455//===----------------------------------------------------------------------===//
456// Our DiagnosticClient implementation
457//===----------------------------------------------------------------------===//
458
459// FIXME: Werror should take a list of things, -Werror=foo,bar
460static llvm::cl::opt<bool>
461WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
462
463static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000464SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
465
466static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000467WarnOnExtensions("pedantic", llvm::cl::init(false),
468 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
469
470static llvm::cl::opt<bool>
471ErrorOnExtensions("pedantic-errors",
472 llvm::cl::desc("Issue an error on uses of GCC extensions"));
473
474static llvm::cl::opt<bool>
475WarnUnusedMacros("Wunused_macros",
476 llvm::cl::desc("Warn for unused macros in the main translation unit"));
477
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000478static llvm::cl::opt<bool>
479WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000480 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000481
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000482static llvm::cl::opt<bool>
483WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000484 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000485
Chris Lattnera616ee32008-01-23 17:19:46 +0000486static llvm::cl::opt<bool>
487WarnUndefMacros("Wundef",
488 llvm::cl::desc("Warn on use of undefined macros in #if's"));
489
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000490static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000491WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
492 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000493
Chris Lattner4b009652007-07-25 00:24:17 +0000494/// InitializeDiagnostics - Initialize the diagnostic object, based on the
495/// current command line option settings.
496static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000497 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000498 Diags.setWarningsAsErrors(WarningsAsErrors);
499 Diags.setWarnOnExtensions(WarnOnExtensions);
500 Diags.setErrorOnExtensions(ErrorOnExtensions);
501
502 // Silence the "macro is not used" warning unless requested.
503 if (!WarnUnusedMacros)
504 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000505
506 // Silence "floating point comparison" warnings unless requested.
507 if (!WarnFloatEqual)
508 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000509
510 // Silence "format string is not a string literal" warnings if requested
511 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000512 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
513 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000514 if (!WarnUndefMacros)
515 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000516
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000517 if (!WarnImplicitFunctionDeclaration)
518 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
519 diag::MAP_IGNORE);
520
Steve Naroff606f7072008-02-11 22:40:08 +0000521 if (MSExtensions) // MS allows unnamed struct/union fields.
522 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner057a2f52008-05-04 23:52:02 +0000523
524 // If -pedantic-errors is set, turn extensions that warn by default into
525 // errors.
526 if (ErrorOnExtensions) {
527 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
528 diag::MAP_ERROR);
529 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
530 diag::MAP_ERROR);
531 }
Chris Lattner4b009652007-07-25 00:24:17 +0000532}
533
534//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000535// Analysis-specific options.
536//===----------------------------------------------------------------------===//
537
538static llvm::cl::opt<std::string>
539AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000540 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000541
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000542static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000543TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000544 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000545
Ted Kremenek0118bb52008-02-18 21:21:23 +0000546//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000547// Target Triple Processing.
548//===----------------------------------------------------------------------===//
549
550static llvm::cl::opt<std::string>
551TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000552 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000553
Chris Lattnerfc457002008-03-05 01:18:20 +0000554static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000555Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000556
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000557static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000558 // Initialize base triple. If a -triple option has been specified, use
559 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000560 std::string Triple = TargetTriple;
561 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000562
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000563 // If -arch foo was specified, remove the architecture from the triple we have
564 // so far and replace it with the specified one.
565 if (Arch.empty())
566 return Triple;
567
Ted Kremenek40499482007-12-03 22:06:55 +0000568 // Decompose the base triple into "arch" and suffix.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000569 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000570
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000571 if (FirstDashIdx == std::string::npos) {
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000572 fprintf(stderr,
573 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner210c0cc2007-12-12 05:01:48 +0000574 Triple.c_str());
575 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000576 }
Ted Kremenek40499482007-12-03 22:06:55 +0000577
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000578 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenek40499482007-12-03 22:06:55 +0000579}
580
581//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000582// Preprocessor Initialization
583//===----------------------------------------------------------------------===//
584
585// FIXME: Preprocessor builtins to support.
586// -A... - Play with #assertions
587// -undef - Undefine all predefined macros
588
589static llvm::cl::list<std::string>
590D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
591 llvm::cl::desc("Predefine the specified macro"));
592static llvm::cl::list<std::string>
593U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
594 llvm::cl::desc("Undefine the specified macro"));
595
Chris Lattner008da782008-01-10 01:53:41 +0000596static llvm::cl::list<std::string>
597ImplicitIncludes("include", llvm::cl::value_desc("file"),
598 llvm::cl::desc("Include file before parsing"));
599
600
Chris Lattner4b009652007-07-25 00:24:17 +0000601// Append a #define line to Buf for Macro. Macro should be of the form XXX,
602// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
603// "#define XXX Y z W". To get a #define with no value, use "XXX=".
604static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
605 const char *Command = "#define ") {
606 Buf.insert(Buf.end(), Command, Command+strlen(Command));
607 if (const char *Equal = strchr(Macro, '=')) {
608 // Turn the = into ' '.
609 Buf.insert(Buf.end(), Macro, Equal);
610 Buf.push_back(' ');
611 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
612 } else {
613 // Push "macroname 1".
614 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
615 Buf.push_back(' ');
616 Buf.push_back('1');
617 }
618 Buf.push_back('\n');
619}
620
Chris Lattner008da782008-01-10 01:53:41 +0000621/// AddImplicitInclude - Add an implicit #include of the specified file to the
622/// predefines buffer.
623static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
624 const char *Inc = "#include \"";
625 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
626 Buf.insert(Buf.end(), File.begin(), File.end());
627 Buf.push_back('"');
628 Buf.push_back('\n');
629}
630
Chris Lattner4b009652007-07-25 00:24:17 +0000631
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000632/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000633/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000634///
Chris Lattner9d818a22008-04-19 23:25:44 +0000635static bool InitializePreprocessor(Preprocessor &PP,
636 bool InitializeSourceMgr,
637 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000638 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000639
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000640 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000641 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000642
643 if (InitializeSourceMgr) {
644 if (InFile != "-") {
645 const FileEntry *File = FileMgr.getFile(InFile);
646 if (File) SourceMgr.createMainFileID(File, SourceLocation());
647 if (SourceMgr.getMainFileID() == 0) {
648 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000649 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000650 }
651 } else {
652 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
653 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
654 if (SourceMgr.getMainFileID() == 0) {
655 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000656 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000657 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000658 }
Chris Lattner4b009652007-07-25 00:24:17 +0000659 }
Sam Bishop61a20782008-04-14 14:41:57 +0000660
Chris Lattner47b6a162008-04-19 23:09:31 +0000661 std::vector<char> PredefineBuffer;
662
Chris Lattner4b009652007-07-25 00:24:17 +0000663 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000664 unsigned d = 0, D = D_macros.size();
665 unsigned u = 0, U = U_macros.size();
666 while (d < D || u < U) {
667 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
668 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
669 else
670 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
671 }
672
Chris Lattner008da782008-01-10 01:53:41 +0000673 // FIXME: Read any files specified by -imacros.
674
675 // Add implicit #includes from -include.
676 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
677 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000678
Chris Lattner47b6a162008-04-19 23:09:31 +0000679 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000680 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000681 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000682
683 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000684 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000685}
686
687//===----------------------------------------------------------------------===//
688// Preprocessor include path information.
689//===----------------------------------------------------------------------===//
690
691// This tool exports a large number of command line options to control how the
692// preprocessor searches for header files. At root, however, the Preprocessor
693// object takes a very simple interface: a list of directories to search for
694//
695// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000696// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000697//
Chris Lattner008da782008-01-10 01:53:41 +0000698// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000699
700static llvm::cl::opt<bool>
701nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
702
703// Various command line options. These four add directories to each chain.
704static llvm::cl::list<std::string>
705F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
706 llvm::cl::desc("Add directory to framework include search path"));
707static llvm::cl::list<std::string>
708I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
709 llvm::cl::desc("Add directory to include search path"));
710static llvm::cl::list<std::string>
711idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
712 llvm::cl::desc("Add directory to AFTER include search path"));
713static llvm::cl::list<std::string>
714iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
715 llvm::cl::desc("Add directory to QUOTE include search path"));
716static llvm::cl::list<std::string>
717isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
718 llvm::cl::desc("Add directory to SYSTEM include search path"));
719
720// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
721static llvm::cl::list<std::string>
722iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
723 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
724static llvm::cl::list<std::string>
725iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
726 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
727static llvm::cl::list<std::string>
728iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
729 llvm::cl::Prefix,
730 llvm::cl::desc("Set directory to include search path with prefix"));
731
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000732static llvm::cl::opt<std::string>
733isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
734 llvm::cl::desc("Set the system root directory (usually /)"));
735
Chris Lattner4b009652007-07-25 00:24:17 +0000736// Finally, implement the code that groks the options above.
737enum IncludeDirGroup {
738 Quoted = 0,
739 Angled,
740 System,
741 After
742};
743
744static std::vector<DirectoryLookup> IncludeGroup[4];
745
746/// AddPath - Add the specified path to the specified group list.
747///
748static void AddPath(const std::string &Path, IncludeDirGroup Group,
749 bool isCXXAware, bool isUserSupplied,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000750 bool isFramework, HeaderSearch &HS) {
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000751 assert(!Path.empty() && "can't handle empty path here");
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000752 FileManager &FM = HS.getFileMgr();
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000753
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000754 // Compute the actual path, taking into consideration -isysroot.
755 llvm::SmallString<256> MappedPath;
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000756
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000757 // Handle isysroot.
758 if (Group == System) {
Chris Lattner2a2702a2007-12-17 06:51:34 +0000759 // FIXME: Portability. This should be a sys::Path interface, this doesn't
760 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000761 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
762 MappedPath.append(isysroot.begin(), isysroot.end());
Chris Lattner4b009652007-07-25 00:24:17 +0000763 }
764
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000765 MappedPath.append(Path.begin(), Path.end());
766
767 // Compute the DirectoryLookup type.
Chris Lattner4b009652007-07-25 00:24:17 +0000768 DirectoryLookup::DirType Type;
769 if (Group == Quoted || Group == Angled)
770 Type = DirectoryLookup::NormalHeaderDir;
771 else if (isCXXAware)
772 Type = DirectoryLookup::SystemHeaderDir;
773 else
774 Type = DirectoryLookup::ExternCSystemHeaderDir;
775
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000776
777 // If the directory exists, add it.
778 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
779 &MappedPath[0]+
780 MappedPath.size())) {
781 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
782 isFramework));
783 return;
784 }
785
Chris Lattnerb7426782007-12-17 07:52:39 +0000786 // Check to see if this is an apple-style headermap (which are not allowed to
787 // be frameworks).
788 if (!isFramework) {
789 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
790 &MappedPath[0]+MappedPath.size())) {
Chris Lattner9af36d32007-12-17 18:34:53 +0000791 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
792 // It is a headermap, add it to the search path.
Chris Lattnerb7426782007-12-17 07:52:39 +0000793 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
794 return;
795 }
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000796 }
797 }
798
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000799 if (Verbose)
800 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000801}
802
803/// RemoveDuplicates - If there are duplicate directory entries in the specified
804/// search list, remove the later (dead) ones.
805static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattnerac139d22007-12-15 23:20:07 +0000806 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerb7426782007-12-17 07:52:39 +0000807 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnercf33e932007-12-17 06:44:29 +0000808 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Chris Lattner4b009652007-07-25 00:24:17 +0000809 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnercf33e932007-12-17 06:44:29 +0000810 if (SearchList[i].isNormalDir()) {
811 // If this isn't the first time we've seen this dir, remove it.
812 if (SeenDirs.insert(SearchList[i].getDir()))
813 continue;
814
Chris Lattner4b009652007-07-25 00:24:17 +0000815 if (Verbose)
816 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
817 SearchList[i].getDir()->getName());
Chris Lattnerb7426782007-12-17 07:52:39 +0000818 } else if (SearchList[i].isFramework()) {
819 // If this isn't the first time we've seen this framework dir, remove it.
820 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
821 continue;
822
823 if (Verbose)
824 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
825 SearchList[i].getFrameworkDir()->getName());
826
Chris Lattnercf33e932007-12-17 06:44:29 +0000827 } else {
828 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
829 // If this isn't the first time we've seen this headermap, remove it.
830 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
831 continue;
832
833 if (Verbose)
834 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
835 SearchList[i].getDir()->getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000836 }
Chris Lattnercf33e932007-12-17 06:44:29 +0000837
838 // This is reached if the current entry is a duplicate.
839 SearchList.erase(SearchList.begin()+i);
840 --i;
Chris Lattner4b009652007-07-25 00:24:17 +0000841 }
842}
843
Chris Lattner4f022a72008-03-01 08:07:28 +0000844// AddEnvVarPaths - Add a list of paths from an environment variable to a
845// header search list.
846//
847static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
848 const char* at = getenv(Name);
849 if (!at)
850 return;
851
852 const char* delim = strchr(at, llvm::sys::PathSeparator);
853 while (delim != 0) {
854 if (delim-at == 0)
855 AddPath(".", Angled, false, true, false, Headers);
856 else
857 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
858 true, false, Headers);
859 at = delim + 1;
860 delim = strchr(at, llvm::sys::PathSeparator);
861 }
862 if (*at == 0)
863 AddPath(".", Angled, false, true, false, Headers);
864 else
865 AddPath(at, Angled, false, true, false, Headers);
866}
867
Chris Lattner4b009652007-07-25 00:24:17 +0000868/// InitializeIncludePaths - Process the -I options and set them in the
869/// HeaderSearch object.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000870static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
871 FileManager &FM, const LangOptions &Lang) {
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000872 // Handle -I... and -F... options, walking the lists in parallel.
873 unsigned Iidx = 0, Fidx = 0;
874 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
875 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
876 AddPath(I_dirs[Iidx], Angled, false, true, false, Headers);
877 ++Iidx;
878 } else {
879 AddPath(F_dirs[Fidx], Angled, false, true, true, Headers);
880 ++Fidx;
881 }
882 }
Chris Lattner4b009652007-07-25 00:24:17 +0000883
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000884 // Consume what's left from whatever list was longer.
885 for (; Iidx != I_dirs.size(); ++Iidx)
886 AddPath(I_dirs[Iidx], Angled, false, true, false, Headers);
887 for (; Fidx != F_dirs.size(); ++Fidx)
888 AddPath(F_dirs[Fidx], Angled, false, true, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000889
890 // Handle -idirafter... options.
891 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000892 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000893
894 // Handle -iquote... options.
895 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000896 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000897
898 // Handle -isystem... options.
899 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000900 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000901
902 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
903 // parallel, processing the values in order of occurance to get the right
904 // prefixes.
905 {
906 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
907 unsigned iprefix_idx = 0;
908 unsigned iwithprefix_idx = 0;
909 unsigned iwithprefixbefore_idx = 0;
910 bool iprefix_done = iprefix_vals.empty();
911 bool iwithprefix_done = iwithprefix_vals.empty();
912 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
913 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
914 if (!iprefix_done &&
915 (iwithprefix_done ||
916 iprefix_vals.getPosition(iprefix_idx) <
917 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
918 (iwithprefixbefore_done ||
919 iprefix_vals.getPosition(iprefix_idx) <
920 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
921 Prefix = iprefix_vals[iprefix_idx];
922 ++iprefix_idx;
923 iprefix_done = iprefix_idx == iprefix_vals.size();
924 } else if (!iwithprefix_done &&
925 (iwithprefixbefore_done ||
926 iwithprefix_vals.getPosition(iwithprefix_idx) <
927 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
928 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000929 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000930 ++iwithprefix_idx;
931 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
932 } else {
933 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000934 Angled, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000935 ++iwithprefixbefore_idx;
936 iwithprefixbefore_done =
937 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
938 }
939 }
940 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000941
942 AddEnvVarPaths("CPATH", Headers);
943 if (Lang.CPlusPlus && Lang.ObjC1)
944 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
945 else if (Lang.CPlusPlus)
946 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
947 else if (Lang.ObjC1)
948 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
949 else
950 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
951
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000952 // Add the clang headers, which are relative to the clang driver.
953 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000954 llvm::sys::Path::GetMainExecutable(Argv0,
955 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000956 if (!MainExecutablePath.isEmpty()) {
957 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
958 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
959 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
960 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
961 }
962
Chris Lattner4b009652007-07-25 00:24:17 +0000963 // FIXME: temporary hack: hard-coded paths.
964 // FIXME: get these from the target?
965 if (!nostdinc) {
966 if (Lang.CPlusPlus) {
Ted Kremenek6032d722008-05-22 15:26:22 +0000967 AddPath("/usr/include/c++/4.2.1", System, true, false, false, Headers);
968 AddPath("/usr/include/c++/4.2.1/i686-apple-darwin10", System, true, false,
969 false, Headers);
970 AddPath("/usr/include/c++/4.2.1/backward", System, true, false, false,
971 Headers);
972
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000973 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000974 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000975 false, Headers);
976 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
977 Headers);
Lauro Ramos Venanciof6a66272008-02-15 22:36:38 +0000978
979 // Ubuntu 7.10 - Gutsy Gibbon
980 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
981 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
982 false, Headers);
983 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
984 Headers);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000985
986 // Fedora 8
987 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
Chris Lattner5fdcc302008-04-16 05:21:09 +0000988 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
989 false, Headers);
990 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false,
991 Headers);
Ted Kremenek0cb803a2008-06-24 03:33:47 +0000992
993 // Arch Linux 2008-06-24
994 AddPath("/usr/include/c++/4.3.1", System, true, false, false, Headers);
995 AddPath("/usr/include/c++/4.3.1/i686-pc-linux-gnu", System, true, false,
996 false, Headers);
997 AddPath("/usr/include/c++/4.3.1/backward", System, true, false, false,
998 Headers);
999 AddPath("/usr/include/c++/4.3.1/x86_64-unknown-linux-gnu", System, true,
1000 false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001001 }
1002
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001003 AddPath("/usr/local/include", System, false, false, false, Headers);
Ted Kremenek6032d722008-05-22 15:26:22 +00001004
1005 AddPath("/usr/lib/gcc/i686-apple-darwin10/4.2.1/include", System,
1006 false, false, false, Headers);
1007 AddPath("/usr/lib/gcc/powerpc-apple-darwin10/4.2.1/include",
1008 System, false, false, false, Headers);
1009
Chris Lattner4b009652007-07-25 00:24:17 +00001010 // leopard
1011 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001012 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001013 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001014 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001015 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
1016 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001017 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001018
1019 // tiger
1020 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001021 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001022 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001023 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001024 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
1025 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001026 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001027
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +00001028 // Ubuntu 7.10 - Gutsy Gibbon
1029 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattner43b885f2008-02-25 21:04:36 +00001030 false, false, false, Headers);
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +00001031
Chris Lattner3e254fb2008-04-08 04:40:51 +00001032 // Fedora 8
1033 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
1034 false, false, false, Headers);
1035
Andrew Lenharth6961ec42008-03-24 21:25:48 +00001036 //Debian testing/lenny x86
1037 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
1038 false, false, false, Headers);
Andrew Lenharthfccd7be2008-03-24 21:39:05 +00001039
1040 //Debian testing/lenny amd64
1041 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
1042 false, false, false, Headers);
Andrew Lenharth6961ec42008-03-24 21:25:48 +00001043
Ted Kremenek0cb803a2008-06-24 03:33:47 +00001044 // Arch Linux 2008-06-24
1045 AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.3.1/include", System,
1046 false, false, false, Headers);
1047 AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.3.1/include-fixed", System,
1048 false, false, false, Headers);
1049 AddPath("/usr/lib/gcc/x86_64-unknown-linux-gnu/4.3.1/include", System,
1050 false, false, false, Headers);
1051 AddPath("/usr/lib/gcc/x86_64-unknown-linux-gnu/4.3.1/include-fixed",
1052 System, false, false, false, Headers);
1053
Matthijs Kooijman25349e42008-06-26 08:39:30 +00001054 // Debian testing/lenny ppc32
1055 AddPath("/usr/lib/gcc/powerpc-linux-gnu/4.2.3/include", System,
1056 false, false, false, Headers);
1057
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001058 AddPath("/usr/include", System, false, false, false, Headers);
1059 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
1060 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001061 }
1062
1063 // Now that we have collected all of the include paths, merge them all
1064 // together and tell the preprocessor about them.
1065
1066 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
1067 std::vector<DirectoryLookup> SearchList;
1068 SearchList = IncludeGroup[Angled];
1069 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
1070 IncludeGroup[System].end());
1071 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
1072 IncludeGroup[After].end());
1073 RemoveDuplicates(SearchList);
1074 RemoveDuplicates(IncludeGroup[Quoted]);
1075
1076 // Prepend QUOTED list on the search list.
1077 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
1078 IncludeGroup[Quoted].end());
1079
1080
1081 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
1082 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
1083 DontSearchCurDir);
1084
1085 // If verbose, print the list of directories that will be searched.
1086 if (Verbose) {
1087 fprintf(stderr, "#include \"...\" search starts here:\n");
1088 unsigned QuotedIdx = IncludeGroup[Quoted].size();
1089 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
1090 if (i == QuotedIdx)
1091 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner1df68f92007-12-17 17:57:27 +00001092 const char *Name = SearchList[i].getName();
1093 const char *Suffix;
Chris Lattner0f64f652007-12-17 17:42:26 +00001094 if (SearchList[i].isNormalDir())
Chris Lattner1df68f92007-12-17 17:57:27 +00001095 Suffix = "";
Chris Lattner0f64f652007-12-17 17:42:26 +00001096 else if (SearchList[i].isFramework())
Chris Lattner1df68f92007-12-17 17:57:27 +00001097 Suffix = " (framework directory)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001098 else {
1099 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner1df68f92007-12-17 17:57:27 +00001100 Suffix = " (headermap)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001101 }
Chris Lattner1df68f92007-12-17 17:57:27 +00001102 fprintf(stderr, " %s%s\n", Name, Suffix);
Chris Lattner4b009652007-07-25 00:24:17 +00001103 }
Chris Lattnerac553842007-12-15 23:11:06 +00001104 fprintf(stderr, "End of search list.\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001105 }
1106}
1107
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001108//===----------------------------------------------------------------------===//
1109// Driver PreprocessorFactory - For lazily generating preprocessors ...
1110//===----------------------------------------------------------------------===//
1111
1112namespace {
1113class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001114 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001115 Diagnostic &Diags;
1116 const LangOptions &LangInfo;
1117 TargetInfo &Target;
1118 SourceManager &SourceMgr;
1119 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001120 bool InitializeSourceMgr;
1121
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001122public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001123 DriverPreprocessorFactory(const std::string &infile,
1124 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001125 TargetInfo &target, SourceManager &SM,
1126 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001127 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1128 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1129
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001130
1131 virtual ~DriverPreprocessorFactory() {}
1132
1133 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001134 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1135 SourceMgr, HeaderInfo);
1136
Chris Lattner9d818a22008-04-19 23:25:44 +00001137 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001138 delete PP;
1139 return NULL;
1140 }
1141
1142 InitializeSourceMgr = false;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001143 return PP;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001144 }
1145};
1146}
Chris Lattner4b009652007-07-25 00:24:17 +00001147
Chris Lattner4b009652007-07-25 00:24:17 +00001148//===----------------------------------------------------------------------===//
1149// Basic Parser driver
1150//===----------------------------------------------------------------------===//
1151
Chris Lattner9d818a22008-04-19 23:25:44 +00001152static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001153 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001154 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001155
1156 // Parsing the specified input file.
1157 P.ParseTranslationUnit();
1158 delete PA;
Argiris Kirtzidis8d833762008-06-13 12:15:34 +00001159
1160 if (VerifyDiagnostics)
1161 exit(CheckDiagnostics(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001162}
1163
1164//===----------------------------------------------------------------------===//
1165// Main driver
1166//===----------------------------------------------------------------------===//
1167
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001168/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1169/// action. These consumers can operate on both ASTs that are freshly
1170/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001171static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001172 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001173 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001174 Preprocessor *PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001175 PreprocessorFactory *PPF,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001176 llvm::Module *&DestModule) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001177 switch (ProgAction) {
1178 default:
1179 return NULL;
1180
1181 case ASTPrint:
1182 return CreateASTPrinter();
1183
1184 case ASTDump:
1185 return CreateASTDumper();
1186
1187 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001188 return CreateASTViewer();
1189
1190 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001191 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001192
1193 case ParseCFGDump:
1194 case ParseCFGView:
Ted Kremenek83390ec2008-02-22 20:00:31 +00001195 return CreateCFGDumper(ProgAction == ParseCFGView,
1196 AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001197
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001198 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001199 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001200
1201 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001202 case EmitBC:
Chris Lattner8d72ee02008-02-06 01:42:25 +00001203 DestModule = new llvm::Module(InFile);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +00001204 return CreateLLVMCodeGen(Diag, LangOpts, DestModule, GenerateDebugInfo);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001205
Ted Kremenekbde30332007-12-19 17:25:59 +00001206 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001207 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001208 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001209
Steve Naroff44e81222008-04-14 22:03:09 +00001210 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001211 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001212
1213 case RunAnalysis:
1214 assert (!AnalysisList.empty());
1215 return CreateAnalysisConsumer(&AnalysisList[0],
1216 &AnalysisList[0]+AnalysisList.size(),
1217 Diag, PP, PPF, LangOpts,
1218 AnalyzeSpecificFunction,
1219 OutputFile, VisualizeEG, TrimGraph,
1220 AnalyzeAll);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001221 }
1222}
1223
Chris Lattner4b009652007-07-25 00:24:17 +00001224/// ProcessInputFile - Process a single input file with the specified state.
1225///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001226static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1227 const std::string &InFile) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001228
1229 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +00001230 bool ClearSourceMgr = false;
Chris Lattner8d72ee02008-02-06 01:42:25 +00001231 llvm::Module *CodeGenModule = 0;
Ted Kremenek6856c632007-09-26 18:39:29 +00001232
Chris Lattner4b009652007-07-25 00:24:17 +00001233 switch (ProgAction) {
1234 default:
Chris Lattner21f72d62008-04-16 06:11:58 +00001235 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
1236 PP.getFileManager(), PP.getLangOptions(), &PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001237 &PPF, CodeGenModule);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001238
1239 if (!Consumer) {
1240 fprintf(stderr, "Unexpected program action!\n");
1241 return;
1242 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001243
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001244 break;
1245
Chris Lattner4b009652007-07-25 00:24:17 +00001246 case DumpTokens: { // Token dump mode.
1247 Token Tok;
1248 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001249 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001250 do {
1251 PP.Lex(Tok);
1252 PP.DumpToken(Tok, true);
1253 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001254 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001255 ClearSourceMgr = true;
1256 break;
1257 }
1258 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1259 Token Tok;
1260 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001261 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001262 do {
1263 PP.Lex(Tok);
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
1269 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001270 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001271 ClearSourceMgr = true;
1272 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001273
Chris Lattner4b009652007-07-25 00:24:17 +00001274 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001275 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001276 ClearSourceMgr = true;
1277 break;
1278
1279 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001280 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001281 ClearSourceMgr = true;
1282 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001283
Ted Kremenek6856c632007-09-26 18:39:29 +00001284 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +00001285 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001286 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001287
1288 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001289 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001290 ClearSourceMgr = true;
1291 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001292 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001293
1294 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001295 if (VerifyDiagnostics)
Ted Kremenek17861c52007-12-19 22:51:13 +00001296 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001297
1298 // This deletes Consumer.
Ted Kremenek17861c52007-12-19 22:51:13 +00001299 ParseAST(PP, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001300 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001301
1302 // If running the code generator, finish up now.
1303 if (CodeGenModule) {
1304 std::ostream *Out;
1305 if (OutputFile == "-") {
1306 Out = llvm::cout.stream();
1307 } else if (!OutputFile.empty()) {
1308 Out = new std::ofstream(OutputFile.c_str(),
1309 std::ios_base::binary|std::ios_base::out);
1310 } else if (InFile == "-") {
1311 Out = llvm::cout.stream();
1312 } else {
1313 llvm::sys::Path Path(InFile);
1314 Path.eraseSuffix();
1315 if (ProgAction == EmitLLVM)
1316 Path.appendSuffix("ll");
1317 else if (ProgAction == EmitBC)
1318 Path.appendSuffix("bc");
1319 else
1320 assert(0 && "Unknown action");
1321 Out = new std::ofstream(Path.toString().c_str(),
1322 std::ios_base::binary|std::ios_base::out);
1323 }
1324
1325 if (ProgAction == EmitLLVM) {
1326 CodeGenModule->print(*Out);
1327 } else {
1328 assert(ProgAction == EmitBC);
1329 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1330 }
1331
1332 if (Out != llvm::cout.stream())
1333 delete Out;
1334 delete CodeGenModule;
1335 }
Chris Lattner4b009652007-07-25 00:24:17 +00001336
1337 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001338 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001339 PP.PrintStats();
1340 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001341 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001342 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001343 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001344 fprintf(stderr, "\n");
1345 }
1346
1347 // For a multi-file compilation, some things are ok with nuking the source
1348 // manager tables, other require stable fileid/macroid's across multiple
1349 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001350 if (ClearSourceMgr)
1351 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001352}
1353
Ted Kremenek80d53372007-12-12 23:41:08 +00001354static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1355 FileManager& FileMgr) {
1356
1357 if (VerifyDiagnostics) {
1358 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1359 exit (1);
1360 }
1361
1362 llvm::sys::Path Filename(InFile);
1363
1364 if (!Filename.isValid()) {
1365 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1366 exit (1);
1367 }
1368
Ted Kremenek863b01f2008-04-23 16:25:39 +00001369 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001370
1371 if (!TU) {
1372 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1373 InFile.c_str());
1374 exit (1);
1375 }
1376
Ted Kremenekab749372007-12-19 19:27:38 +00001377 // Observe that we use the source file name stored in the deserialized
1378 // translation unit, rather than InFile.
Chris Lattner8d72ee02008-02-06 01:42:25 +00001379 llvm::Module *DestModule;
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001380 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001381 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
1382 0, 0, DestModule));
Ted Kremenek80d53372007-12-12 23:41:08 +00001383
1384 if (!Consumer) {
1385 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1386 exit (1);
1387 }
1388
Ted Kremenek863b01f2008-04-23 16:25:39 +00001389 Consumer->Initialize(TU->getContext());
Ted Kremenek80d53372007-12-12 23:41:08 +00001390
Chris Lattner8d72ee02008-02-06 01:42:25 +00001391 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001392 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1393 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001394}
1395
1396
Chris Lattner4b009652007-07-25 00:24:17 +00001397static llvm::cl::list<std::string>
1398InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1399
Ted Kremenek80d53372007-12-12 23:41:08 +00001400static bool isSerializedFile(const std::string& InFile) {
1401 if (InFile.size() < 4)
1402 return false;
1403
1404 const char* s = InFile.c_str()+InFile.size()-4;
1405
1406 return s[0] == '.' &&
1407 s[1] == 'a' &&
1408 s[2] == 's' &&
1409 s[3] == 't';
1410}
1411
Chris Lattner4b009652007-07-25 00:24:17 +00001412
1413int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001414 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001415 llvm::sys::PrintStackTraceOnErrorSignal();
1416
1417 // If no input was specified, read from stdin.
1418 if (InputFilenames.empty())
1419 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001420
Chris Lattner4b009652007-07-25 00:24:17 +00001421 // Create a file manager object to provide access to and cache the filesystem.
1422 FileManager FileMgr;
1423
Ted Kremenekb240e822007-12-11 23:28:38 +00001424 // Create the diagnostic client for reporting errors or for
1425 // implementing -verify.
Ted Kremenekfd75e312008-03-27 06:17:42 +00001426 std::auto_ptr<DiagnosticClient> DiagClient;
1427 TextDiagnostics* TextDiagClient = NULL;
1428
1429 if (!HTMLDiag.empty()) {
Ted Kremenek675ac6f2008-04-16 16:53:18 +00001430
1431 // FIXME: The HTMLDiagnosticClient uses the Preprocessor for
1432 // (optional) syntax highlighting, but we don't have a preprocessor yet.
1433 // Fix this dependency later.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001434 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, 0, 0));
Ted Kremenekfd75e312008-03-27 06:17:42 +00001435 }
1436 else { // Use Text diagnostics.
1437 if (!VerifyDiagnostics) {
1438 // Print diagnostics to stderr by default.
1439 TextDiagClient = new TextDiagnosticPrinter();
1440 } else {
1441 // When checking diagnostics, just buffer them up.
1442 TextDiagClient = new TextDiagnosticBuffer();
1443
1444 if (InputFilenames.size() != 1) {
1445 fprintf(stderr,
1446 "-verify only works on single input files for now.\n");
1447 return 1;
1448 }
Chris Lattner4b009652007-07-25 00:24:17 +00001449 }
Ted Kremenekfd75e312008-03-27 06:17:42 +00001450
1451 assert (TextDiagClient);
1452 DiagClient.reset(TextDiagClient);
Chris Lattner4b009652007-07-25 00:24:17 +00001453 }
1454
1455 // Configure our handling of diagnostics.
1456 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +00001457 InitializeDiagnostics(Diags);
1458
Chris Lattner45a56e02007-12-05 23:24:17 +00001459 // -I- is a deprecated GCC feature, scan for it and reject it.
1460 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1461 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001462 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001463 I_dirs.erase(I_dirs.begin()+i);
1464 --i;
1465 }
1466 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001467
1468 // Get information about the target being compiled for.
1469 std::string Triple = CreateTargetTriple();
1470 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1471 if (Target == 0) {
1472 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1473 Triple.c_str());
1474 fprintf(stderr, "Please use -triple or -arch.\n");
1475 exit(1);
1476 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001477
Ted Kremenek81ea7992008-07-02 00:03:09 +00001478 // Are we invoking one or more source analyses?
1479 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1480 ProgAction = RunAnalysis;
1481
1482
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001483 llvm::OwningPtr<SourceManager> SourceMgr;
1484
Chris Lattner4b009652007-07-25 00:24:17 +00001485 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001486 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001487
Ted Kremenek80d53372007-12-12 23:41:08 +00001488 if (isSerializedFile(InFile))
1489 ProcessSerializedFile(InFile,Diags,FileMgr);
1490 else {
1491 /// Create a SourceManager object. This tracks and owns all the file
1492 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001493 if (!SourceMgr)
1494 SourceMgr.reset(new SourceManager());
1495 else
1496 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001497
Ted Kremenek80d53372007-12-12 23:41:08 +00001498 // Initialize language options, inferring file types from input filenames.
1499 LangOptions LangInfo;
1500 InitializeBaseLanguage();
1501 LangKind LK = GetLanguage(InFile);
1502 InitializeLangOptions(LangInfo, LK);
1503 InitializeLanguageStandard(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001504 InitializeGCMode(LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001505
1506 // Process the -I options and set them in the HeaderInfo.
1507 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekfd75e312008-03-27 06:17:42 +00001508 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Ted Kremenek649465c2008-06-06 01:47:30 +00001509
1510 // FIXME: Sink IncludeGroup into this loop.
1511 IncludeGroup[0].clear();
1512 IncludeGroup[1].clear();
1513 IncludeGroup[2].clear();
1514 IncludeGroup[3].clear();
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001515 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001516
Ted Kremenek80d53372007-12-12 23:41:08 +00001517 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001518 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001519 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001520
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001521 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1522
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001523 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001524 continue;
1525
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001526 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001527 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001528
1529 if (Stats)
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001530 SourceMgr->PrintStats();
Ted Kremenek80d53372007-12-12 23:41:08 +00001531 }
Chris Lattner4b009652007-07-25 00:24:17 +00001532 }
1533
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001534
Chris Lattner2c77d852008-03-14 06:12:05 +00001535 delete Target;
1536
Chris Lattner4b009652007-07-25 00:24:17 +00001537 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1538
1539 if (NumDiagnostics)
1540 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1541 (NumDiagnostics == 1 ? "" : "s"));
1542
1543 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001544 FileMgr.PrintStats();
1545 fprintf(stderr, "\n");
1546 }
1547
1548 return Diags.getNumErrors() != 0;
1549}