blob: 8cfdd941b8f44cffd7884664af5bdb5294e4dc73 [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"
Zhongxing Xue7079442008-08-24 02:33:36 +000027#include "clang/Driver/HTMLDiagnostics.h"
Nico Weber770e3882008-08-22 09:25:22 +000028#include "clang/Driver/InitHeaderSearch.h"
Nico Weber0e13eaa2008-08-05 23:33:20 +000029#include "clang/Driver/TextDiagnosticBuffer.h"
30#include "clang/Driver/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000031#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000032#include "clang/AST/Decl.h"
Ted Kremenekac881932007-12-18 21:34:28 +000033#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000034#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000035#include "clang/Sema/ParseAST.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000036#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000037#include "clang/Parse/Parser.h"
38#include "clang/Lex/HeaderSearch.h"
39#include "clang/Basic/FileManager.h"
40#include "clang/Basic/SourceManager.h"
41#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000042#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000043#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000044#include "llvm/ADT/StringExtras.h"
45#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000046#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000048#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000049#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000050using namespace clang;
51
52//===----------------------------------------------------------------------===//
53// Global options.
54//===----------------------------------------------------------------------===//
55
56static llvm::cl::opt<bool>
57Verbose("v", llvm::cl::desc("Enable verbose output"));
58static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000059Stats("print-stats",
60 llvm::cl::desc("Print performance metrics and statistics"));
Chris Lattner4b009652007-07-25 00:24:17 +000061
62enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000063 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000064 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000065 RewriteMacros, // Expand macros but not #includes.
Ted Kremeneke1a79d82008-03-19 07:53:42 +000066 HTMLTest, // HTML displayer testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000067 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000068 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000069 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000070 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000071 ASTPrint, // Parse ASTs and print them.
72 ASTDump, // Parse ASTs and dump them.
73 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000074 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000075 ParsePrintCallbacks, // Parse and print each callback.
76 ParseSyntaxOnly, // Parse and perform semantic analysis.
77 ParseNoop, // Parse with noop callbacks.
78 RunPreprocessorOnly, // Just lex, no output.
79 PrintPreprocessedInput, // -E mode.
Ted Kremenek81ea7992008-07-02 00:03:09 +000080 DumpTokens, // Token dump mode.
81 RunAnalysis // Run one or more source code analyses.
Chris Lattner4b009652007-07-25 00:24:17 +000082};
83
84static llvm::cl::opt<ProgActions>
85ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
86 llvm::cl::init(ParseSyntaxOnly),
87 llvm::cl::values(
88 clEnumValN(RunPreprocessorOnly, "Eonly",
89 "Just run preprocessor, no output (for timings)"),
90 clEnumValN(PrintPreprocessedInput, "E",
91 "Run preprocessor, emit preprocessed file"),
92 clEnumValN(DumpTokens, "dumptokens",
93 "Run preprocessor, dump internal rep of tokens"),
94 clEnumValN(ParseNoop, "parse-noop",
95 "Run parser with noop callbacks (for timings)"),
96 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
97 "Run parser and perform semantic analysis"),
98 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
99 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000100 clEnumValN(EmitHTML, "emit-html",
101 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000102 clEnumValN(ASTPrint, "ast-print",
103 "Build ASTs and then pretty-print them"),
104 clEnumValN(ASTDump, "ast-dump",
105 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000106 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000107 "Build ASTs and view them with GraphViz"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000108 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000109 "Run prototype serialization code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000110 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000111 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000112 clEnumValN(EmitBC, "emit-llvm-bc",
113 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000114 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000115 "Build ASTs and emit .ast file"),
Steve Naroff44e81222008-04-14 22:03:09 +0000116 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000117 "Rewrite ObjC into C (code rewriter example)"),
118 clEnumValN(RewriteMacros, "rewrite-macros",
119 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000120 clEnumValN(RewriteBlocks, "rewrite-blocks",
121 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000122 clEnumValEnd));
123
Ted Kremenekd01eae62007-12-19 19:47:59 +0000124
125static llvm::cl::opt<std::string>
126OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000127 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000128 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000129
130//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000131// Code Generator Options
132//===----------------------------------------------------------------------===//
133static llvm::cl::opt<bool>
134GenerateDebugInfo("g",
135 llvm::cl::desc("Generate source level debug information"));
136
137//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000138// Diagnostic Options
139//===----------------------------------------------------------------------===//
140
Ted Kremenek10389cf2007-09-26 19:42:19 +0000141static llvm::cl::opt<bool>
142VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000143 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000144
Ted Kremenekfd75e312008-03-27 06:17:42 +0000145static llvm::cl::opt<std::string>
146HTMLDiag("html-diags",
147 llvm::cl::desc("Generate HTML to report diagnostics"),
148 llvm::cl::value_desc("HTML directory"));
149
Nico Weber0e13eaa2008-08-05 23:33:20 +0000150static llvm::cl::opt<bool>
151NoShowColumn("fno-show-column",
152 llvm::cl::desc("Do not include column number on diagnostics"));
153
154static llvm::cl::opt<bool>
155NoCaretDiagnostics("fno-caret-diagnostics",
156 llvm::cl::desc("Do not include source line and caret with"
157 " diagnostics"));
158
159
Chris Lattner4b009652007-07-25 00:24:17 +0000160//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000161// Analyzer Options
162//===----------------------------------------------------------------------===//
163
164static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000165VisualizeEGDot("analyzer-viz-egraph-graphviz",
166 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000167
168static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000169VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
170 llvm::cl::desc("Display exploded graph using Ubigraph"));
171
172static llvm::cl::opt<bool>
173AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek517cb512008-04-14 18:40:58 +0000174 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000175 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000176
Ted Kremenek81ea7992008-07-02 00:03:09 +0000177static llvm::cl::list<Analyses>
178AnalysisList(llvm::cl::desc("Available Source Code Analyses:"),
179llvm::cl::values(
Ted Kremenekfbda0ef2008-07-15 00:46:02 +0000180#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenek8ce61b32008-07-14 23:41:13 +0000181clEnumValN(NAME, CMDFLAG, DESC),
182#include "Analyses.def"
183clEnumValEnd));
Ted Kremenek81ea7992008-07-02 00:03:09 +0000184
Ted Kremenek517cb512008-04-14 18:40:58 +0000185//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000186// Language Options
187//===----------------------------------------------------------------------===//
188
189enum LangKind {
190 langkind_unspecified,
191 langkind_c,
192 langkind_c_cpp,
193 langkind_cxx,
194 langkind_cxx_cpp,
195 langkind_objc,
196 langkind_objc_cpp,
197 langkind_objcxx,
198 langkind_objcxx_cpp
199};
200
201/* TODO: GCC also accepts:
202 c-header c++-header objective-c-header objective-c++-header
203 assembler assembler-with-cpp
204 ada, f77*, ratfor (!), f95, java, treelang
205 */
206static llvm::cl::opt<LangKind>
207BaseLang("x", llvm::cl::desc("Base language to compile"),
208 llvm::cl::init(langkind_unspecified),
209 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
210 clEnumValN(langkind_cxx, "c++", "C++"),
211 clEnumValN(langkind_objc, "objective-c", "Objective C"),
212 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
213 clEnumValN(langkind_c_cpp, "c-cpp-output",
214 "Preprocessed C"),
215 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
216 "Preprocessed C++"),
217 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
218 "Preprocessed Objective C"),
219 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
220 "Preprocessed Objective C++"),
221 clEnumValEnd));
222
223static llvm::cl::opt<bool>
224LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
225 llvm::cl::Hidden);
226static llvm::cl::opt<bool>
227LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
228 llvm::cl::Hidden);
229
Ted Kremenek11ad8952007-12-05 23:49:08 +0000230/// InitializeBaseLanguage - Handle the -x foo options.
231static void InitializeBaseLanguage() {
232 if (LangObjC)
233 BaseLang = langkind_objc;
234 else if (LangObjCXX)
235 BaseLang = langkind_objcxx;
236}
237
238static LangKind GetLanguage(const std::string &Filename) {
239 if (BaseLang != langkind_unspecified)
240 return BaseLang;
241
242 std::string::size_type DotPos = Filename.rfind('.');
243
244 if (DotPos == std::string::npos) {
245 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000246 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000247 }
248
Ted Kremenek11ad8952007-12-05 23:49:08 +0000249 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
250 // C header: .h
251 // C++ header: .hh or .H;
252 // assembler no preprocessing: .s
253 // assembler: .S
254 if (Ext == "c")
255 return langkind_c;
256 else if (Ext == "i")
257 return langkind_c_cpp;
258 else if (Ext == "ii")
259 return langkind_cxx_cpp;
260 else if (Ext == "m")
261 return langkind_objc;
262 else if (Ext == "mi")
263 return langkind_objc_cpp;
264 else if (Ext == "mm" || Ext == "M")
265 return langkind_objcxx;
266 else if (Ext == "mii")
267 return langkind_objcxx_cpp;
268 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
269 Ext == "c++" || Ext == "cp" || Ext == "cxx")
270 return langkind_cxx;
271 else
272 return langkind_c;
273}
274
275
276static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000277 // FIXME: implement -fpreprocessed mode.
278 bool NoPreprocess = false;
279
Ted Kremenek11ad8952007-12-05 23:49:08 +0000280 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000281 default: assert(0 && "Unknown language kind!");
282 case langkind_c_cpp:
283 NoPreprocess = true;
284 // FALLTHROUGH
285 case langkind_c:
286 break;
287 case langkind_cxx_cpp:
288 NoPreprocess = true;
289 // FALLTHROUGH
290 case langkind_cxx:
291 Options.CPlusPlus = 1;
292 break;
293 case langkind_objc_cpp:
294 NoPreprocess = true;
295 // FALLTHROUGH
296 case langkind_objc:
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000297 Options.ObjC1 = Options.ObjC2 = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000298 break;
299 case langkind_objcxx_cpp:
300 NoPreprocess = true;
301 // FALLTHROUGH
302 case langkind_objcxx:
303 Options.ObjC1 = Options.ObjC2 = 1;
304 Options.CPlusPlus = 1;
305 break;
306 }
307}
308
309/// LangStds - Language standards we support.
310enum LangStds {
311 lang_unspecified,
312 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000313 lang_gnu_START,
314 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000315 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
Daniel Dunbar91692d92008-08-11 17:36:14 +0000374// FIXME: This (and all GCC -f options) really come in -f... and
375// -fno-... forms, and additionally support automagic behavior when
376// they are not defined. For example, -fexceptions defaults to on or
377// off depending on the language. We should support this behavior in
378// some form (perhaps just add a facility for distinguishing when an
379// has its default value from when it has been set to its default
380// value).
381static llvm::cl::opt<bool>
382Exceptions("fexceptions",
383 llvm::cl::desc("Enable support for exception handling."));
384
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000385static llvm::cl::opt<bool>
386GNURuntime("fgnu-runtime",
387 llvm::cl::desc("Generate output compatible with the standard GNU Objective-C runtime."));
388
389static llvm::cl::opt<bool>
390NeXTRuntime("fnext-runtime",
391 llvm::cl::desc("Generate output compatible with the NeXT runtime."));
392
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000393
394
395static llvm::cl::opt<bool>
396Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
397
398static llvm::cl::opt<bool>
399Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
400
Chris Lattner4b009652007-07-25 00:24:17 +0000401// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000402// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000403// -fpascal-strings
Daniel Dunbar34542952008-08-23 08:43:39 +0000404static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
405 TargetInfo *Target) {
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000406
407 if (Ansi) // "The -ansi option is equivalent to -std=c89."
408 LangStd = lang_c89;
409
Chris Lattner4b009652007-07-25 00:24:17 +0000410 if (LangStd == lang_unspecified) {
411 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000412 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000413 default: assert(0 && "Unknown base language");
414 case langkind_c:
415 case langkind_c_cpp:
416 case langkind_objc:
417 case langkind_objc_cpp:
418 LangStd = lang_gnu99;
419 break;
420 case langkind_cxx:
421 case langkind_cxx_cpp:
422 case langkind_objcxx:
423 case langkind_objcxx_cpp:
424 LangStd = lang_gnucxx98;
425 break;
426 }
427 }
428
429 switch (LangStd) {
430 default: assert(0 && "Unknown language standard!");
431
432 // Fall through from newer standards to older ones. This isn't really right.
433 // FIXME: Enable specifically the right features based on the language stds.
434 case lang_gnucxx0x:
435 case lang_cxx0x:
436 Options.CPlusPlus0x = 1;
437 // FALL THROUGH
438 case lang_gnucxx98:
439 case lang_cxx98:
440 Options.CPlusPlus = 1;
441 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000442 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000443 // FALL THROUGH.
444 case lang_gnu99:
445 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000446 Options.C99 = 1;
447 Options.HexFloats = 1;
448 // FALL THROUGH.
449 case lang_gnu89:
450 Options.BCPLComment = 1; // Only for C99/C++.
451 // FALL THROUGH.
452 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000453 Options.Digraphs = 1; // C94, C99, C++.
454 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000455 case lang_c89:
456 break;
457 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000458
459 if (Options.CPlusPlus) {
460 Options.C99 = 0;
461 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
462 }
Chris Lattner4b009652007-07-25 00:24:17 +0000463
Chris Lattner6ab935b2008-04-05 06:32:51 +0000464 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
465 Options.ImplicitInt = 1;
466 else
467 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000468
469 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
470 // is specified, or -std is set to a conforming mode.
471 Options.Trigraphs = LangStd < lang_gnu_START || Trigraphs ? 1 : 0;
472
Chris Lattner4b009652007-07-25 00:24:17 +0000473 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000474 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000475 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000476 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000477 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000478 Options.Exceptions = Exceptions;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000479
480 if (NeXTRuntime) {
481 Options.NeXTRuntime = 1;
482 } else if (GNURuntime) {
483 Options.NeXTRuntime = 0;
484 } else {
Daniel Dunbar34542952008-08-23 08:43:39 +0000485 Options.NeXTRuntime = Target->useNeXTRuntimeAsDefault();
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000486 }
Chris Lattner4b009652007-07-25 00:24:17 +0000487}
488
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000489static llvm::cl::opt<bool>
490ObjCExclusiveGC("fobjc-gc-only",
491 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000492 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000493
494static llvm::cl::opt<bool>
495ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000496 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000497
498void InitializeGCMode(LangOptions &Options) {
499 if (ObjCExclusiveGC)
500 Options.setGCMode(LangOptions::GCOnly);
501 else if (ObjCEnableGC)
502 Options.setGCMode(LangOptions::HybridGC);
503}
504
505
Chris Lattner4b009652007-07-25 00:24:17 +0000506//===----------------------------------------------------------------------===//
507// Our DiagnosticClient implementation
508//===----------------------------------------------------------------------===//
509
510// FIXME: Werror should take a list of things, -Werror=foo,bar
511static llvm::cl::opt<bool>
512WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
513
514static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000515SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
516
517static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000518WarnOnExtensions("pedantic", llvm::cl::init(false),
519 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
520
521static llvm::cl::opt<bool>
522ErrorOnExtensions("pedantic-errors",
523 llvm::cl::desc("Issue an error on uses of GCC extensions"));
524
525static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000526SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar35e50942008-09-30 20:49:53 +0000527 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000528 llvm::cl::init(true));
529
530static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000531WarnUnusedMacros("Wunused_macros",
532 llvm::cl::desc("Warn for unused macros in the main translation unit"));
533
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000534static llvm::cl::opt<bool>
535WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000536 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000537
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000538static llvm::cl::opt<bool>
539WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000540 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000541
Chris Lattnera616ee32008-01-23 17:19:46 +0000542static llvm::cl::opt<bool>
543WarnUndefMacros("Wundef",
544 llvm::cl::desc("Warn on use of undefined macros in #if's"));
545
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000546static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000547WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
548 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000549
Chris Lattner4b009652007-07-25 00:24:17 +0000550/// InitializeDiagnostics - Initialize the diagnostic object, based on the
551/// current command line option settings.
552static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000553 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000554 Diags.setWarningsAsErrors(WarningsAsErrors);
555 Diags.setWarnOnExtensions(WarnOnExtensions);
556 Diags.setErrorOnExtensions(ErrorOnExtensions);
557
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000558 // Suppress warnings in system headers unless requested not to.
559 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
560
Chris Lattner4b009652007-07-25 00:24:17 +0000561 // Silence the "macro is not used" warning unless requested.
562 if (!WarnUnusedMacros)
563 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000564
565 // Silence "floating point comparison" warnings unless requested.
566 if (!WarnFloatEqual)
567 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000568
569 // Silence "format string is not a string literal" warnings if requested
570 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000571 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
572 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000573 if (!WarnUndefMacros)
574 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000575
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000576 if (!WarnImplicitFunctionDeclaration)
577 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
578 diag::MAP_IGNORE);
579
Steve Naroff606f7072008-02-11 22:40:08 +0000580 if (MSExtensions) // MS allows unnamed struct/union fields.
581 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner057a2f52008-05-04 23:52:02 +0000582
583 // If -pedantic-errors is set, turn extensions that warn by default into
584 // errors.
585 if (ErrorOnExtensions) {
586 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
587 diag::MAP_ERROR);
588 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
589 diag::MAP_ERROR);
590 }
Chris Lattner4b009652007-07-25 00:24:17 +0000591}
592
593//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000594// Analysis-specific options.
595//===----------------------------------------------------------------------===//
596
597static llvm::cl::opt<std::string>
598AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000599 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000600
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000601static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000602TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000603 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000604
Ted Kremenek0118bb52008-02-18 21:21:23 +0000605//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000606// Target Triple Processing.
607//===----------------------------------------------------------------------===//
608
609static llvm::cl::opt<std::string>
610TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000611 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000612
Chris Lattnerfc457002008-03-05 01:18:20 +0000613static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000614Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000615
Chris Lattner2b168e02008-09-30 01:13:12 +0000616static llvm::cl::opt<std::string>
617MacOSVersionMin("mmacosx-version-min",
618 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
619
Chris Lattner01de9c82008-09-30 20:16:56 +0000620// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
621// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
622static void HandleMacOSVersionMin(std::string &Triple) {
623 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
624 if (DarwinDashIdx == std::string::npos) {
625 fprintf(stderr,
626 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
627 exit(1);
628 }
629 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
630
631 // Validate that there is a number after the "-darwin" and nothing else.
632 bool IsValidDarwinNumber = Triple.size() != DarwinNumIdx;
633 for (unsigned i = DarwinNumIdx; i != Triple.size(); ++i)
634 if ((Triple[i] < '0' || Triple[i] > '9') && Triple[i] != '.')
635 IsValidDarwinNumber = false;
636 if (!IsValidDarwinNumber) {
637 fprintf(stderr, "invalid darwin target triple '%s' expected number\n",
638 Triple.c_str());
639 exit(1);
640 }
641
642 // Remove the number.
643 Triple.resize(DarwinNumIdx);
644
645 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
646 bool MacOSVersionMinIsInvalid = false;
647 int VersionNum = 0;
648 if (MacOSVersionMin.size() < 4 ||
649 MacOSVersionMin.substr(0, 3) != "10." ||
650 !isdigit(MacOSVersionMin[3])) {
651 MacOSVersionMinIsInvalid = true;
652 } else {
653 const char *Start = MacOSVersionMin.c_str()+3;
654 char *End = 0;
655 VersionNum = (int)strtol(Start, &End, 10);
656
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000657 // The version number must be in the range 0-9.
658 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
659
Chris Lattner01de9c82008-09-30 20:16:56 +0000660 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
661 Triple += llvm::itostr(VersionNum+4);
662
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000663 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
664 // Add the period piece (.7) to the end of the triple. This gives us
665 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000666 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000667 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
668 MacOSVersionMinIsInvalid = true;
669 }
670 }
671
672 if (MacOSVersionMinIsInvalid) {
673 fprintf(stderr,
674 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
675 MacOSVersionMin.c_str());
676 exit(1);
677 }
678}
679
680/// CreateTargetTriple - Process the various options that affect the target
681/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000682static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000683 // Initialize base triple. If a -triple option has been specified, use
684 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000685 std::string Triple = TargetTriple;
686 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000687
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000688 // If -arch foo was specified, remove the architecture from the triple we have
689 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000690 if (!Arch.empty()) {
691 // Decompose the base triple into "arch" and suffix.
692 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000693
Chris Lattner2b168e02008-09-30 01:13:12 +0000694 if (FirstDashIdx == std::string::npos) {
695 fprintf(stderr,
696 "Malformed target triple: \"%s\" ('-' could not be found).\n",
697 Triple.c_str());
698 exit(1);
699 }
Ted Kremenek40499482007-12-03 22:06:55 +0000700
Chris Lattner2b168e02008-09-30 01:13:12 +0000701 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
702 }
703
704 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
705 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000706 if (!MacOSVersionMin.empty())
707 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000708
Chris Lattner2b168e02008-09-30 01:13:12 +0000709 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000710}
711
712//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000713// Preprocessor Initialization
714//===----------------------------------------------------------------------===//
715
716// FIXME: Preprocessor builtins to support.
717// -A... - Play with #assertions
718// -undef - Undefine all predefined macros
719
720static llvm::cl::list<std::string>
721D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
722 llvm::cl::desc("Predefine the specified macro"));
723static llvm::cl::list<std::string>
724U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
725 llvm::cl::desc("Undefine the specified macro"));
726
Chris Lattner008da782008-01-10 01:53:41 +0000727static llvm::cl::list<std::string>
728ImplicitIncludes("include", llvm::cl::value_desc("file"),
729 llvm::cl::desc("Include file before parsing"));
730
731
Chris Lattner4b009652007-07-25 00:24:17 +0000732// Append a #define line to Buf for Macro. Macro should be of the form XXX,
733// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
734// "#define XXX Y z W". To get a #define with no value, use "XXX=".
735static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
736 const char *Command = "#define ") {
737 Buf.insert(Buf.end(), Command, Command+strlen(Command));
738 if (const char *Equal = strchr(Macro, '=')) {
739 // Turn the = into ' '.
740 Buf.insert(Buf.end(), Macro, Equal);
741 Buf.push_back(' ');
742 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
743 } else {
744 // Push "macroname 1".
745 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
746 Buf.push_back(' ');
747 Buf.push_back('1');
748 }
749 Buf.push_back('\n');
750}
751
Chris Lattner008da782008-01-10 01:53:41 +0000752/// AddImplicitInclude - Add an implicit #include of the specified file to the
753/// predefines buffer.
754static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
755 const char *Inc = "#include \"";
756 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
757 Buf.insert(Buf.end(), File.begin(), File.end());
758 Buf.push_back('"');
759 Buf.push_back('\n');
760}
761
Chris Lattner4b009652007-07-25 00:24:17 +0000762
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000763/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000764/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000765///
Chris Lattner9d818a22008-04-19 23:25:44 +0000766static bool InitializePreprocessor(Preprocessor &PP,
767 bool InitializeSourceMgr,
768 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000769 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000770
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000771 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000772 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000773
774 if (InitializeSourceMgr) {
775 if (InFile != "-") {
776 const FileEntry *File = FileMgr.getFile(InFile);
777 if (File) SourceMgr.createMainFileID(File, SourceLocation());
778 if (SourceMgr.getMainFileID() == 0) {
779 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000780 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000781 }
782 } else {
783 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
784 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
785 if (SourceMgr.getMainFileID() == 0) {
786 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000787 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000788 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000789 }
Chris Lattner4b009652007-07-25 00:24:17 +0000790 }
Sam Bishop61a20782008-04-14 14:41:57 +0000791
Chris Lattner47b6a162008-04-19 23:09:31 +0000792 std::vector<char> PredefineBuffer;
793
Chris Lattner4b009652007-07-25 00:24:17 +0000794 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000795 unsigned d = 0, D = D_macros.size();
796 unsigned u = 0, U = U_macros.size();
797 while (d < D || u < U) {
798 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
799 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
800 else
801 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
802 }
803
Chris Lattner008da782008-01-10 01:53:41 +0000804 // FIXME: Read any files specified by -imacros.
805
806 // Add implicit #includes from -include.
807 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
808 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000809
Chris Lattner47b6a162008-04-19 23:09:31 +0000810 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000811 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000812 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000813
814 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000815 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000816}
817
818//===----------------------------------------------------------------------===//
819// Preprocessor include path information.
820//===----------------------------------------------------------------------===//
821
822// This tool exports a large number of command line options to control how the
823// preprocessor searches for header files. At root, however, the Preprocessor
824// object takes a very simple interface: a list of directories to search for
825//
826// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000827// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000828//
Chris Lattner008da782008-01-10 01:53:41 +0000829// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000830
831static llvm::cl::opt<bool>
832nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
833
834// Various command line options. These four add directories to each chain.
835static llvm::cl::list<std::string>
836F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
837 llvm::cl::desc("Add directory to framework include search path"));
838static llvm::cl::list<std::string>
839I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
840 llvm::cl::desc("Add directory to include search path"));
841static llvm::cl::list<std::string>
842idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
843 llvm::cl::desc("Add directory to AFTER include search path"));
844static llvm::cl::list<std::string>
845iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
846 llvm::cl::desc("Add directory to QUOTE include search path"));
847static llvm::cl::list<std::string>
848isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
849 llvm::cl::desc("Add directory to SYSTEM include search path"));
850
851// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
852static llvm::cl::list<std::string>
853iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
854 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
855static llvm::cl::list<std::string>
856iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
857 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
858static llvm::cl::list<std::string>
859iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
860 llvm::cl::Prefix,
861 llvm::cl::desc("Set directory to include search path with prefix"));
862
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000863static llvm::cl::opt<std::string>
864isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
865 llvm::cl::desc("Set the system root directory (usually /)"));
866
Chris Lattner4b009652007-07-25 00:24:17 +0000867// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +0000868
Chris Lattner4b009652007-07-25 00:24:17 +0000869/// InitializeIncludePaths - Process the -I options and set them in the
870/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +0000871void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
872 FileManager &FM, const LangOptions &Lang) {
873 InitHeaderSearch Init(Headers, Verbose, isysroot);
874
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)) {
Nico Weber770e3882008-08-22 09:25:22 +0000879 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000880 ++Iidx;
881 } else {
Nico Weber770e3882008-08-22 09:25:22 +0000882 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000883 ++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)
Nico Weber770e3882008-08-22 09:25:22 +0000889 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000890 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +0000891 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000892
893 // Handle -idirafter... options.
894 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000895 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
896 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000897
898 // Handle -iquote... options.
899 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000900 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000901
902 // Handle -isystem... options.
903 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000904 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000905
906 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
907 // parallel, processing the values in order of occurance to get the right
908 // prefixes.
909 {
910 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
911 unsigned iprefix_idx = 0;
912 unsigned iwithprefix_idx = 0;
913 unsigned iwithprefixbefore_idx = 0;
914 bool iprefix_done = iprefix_vals.empty();
915 bool iwithprefix_done = iwithprefix_vals.empty();
916 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
917 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
918 if (!iprefix_done &&
919 (iwithprefix_done ||
920 iprefix_vals.getPosition(iprefix_idx) <
921 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
922 (iwithprefixbefore_done ||
923 iprefix_vals.getPosition(iprefix_idx) <
924 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
925 Prefix = iprefix_vals[iprefix_idx];
926 ++iprefix_idx;
927 iprefix_done = iprefix_idx == iprefix_vals.size();
928 } else if (!iwithprefix_done &&
929 (iwithprefixbefore_done ||
930 iwithprefix_vals.getPosition(iwithprefix_idx) <
931 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +0000932 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
933 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000934 ++iwithprefix_idx;
935 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
936 } else {
Nico Weber770e3882008-08-22 09:25:22 +0000937 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
938 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000939 ++iwithprefixbefore_idx;
940 iwithprefixbefore_done =
941 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
942 }
943 }
944 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000945
Nico Weber770e3882008-08-22 09:25:22 +0000946 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +0000947
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000948 // Add the clang headers, which are relative to the clang driver.
949 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000950 llvm::sys::Path::GetMainExecutable(Argv0,
951 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000952 if (!MainExecutablePath.isEmpty()) {
953 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
954 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
955 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +0000956 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
957 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000958 }
959
Nico Weber770e3882008-08-22 09:25:22 +0000960 if (!nostdinc)
961 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +0000962
963 // Now that we have collected all of the include paths, merge them all
964 // together and tell the preprocessor about them.
965
Nico Weber770e3882008-08-22 09:25:22 +0000966 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +0000967}
968
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000969//===----------------------------------------------------------------------===//
970// Driver PreprocessorFactory - For lazily generating preprocessors ...
971//===----------------------------------------------------------------------===//
972
973namespace {
974class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000975 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000976 Diagnostic &Diags;
977 const LangOptions &LangInfo;
978 TargetInfo &Target;
979 SourceManager &SourceMgr;
980 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000981 bool InitializeSourceMgr;
982
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000983public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000984 DriverPreprocessorFactory(const std::string &infile,
985 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000986 TargetInfo &target, SourceManager &SM,
987 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000988 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
989 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
990
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000991
992 virtual ~DriverPreprocessorFactory() {}
993
994 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000995 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
996 SourceMgr, HeaderInfo);
997
Chris Lattner9d818a22008-04-19 23:25:44 +0000998 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000999 delete PP;
1000 return NULL;
1001 }
1002
1003 InitializeSourceMgr = false;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001004 return PP;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001005 }
1006};
1007}
Chris Lattner4b009652007-07-25 00:24:17 +00001008
Chris Lattner4b009652007-07-25 00:24:17 +00001009//===----------------------------------------------------------------------===//
1010// Basic Parser driver
1011//===----------------------------------------------------------------------===//
1012
Chris Lattner9d818a22008-04-19 23:25:44 +00001013static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001014 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001015 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001016
1017 // Parsing the specified input file.
1018 P.ParseTranslationUnit();
1019 delete PA;
Argiris Kirtzidis8d833762008-06-13 12:15:34 +00001020
1021 if (VerifyDiagnostics)
1022 exit(CheckDiagnostics(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001023}
1024
1025//===----------------------------------------------------------------------===//
1026// Main driver
1027//===----------------------------------------------------------------------===//
1028
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001029/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1030/// action. These consumers can operate on both ASTs that are freshly
1031/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001032static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001033 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001034 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001035 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001036 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001037 switch (ProgAction) {
1038 default:
1039 return NULL;
1040
1041 case ASTPrint:
1042 return CreateASTPrinter();
1043
1044 case ASTDump:
1045 return CreateASTDumper();
1046
1047 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001048 return CreateASTViewer();
1049
1050 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001051 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001052
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001053 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001054 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001055
1056 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001057 case EmitBC:
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001058 return CreateLLVMCodeGenWriter(ProgAction == EmitBC, Diag, LangOpts,
1059 InFile, OutputFile, GenerateDebugInfo);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001060
Ted Kremenekbde30332007-12-19 17:25:59 +00001061 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001062 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001063 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001064
Steve Naroff44e81222008-04-14 22:03:09 +00001065 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001066 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001067
1068 case RewriteBlocks:
1069 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001070
1071 case RunAnalysis:
1072 assert (!AnalysisList.empty());
1073 return CreateAnalysisConsumer(&AnalysisList[0],
1074 &AnalysisList[0]+AnalysisList.size(),
1075 Diag, PP, PPF, LangOpts,
1076 AnalyzeSpecificFunction,
Ted Kremenekcf262252008-08-27 22:31:43 +00001077 OutputFile, VisualizeEGDot, VisualizeEGUbi,
1078 TrimGraph, AnalyzeAll);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001079 }
1080}
1081
Chris Lattner4b009652007-07-25 00:24:17 +00001082/// ProcessInputFile - Process a single input file with the specified state.
1083///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001084static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1085 const std::string &InFile) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001086
Ted Kremenek50aab982008-08-08 02:46:37 +00001087 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001088 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001089
Chris Lattner4b009652007-07-25 00:24:17 +00001090 switch (ProgAction) {
1091 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001092 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1093 PP.getFileManager(), PP.getLangOptions(),
1094 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001095
1096 if (!Consumer) {
1097 fprintf(stderr, "Unexpected program action!\n");
1098 return;
1099 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001100
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001101 break;
1102
Chris Lattner4b009652007-07-25 00:24:17 +00001103 case DumpTokens: { // Token dump mode.
1104 Token Tok;
1105 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001106 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001107 do {
1108 PP.Lex(Tok);
1109 PP.DumpToken(Tok, true);
1110 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001111 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001112 ClearSourceMgr = true;
1113 break;
1114 }
1115 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1116 Token Tok;
1117 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001118 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001119 do {
1120 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001121 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001122 ClearSourceMgr = true;
1123 break;
1124 }
1125
1126 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001127 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001128 ClearSourceMgr = true;
1129 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001130
Chris Lattner4b009652007-07-25 00:24:17 +00001131 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001132 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001133 ClearSourceMgr = true;
1134 break;
1135
1136 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001137 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001138 ClearSourceMgr = true;
1139 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001140
Ted Kremenek6856c632007-09-26 18:39:29 +00001141 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001142 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001143 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001144
1145 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001146 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001147 ClearSourceMgr = true;
1148 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001149 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001150
1151 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001152 if (VerifyDiagnostics)
Ted Kremenek50aab982008-08-08 02:46:37 +00001153 exit(CheckASTConsumer(PP, Consumer.get()));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001154
Ted Kremenek50aab982008-08-08 02:46:37 +00001155 ParseAST(PP, Consumer.get(), Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001156 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001157
Chris Lattner4b009652007-07-25 00:24:17 +00001158 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001159 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001160 PP.PrintStats();
1161 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001162 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001163 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001164 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001165 fprintf(stderr, "\n");
1166 }
1167
1168 // For a multi-file compilation, some things are ok with nuking the source
1169 // manager tables, other require stable fileid/macroid's across multiple
1170 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001171 if (ClearSourceMgr)
1172 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001173}
1174
Ted Kremenek80d53372007-12-12 23:41:08 +00001175static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1176 FileManager& FileMgr) {
1177
1178 if (VerifyDiagnostics) {
1179 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1180 exit (1);
1181 }
1182
1183 llvm::sys::Path Filename(InFile);
1184
1185 if (!Filename.isValid()) {
1186 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1187 exit (1);
1188 }
1189
Ted Kremenek863b01f2008-04-23 16:25:39 +00001190 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001191
1192 if (!TU) {
1193 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1194 InFile.c_str());
1195 exit (1);
1196 }
1197
Ted Kremenekab749372007-12-19 19:27:38 +00001198 // Observe that we use the source file name stored in the deserialized
1199 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001200 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001201 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001202 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001203
Ted Kremenek80d53372007-12-12 23:41:08 +00001204 if (!Consumer) {
1205 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1206 exit (1);
1207 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001208
Ted Kremenek863b01f2008-04-23 16:25:39 +00001209 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001210
Chris Lattner8d72ee02008-02-06 01:42:25 +00001211 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001212 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1213 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001214}
1215
1216
Chris Lattner4b009652007-07-25 00:24:17 +00001217static llvm::cl::list<std::string>
1218InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1219
Ted Kremenek80d53372007-12-12 23:41:08 +00001220static bool isSerializedFile(const std::string& InFile) {
1221 if (InFile.size() < 4)
1222 return false;
1223
1224 const char* s = InFile.c_str()+InFile.size()-4;
1225
1226 return s[0] == '.' &&
1227 s[1] == 'a' &&
1228 s[2] == 's' &&
1229 s[3] == 't';
1230}
1231
Chris Lattner4b009652007-07-25 00:24:17 +00001232
1233int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001234 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001235 llvm::sys::PrintStackTraceOnErrorSignal();
1236
1237 // If no input was specified, read from stdin.
1238 if (InputFilenames.empty())
1239 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001240
Chris Lattner4b009652007-07-25 00:24:17 +00001241 // Create a file manager object to provide access to and cache the filesystem.
1242 FileManager FileMgr;
1243
Ted Kremenekb240e822007-12-11 23:28:38 +00001244 // Create the diagnostic client for reporting errors or for
1245 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001246 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001247
Ted Kremenek5c341732008-08-07 17:49:57 +00001248 if (!VerifyDiagnostics) {
1249 // Print diagnostics to stderr by default.
1250 TextDiagClient = new TextDiagnosticPrinter(!NoShowColumn,
1251 !NoCaretDiagnostics);
1252 } else {
1253 // When checking diagnostics, just buffer them up.
1254 TextDiagClient = new TextDiagnosticBuffer();
1255
1256 if (InputFilenames.size() != 1) {
1257 fprintf(stderr,
1258 "-verify only works on single input files for now.\n");
1259 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001260 }
1261 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001262
Chris Lattner4b009652007-07-25 00:24:17 +00001263 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001264 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1265 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001266 InitializeDiagnostics(Diags);
1267
Chris Lattner45a56e02007-12-05 23:24:17 +00001268 // -I- is a deprecated GCC feature, scan for it and reject it.
1269 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1270 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001271 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001272 I_dirs.erase(I_dirs.begin()+i);
1273 --i;
1274 }
1275 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001276
1277 // Get information about the target being compiled for.
1278 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001279 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1280
Chris Lattner2c77d852008-03-14 06:12:05 +00001281 if (Target == 0) {
1282 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1283 Triple.c_str());
1284 fprintf(stderr, "Please use -triple or -arch.\n");
1285 exit(1);
1286 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001287
Ted Kremenek81ea7992008-07-02 00:03:09 +00001288 // Are we invoking one or more source analyses?
1289 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1290 ProgAction = RunAnalysis;
Ted Kremenek5c341732008-08-07 17:49:57 +00001291
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001292 llvm::OwningPtr<SourceManager> SourceMgr;
1293
Chris Lattner4b009652007-07-25 00:24:17 +00001294 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001295 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001296
Ted Kremenek5c341732008-08-07 17:49:57 +00001297 if (isSerializedFile(InFile)) {
1298 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001299 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001300 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001301 else {
1302 /// Create a SourceManager object. This tracks and owns all the file
1303 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001304 if (!SourceMgr)
1305 SourceMgr.reset(new SourceManager());
1306 else
1307 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001308
Ted Kremenek80d53372007-12-12 23:41:08 +00001309 // Initialize language options, inferring file types from input filenames.
1310 LangOptions LangInfo;
1311 InitializeBaseLanguage();
1312 LangKind LK = GetLanguage(InFile);
1313 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar34542952008-08-23 08:43:39 +00001314 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001315 InitializeGCMode(LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001316
1317 // Process the -I options and set them in the HeaderInfo.
1318 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001319
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001320 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001321
Ted Kremenek80d53372007-12-12 23:41:08 +00001322 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001323 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001324 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001325
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001326 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1327
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001328 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001329 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001330
1331 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1332 // always reset to using TextDiagClient.
1333 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001334
Ted Kremenek5c341732008-08-07 17:49:57 +00001335 if (!HTMLDiag.empty()) {
1336 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1337 &PPFactory));
1338 Diags.setClient(TmpClient.get());
1339 }
1340 else
1341 Diags.setClient(TextDiagClient);
1342
1343 // Process the source file.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001344 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001345 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001346
1347 if (Stats)
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001348 SourceMgr->PrintStats();
Ted Kremenek80d53372007-12-12 23:41:08 +00001349 }
Chris Lattner4b009652007-07-25 00:24:17 +00001350 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001351
Ted Kremenekec6c5252008-08-07 18:13:12 +00001352 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001353 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1354 (NumDiagnostics == 1 ? "" : "s"));
1355
1356 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001357 FileMgr.PrintStats();
1358 fprintf(stderr, "\n");
1359 }
1360
1361 return Diags.getNumErrors() != 0;
1362}