blob: 8e5bca22f81b2f5562f30c354707e1f7acf207a4 [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"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000048#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000049#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000050#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000051using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// Global options.
55//===----------------------------------------------------------------------===//
56
Daniel Dunbar70a66b12008-10-04 23:42:49 +000057bool HadErrors = false;
58
Chris Lattner4b009652007-07-25 00:24:17 +000059static llvm::cl::opt<bool>
60Verbose("v", llvm::cl::desc("Enable verbose output"));
61static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000062Stats("print-stats",
63 llvm::cl::desc("Print performance metrics and statistics"));
Chris Lattner4b009652007-07-25 00:24:17 +000064
65enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000066 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000067 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000068 RewriteMacros, // Expand macros but not #includes.
Ted Kremeneke1a79d82008-03-19 07:53:42 +000069 HTMLTest, // HTML displayer testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000070 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000071 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000072 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000073 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000074 ASTPrint, // Parse ASTs and print them.
75 ASTDump, // Parse ASTs and dump them.
76 ASTView, // Parse ASTs and view them in Graphviz.
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 Kremenek221bb8d2007-10-16 23:37:27 +0000111 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000112 "Run prototype serialization code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000113 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000114 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000115 clEnumValN(EmitBC, "emit-llvm-bc",
116 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000117 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000118 "Build ASTs and emit .ast file"),
Steve Naroff44e81222008-04-14 22:03:09 +0000119 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000120 "Rewrite ObjC into C (code rewriter example)"),
121 clEnumValN(RewriteMacros, "rewrite-macros",
122 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000123 clEnumValN(RewriteBlocks, "rewrite-blocks",
124 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000125 clEnumValEnd));
126
Ted Kremenekd01eae62007-12-19 19:47:59 +0000127
128static llvm::cl::opt<std::string>
129OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000130 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000131 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000132
133//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000134// Code Generator Options
135//===----------------------------------------------------------------------===//
136static llvm::cl::opt<bool>
137GenerateDebugInfo("g",
138 llvm::cl::desc("Generate source level debug information"));
139
140//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000141// Diagnostic Options
142//===----------------------------------------------------------------------===//
143
Ted Kremenek10389cf2007-09-26 19:42:19 +0000144static llvm::cl::opt<bool>
145VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000146 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000147
Ted Kremenekfd75e312008-03-27 06:17:42 +0000148static llvm::cl::opt<std::string>
149HTMLDiag("html-diags",
150 llvm::cl::desc("Generate HTML to report diagnostics"),
151 llvm::cl::value_desc("HTML directory"));
152
Nico Weber0e13eaa2008-08-05 23:33:20 +0000153static llvm::cl::opt<bool>
154NoShowColumn("fno-show-column",
155 llvm::cl::desc("Do not include column number on diagnostics"));
156
157static llvm::cl::opt<bool>
158NoCaretDiagnostics("fno-caret-diagnostics",
159 llvm::cl::desc("Do not include source line and caret with"
160 " diagnostics"));
161
162
Chris Lattner4b009652007-07-25 00:24:17 +0000163//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000164// Analyzer Options
165//===----------------------------------------------------------------------===//
166
167static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000168VisualizeEGDot("analyzer-viz-egraph-graphviz",
169 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000170
171static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000172VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
173 llvm::cl::desc("Display exploded graph using Ubigraph"));
174
175static llvm::cl::opt<bool>
176AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek517cb512008-04-14 18:40:58 +0000177 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000178 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000179
Ted Kremenek81ea7992008-07-02 00:03:09 +0000180static llvm::cl::list<Analyses>
181AnalysisList(llvm::cl::desc("Available Source Code Analyses:"),
182llvm::cl::values(
Ted Kremenekfbda0ef2008-07-15 00:46:02 +0000183#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenek8ce61b32008-07-14 23:41:13 +0000184clEnumValN(NAME, CMDFLAG, DESC),
185#include "Analyses.def"
186clEnumValEnd));
Ted Kremenek81ea7992008-07-02 00:03:09 +0000187
Ted Kremenek517cb512008-04-14 18:40:58 +0000188//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000189// Language Options
190//===----------------------------------------------------------------------===//
191
192enum LangKind {
193 langkind_unspecified,
194 langkind_c,
195 langkind_c_cpp,
196 langkind_cxx,
197 langkind_cxx_cpp,
198 langkind_objc,
199 langkind_objc_cpp,
200 langkind_objcxx,
201 langkind_objcxx_cpp
202};
203
204/* TODO: GCC also accepts:
205 c-header c++-header objective-c-header objective-c++-header
206 assembler assembler-with-cpp
207 ada, f77*, ratfor (!), f95, java, treelang
208 */
209static llvm::cl::opt<LangKind>
210BaseLang("x", llvm::cl::desc("Base language to compile"),
211 llvm::cl::init(langkind_unspecified),
212 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
213 clEnumValN(langkind_cxx, "c++", "C++"),
214 clEnumValN(langkind_objc, "objective-c", "Objective C"),
215 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
216 clEnumValN(langkind_c_cpp, "c-cpp-output",
217 "Preprocessed C"),
218 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
219 "Preprocessed C++"),
220 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
221 "Preprocessed Objective C"),
222 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
223 "Preprocessed Objective C++"),
224 clEnumValEnd));
225
226static llvm::cl::opt<bool>
227LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
228 llvm::cl::Hidden);
229static llvm::cl::opt<bool>
230LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
231 llvm::cl::Hidden);
232
Ted Kremenek11ad8952007-12-05 23:49:08 +0000233/// InitializeBaseLanguage - Handle the -x foo options.
234static void InitializeBaseLanguage() {
235 if (LangObjC)
236 BaseLang = langkind_objc;
237 else if (LangObjCXX)
238 BaseLang = langkind_objcxx;
239}
240
241static LangKind GetLanguage(const std::string &Filename) {
242 if (BaseLang != langkind_unspecified)
243 return BaseLang;
244
245 std::string::size_type DotPos = Filename.rfind('.');
246
247 if (DotPos == std::string::npos) {
248 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000249 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000250 }
251
Ted Kremenek11ad8952007-12-05 23:49:08 +0000252 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
253 // C header: .h
254 // C++ header: .hh or .H;
255 // assembler no preprocessing: .s
256 // assembler: .S
257 if (Ext == "c")
258 return langkind_c;
259 else if (Ext == "i")
260 return langkind_c_cpp;
261 else if (Ext == "ii")
262 return langkind_cxx_cpp;
263 else if (Ext == "m")
264 return langkind_objc;
265 else if (Ext == "mi")
266 return langkind_objc_cpp;
267 else if (Ext == "mm" || Ext == "M")
268 return langkind_objcxx;
269 else if (Ext == "mii")
270 return langkind_objcxx_cpp;
271 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
272 Ext == "c++" || Ext == "cp" || Ext == "cxx")
273 return langkind_cxx;
274 else
275 return langkind_c;
276}
277
278
279static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000280 // FIXME: implement -fpreprocessed mode.
281 bool NoPreprocess = false;
282
Ted Kremenek11ad8952007-12-05 23:49:08 +0000283 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000284 default: assert(0 && "Unknown language kind!");
285 case langkind_c_cpp:
286 NoPreprocess = true;
287 // FALLTHROUGH
288 case langkind_c:
289 break;
290 case langkind_cxx_cpp:
291 NoPreprocess = true;
292 // FALLTHROUGH
293 case langkind_cxx:
294 Options.CPlusPlus = 1;
295 break;
296 case langkind_objc_cpp:
297 NoPreprocess = true;
298 // FALLTHROUGH
299 case langkind_objc:
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000300 Options.ObjC1 = Options.ObjC2 = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000301 break;
302 case langkind_objcxx_cpp:
303 NoPreprocess = true;
304 // FALLTHROUGH
305 case langkind_objcxx:
306 Options.ObjC1 = Options.ObjC2 = 1;
307 Options.CPlusPlus = 1;
308 break;
309 }
310}
311
312/// LangStds - Language standards we support.
313enum LangStds {
314 lang_unspecified,
315 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000316 lang_gnu_START,
317 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000318 lang_cxx98, lang_gnucxx98,
319 lang_cxx0x, lang_gnucxx0x
320};
321
322static llvm::cl::opt<LangStds>
323LangStd("std", llvm::cl::desc("Language standard to compile for"),
324 llvm::cl::init(lang_unspecified),
325 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
326 clEnumValN(lang_c89, "c90", "ISO C 1990"),
327 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
328 clEnumValN(lang_c94, "iso9899:199409",
329 "ISO C 1990 with amendment 1"),
330 clEnumValN(lang_c99, "c99", "ISO C 1999"),
331// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
332 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
333// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
334 clEnumValN(lang_gnu89, "gnu89",
335 "ISO C 1990 with GNU extensions (default for C)"),
336 clEnumValN(lang_gnu99, "gnu99",
337 "ISO C 1999 with GNU extensions"),
338 clEnumValN(lang_gnu99, "gnu9x",
339 "ISO C 1999 with GNU extensions"),
340 clEnumValN(lang_cxx98, "c++98",
341 "ISO C++ 1998 with amendments"),
342 clEnumValN(lang_gnucxx98, "gnu++98",
343 "ISO C++ 1998 with amendments and GNU "
344 "extensions (default for C++)"),
345 clEnumValN(lang_cxx0x, "c++0x",
346 "Upcoming ISO C++ 200x with amendments"),
347 clEnumValN(lang_gnucxx0x, "gnu++0x",
348 "Upcoming ISO C++ 200x with amendments and GNU "
349 "extensions (default for C++)"),
350 clEnumValEnd));
351
352static llvm::cl::opt<bool>
353NoOperatorNames("fno-operator-names",
354 llvm::cl::desc("Do not treat C++ operator name keywords as "
355 "synonyms for operators"));
356
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000357static llvm::cl::opt<bool>
358PascalStrings("fpascal-strings",
359 llvm::cl::desc("Recognize and construct Pascal-style "
360 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000361
362static llvm::cl::opt<bool>
363MSExtensions("fms-extensions",
364 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000365 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000366
367static llvm::cl::opt<bool>
368WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000369 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000370
371static llvm::cl::opt<bool>
372LaxVectorConversions("flax-vector-conversions",
373 llvm::cl::desc("Allow implicit conversions between vectors"
374 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000375 "different element types"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000376
Daniel Dunbar91692d92008-08-11 17:36:14 +0000377// FIXME: This (and all GCC -f options) really come in -f... and
378// -fno-... forms, and additionally support automagic behavior when
379// they are not defined. For example, -fexceptions defaults to on or
380// off depending on the language. We should support this behavior in
381// some form (perhaps just add a facility for distinguishing when an
382// has its default value from when it has been set to its default
383// value).
384static llvm::cl::opt<bool>
385Exceptions("fexceptions",
386 llvm::cl::desc("Enable support for exception handling."));
387
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000388static llvm::cl::opt<bool>
389GNURuntime("fgnu-runtime",
390 llvm::cl::desc("Generate output compatible with the standard GNU Objective-C runtime."));
391
392static llvm::cl::opt<bool>
393NeXTRuntime("fnext-runtime",
394 llvm::cl::desc("Generate output compatible with the NeXT runtime."));
395
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000396
397
398static llvm::cl::opt<bool>
399Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
400
401static llvm::cl::opt<bool>
402Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
403
Chris Lattner4b009652007-07-25 00:24:17 +0000404// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000405// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000406// -fpascal-strings
Daniel Dunbar34542952008-08-23 08:43:39 +0000407static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
408 TargetInfo *Target) {
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000409
410 if (Ansi) // "The -ansi option is equivalent to -std=c89."
411 LangStd = lang_c89;
412
Chris Lattner4b009652007-07-25 00:24:17 +0000413 if (LangStd == lang_unspecified) {
414 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000415 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000416 default: assert(0 && "Unknown base language");
417 case langkind_c:
418 case langkind_c_cpp:
419 case langkind_objc:
420 case langkind_objc_cpp:
421 LangStd = lang_gnu99;
422 break;
423 case langkind_cxx:
424 case langkind_cxx_cpp:
425 case langkind_objcxx:
426 case langkind_objcxx_cpp:
427 LangStd = lang_gnucxx98;
428 break;
429 }
430 }
431
432 switch (LangStd) {
433 default: assert(0 && "Unknown language standard!");
434
435 // Fall through from newer standards to older ones. This isn't really right.
436 // FIXME: Enable specifically the right features based on the language stds.
437 case lang_gnucxx0x:
438 case lang_cxx0x:
439 Options.CPlusPlus0x = 1;
440 // FALL THROUGH
441 case lang_gnucxx98:
442 case lang_cxx98:
443 Options.CPlusPlus = 1;
444 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000445 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000446 // FALL THROUGH.
447 case lang_gnu99:
448 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000449 Options.C99 = 1;
450 Options.HexFloats = 1;
451 // FALL THROUGH.
452 case lang_gnu89:
453 Options.BCPLComment = 1; // Only for C99/C++.
454 // FALL THROUGH.
455 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000456 Options.Digraphs = 1; // C94, C99, C++.
457 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000458 case lang_c89:
459 break;
460 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000461
462 if (Options.CPlusPlus) {
463 Options.C99 = 0;
464 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
465 }
Chris Lattner4b009652007-07-25 00:24:17 +0000466
Chris Lattner6ab935b2008-04-05 06:32:51 +0000467 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
468 Options.ImplicitInt = 1;
469 else
470 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000471
472 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
473 // is specified, or -std is set to a conforming mode.
474 Options.Trigraphs = LangStd < lang_gnu_START || Trigraphs ? 1 : 0;
475
Chris Lattner4b009652007-07-25 00:24:17 +0000476 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000477 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000478 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000479 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000480 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000481 Options.Exceptions = Exceptions;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000482
483 if (NeXTRuntime) {
484 Options.NeXTRuntime = 1;
485 } else if (GNURuntime) {
486 Options.NeXTRuntime = 0;
487 } else {
Daniel Dunbar34542952008-08-23 08:43:39 +0000488 Options.NeXTRuntime = Target->useNeXTRuntimeAsDefault();
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000489 }
Chris Lattner4b009652007-07-25 00:24:17 +0000490}
491
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000492static llvm::cl::opt<bool>
493ObjCExclusiveGC("fobjc-gc-only",
494 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000495 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000496
497static llvm::cl::opt<bool>
498ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000499 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000500
501void InitializeGCMode(LangOptions &Options) {
502 if (ObjCExclusiveGC)
503 Options.setGCMode(LangOptions::GCOnly);
504 else if (ObjCEnableGC)
505 Options.setGCMode(LangOptions::HybridGC);
506}
507
508
Chris Lattner4b009652007-07-25 00:24:17 +0000509//===----------------------------------------------------------------------===//
510// Our DiagnosticClient implementation
511//===----------------------------------------------------------------------===//
512
513// FIXME: Werror should take a list of things, -Werror=foo,bar
514static llvm::cl::opt<bool>
515WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
516
517static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000518SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
519
520static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000521WarnOnExtensions("pedantic", llvm::cl::init(false),
522 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
523
524static llvm::cl::opt<bool>
525ErrorOnExtensions("pedantic-errors",
526 llvm::cl::desc("Issue an error on uses of GCC extensions"));
527
528static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000529SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar35e50942008-09-30 20:49:53 +0000530 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000531 llvm::cl::init(true));
532
533static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000534WarnUnusedMacros("Wunused_macros",
535 llvm::cl::desc("Warn for unused macros in the main translation unit"));
536
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000537static llvm::cl::opt<bool>
538WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000539 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000540
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000541static llvm::cl::opt<bool>
542WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000543 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000544
Chris Lattnera616ee32008-01-23 17:19:46 +0000545static llvm::cl::opt<bool>
546WarnUndefMacros("Wundef",
547 llvm::cl::desc("Warn on use of undefined macros in #if's"));
548
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000549static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000550WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
551 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000552
Chris Lattner4b009652007-07-25 00:24:17 +0000553/// InitializeDiagnostics - Initialize the diagnostic object, based on the
554/// current command line option settings.
555static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000556 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000557 Diags.setWarningsAsErrors(WarningsAsErrors);
558 Diags.setWarnOnExtensions(WarnOnExtensions);
559 Diags.setErrorOnExtensions(ErrorOnExtensions);
560
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000561 // Suppress warnings in system headers unless requested not to.
562 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
563
Chris Lattner4b009652007-07-25 00:24:17 +0000564 // Silence the "macro is not used" warning unless requested.
565 if (!WarnUnusedMacros)
566 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000567
568 // Silence "floating point comparison" warnings unless requested.
569 if (!WarnFloatEqual)
570 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000571
572 // Silence "format string is not a string literal" warnings if requested
573 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000574 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
575 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000576 if (!WarnUndefMacros)
577 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000578
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000579 if (!WarnImplicitFunctionDeclaration)
580 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
581 diag::MAP_IGNORE);
582
Steve Naroff606f7072008-02-11 22:40:08 +0000583 if (MSExtensions) // MS allows unnamed struct/union fields.
584 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner057a2f52008-05-04 23:52:02 +0000585
586 // If -pedantic-errors is set, turn extensions that warn by default into
587 // errors.
588 if (ErrorOnExtensions) {
589 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
590 diag::MAP_ERROR);
591 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
592 diag::MAP_ERROR);
593 }
Chris Lattner4b009652007-07-25 00:24:17 +0000594}
595
596//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000597// Analysis-specific options.
598//===----------------------------------------------------------------------===//
599
600static llvm::cl::opt<std::string>
601AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000602 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000603
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000604static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000605TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000606 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000607
Ted Kremenek0118bb52008-02-18 21:21:23 +0000608//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000609// Target Triple Processing.
610//===----------------------------------------------------------------------===//
611
612static llvm::cl::opt<std::string>
613TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000614 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000615
Chris Lattnerfc457002008-03-05 01:18:20 +0000616static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000617Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000618
Chris Lattner2b168e02008-09-30 01:13:12 +0000619static llvm::cl::opt<std::string>
620MacOSVersionMin("mmacosx-version-min",
621 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
622
Chris Lattner01de9c82008-09-30 20:16:56 +0000623// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
624// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
625static void HandleMacOSVersionMin(std::string &Triple) {
626 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
627 if (DarwinDashIdx == std::string::npos) {
628 fprintf(stderr,
629 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
630 exit(1);
631 }
632 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
633
Chris Lattner01de9c82008-09-30 20:16:56 +0000634 // Remove the number.
635 Triple.resize(DarwinNumIdx);
636
637 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
638 bool MacOSVersionMinIsInvalid = false;
639 int VersionNum = 0;
640 if (MacOSVersionMin.size() < 4 ||
641 MacOSVersionMin.substr(0, 3) != "10." ||
642 !isdigit(MacOSVersionMin[3])) {
643 MacOSVersionMinIsInvalid = true;
644 } else {
645 const char *Start = MacOSVersionMin.c_str()+3;
646 char *End = 0;
647 VersionNum = (int)strtol(Start, &End, 10);
648
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000649 // The version number must be in the range 0-9.
650 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
651
Chris Lattner01de9c82008-09-30 20:16:56 +0000652 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
653 Triple += llvm::itostr(VersionNum+4);
654
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000655 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
656 // Add the period piece (.7) to the end of the triple. This gives us
657 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000658 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000659 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
660 MacOSVersionMinIsInvalid = true;
661 }
662 }
663
664 if (MacOSVersionMinIsInvalid) {
665 fprintf(stderr,
666 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
667 MacOSVersionMin.c_str());
668 exit(1);
669 }
670}
671
672/// CreateTargetTriple - Process the various options that affect the target
673/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000674static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000675 // Initialize base triple. If a -triple option has been specified, use
676 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000677 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000678 if (Triple.empty()) {
679 Triple = LLVM_HOSTTRIPLE;
680
681 // On darwin, we want to update the version to match that of the
682 // host.
683 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
684 if (DarwinDashIdx != std::string::npos) {
685 Triple.resize(DarwinDashIdx + strlen("-darwin"));
686
687 Triple += llvm::sys::osVersion();
688 }
689 }
Ted Kremenek40499482007-12-03 22:06:55 +0000690
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000691 // If -arch foo was specified, remove the architecture from the triple we have
692 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000693 if (!Arch.empty()) {
694 // Decompose the base triple into "arch" and suffix.
695 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000696
Chris Lattner2b168e02008-09-30 01:13:12 +0000697 if (FirstDashIdx == std::string::npos) {
698 fprintf(stderr,
699 "Malformed target triple: \"%s\" ('-' could not be found).\n",
700 Triple.c_str());
701 exit(1);
702 }
Ted Kremenek40499482007-12-03 22:06:55 +0000703
Chris Lattner2b168e02008-09-30 01:13:12 +0000704 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
705 }
706
707 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
708 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000709 if (!MacOSVersionMin.empty())
710 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000711
Chris Lattner2b168e02008-09-30 01:13:12 +0000712 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000713}
714
715//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000716// Preprocessor Initialization
717//===----------------------------------------------------------------------===//
718
719// FIXME: Preprocessor builtins to support.
720// -A... - Play with #assertions
721// -undef - Undefine all predefined macros
722
723static llvm::cl::list<std::string>
724D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
725 llvm::cl::desc("Predefine the specified macro"));
726static llvm::cl::list<std::string>
727U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
728 llvm::cl::desc("Undefine the specified macro"));
729
Chris Lattner008da782008-01-10 01:53:41 +0000730static llvm::cl::list<std::string>
731ImplicitIncludes("include", llvm::cl::value_desc("file"),
732 llvm::cl::desc("Include file before parsing"));
733
734
Chris Lattner4b009652007-07-25 00:24:17 +0000735// Append a #define line to Buf for Macro. Macro should be of the form XXX,
736// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
737// "#define XXX Y z W". To get a #define with no value, use "XXX=".
738static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
739 const char *Command = "#define ") {
740 Buf.insert(Buf.end(), Command, Command+strlen(Command));
741 if (const char *Equal = strchr(Macro, '=')) {
742 // Turn the = into ' '.
743 Buf.insert(Buf.end(), Macro, Equal);
744 Buf.push_back(' ');
745 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
746 } else {
747 // Push "macroname 1".
748 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
749 Buf.push_back(' ');
750 Buf.push_back('1');
751 }
752 Buf.push_back('\n');
753}
754
Chris Lattner008da782008-01-10 01:53:41 +0000755/// AddImplicitInclude - Add an implicit #include of the specified file to the
756/// predefines buffer.
757static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
758 const char *Inc = "#include \"";
759 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
760 Buf.insert(Buf.end(), File.begin(), File.end());
761 Buf.push_back('"');
762 Buf.push_back('\n');
763}
764
Chris Lattner4b009652007-07-25 00:24:17 +0000765
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000766/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000767/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000768///
Chris Lattner9d818a22008-04-19 23:25:44 +0000769static bool InitializePreprocessor(Preprocessor &PP,
770 bool InitializeSourceMgr,
771 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000772 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000773
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000774 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000775 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000776
777 if (InitializeSourceMgr) {
778 if (InFile != "-") {
779 const FileEntry *File = FileMgr.getFile(InFile);
780 if (File) SourceMgr.createMainFileID(File, SourceLocation());
781 if (SourceMgr.getMainFileID() == 0) {
782 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000783 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000784 }
785 } else {
786 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
787 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
788 if (SourceMgr.getMainFileID() == 0) {
789 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000790 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000791 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000792 }
Chris Lattner4b009652007-07-25 00:24:17 +0000793 }
Sam Bishop61a20782008-04-14 14:41:57 +0000794
Chris Lattner47b6a162008-04-19 23:09:31 +0000795 std::vector<char> PredefineBuffer;
796
Chris Lattner4b009652007-07-25 00:24:17 +0000797 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000798 unsigned d = 0, D = D_macros.size();
799 unsigned u = 0, U = U_macros.size();
800 while (d < D || u < U) {
801 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
802 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
803 else
804 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
805 }
806
Chris Lattner008da782008-01-10 01:53:41 +0000807 // FIXME: Read any files specified by -imacros.
808
809 // Add implicit #includes from -include.
810 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
811 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000812
Chris Lattner47b6a162008-04-19 23:09:31 +0000813 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000814 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000815 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000816
817 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000818 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000819}
820
821//===----------------------------------------------------------------------===//
822// Preprocessor include path information.
823//===----------------------------------------------------------------------===//
824
825// This tool exports a large number of command line options to control how the
826// preprocessor searches for header files. At root, however, the Preprocessor
827// object takes a very simple interface: a list of directories to search for
828//
829// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000830// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000831//
Chris Lattner008da782008-01-10 01:53:41 +0000832// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000833
834static llvm::cl::opt<bool>
835nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
836
837// Various command line options. These four add directories to each chain.
838static llvm::cl::list<std::string>
839F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
840 llvm::cl::desc("Add directory to framework include search path"));
841static llvm::cl::list<std::string>
842I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
843 llvm::cl::desc("Add directory to include search path"));
844static llvm::cl::list<std::string>
845idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
846 llvm::cl::desc("Add directory to AFTER include search path"));
847static llvm::cl::list<std::string>
848iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
849 llvm::cl::desc("Add directory to QUOTE include search path"));
850static llvm::cl::list<std::string>
851isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
852 llvm::cl::desc("Add directory to SYSTEM include search path"));
853
854// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
855static llvm::cl::list<std::string>
856iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
857 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
858static llvm::cl::list<std::string>
859iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
860 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
861static llvm::cl::list<std::string>
862iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
863 llvm::cl::Prefix,
864 llvm::cl::desc("Set directory to include search path with prefix"));
865
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000866static llvm::cl::opt<std::string>
867isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
868 llvm::cl::desc("Set the system root directory (usually /)"));
869
Chris Lattner4b009652007-07-25 00:24:17 +0000870// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +0000871
Chris Lattner4b009652007-07-25 00:24:17 +0000872/// InitializeIncludePaths - Process the -I options and set them in the
873/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +0000874void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
875 FileManager &FM, const LangOptions &Lang) {
876 InitHeaderSearch Init(Headers, Verbose, isysroot);
877
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000878 // Handle -I... and -F... options, walking the lists in parallel.
879 unsigned Iidx = 0, Fidx = 0;
880 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
881 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +0000882 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000883 ++Iidx;
884 } else {
Nico Weber770e3882008-08-22 09:25:22 +0000885 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000886 ++Fidx;
887 }
888 }
Chris Lattner4b009652007-07-25 00:24:17 +0000889
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000890 // Consume what's left from whatever list was longer.
891 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +0000892 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000893 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +0000894 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000895
896 // Handle -idirafter... options.
897 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000898 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
899 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000900
901 // Handle -iquote... options.
902 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000903 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000904
905 // Handle -isystem... options.
906 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000907 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000908
909 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
910 // parallel, processing the values in order of occurance to get the right
911 // prefixes.
912 {
913 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
914 unsigned iprefix_idx = 0;
915 unsigned iwithprefix_idx = 0;
916 unsigned iwithprefixbefore_idx = 0;
917 bool iprefix_done = iprefix_vals.empty();
918 bool iwithprefix_done = iwithprefix_vals.empty();
919 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
920 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
921 if (!iprefix_done &&
922 (iwithprefix_done ||
923 iprefix_vals.getPosition(iprefix_idx) <
924 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
925 (iwithprefixbefore_done ||
926 iprefix_vals.getPosition(iprefix_idx) <
927 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
928 Prefix = iprefix_vals[iprefix_idx];
929 ++iprefix_idx;
930 iprefix_done = iprefix_idx == iprefix_vals.size();
931 } else if (!iwithprefix_done &&
932 (iwithprefixbefore_done ||
933 iwithprefix_vals.getPosition(iwithprefix_idx) <
934 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +0000935 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
936 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000937 ++iwithprefix_idx;
938 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
939 } else {
Nico Weber770e3882008-08-22 09:25:22 +0000940 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
941 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000942 ++iwithprefixbefore_idx;
943 iwithprefixbefore_done =
944 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
945 }
946 }
947 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000948
Nico Weber770e3882008-08-22 09:25:22 +0000949 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +0000950
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000951 // Add the clang headers, which are relative to the clang driver.
952 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000953 llvm::sys::Path::GetMainExecutable(Argv0,
954 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000955 if (!MainExecutablePath.isEmpty()) {
956 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
957 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
958 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +0000959 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
960 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000961 }
962
Nico Weber770e3882008-08-22 09:25:22 +0000963 if (!nostdinc)
964 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +0000965
966 // Now that we have collected all of the include paths, merge them all
967 // together and tell the preprocessor about them.
968
Nico Weber770e3882008-08-22 09:25:22 +0000969 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +0000970}
971
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000972//===----------------------------------------------------------------------===//
973// Driver PreprocessorFactory - For lazily generating preprocessors ...
974//===----------------------------------------------------------------------===//
975
976namespace {
977class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000978 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000979 Diagnostic &Diags;
980 const LangOptions &LangInfo;
981 TargetInfo &Target;
982 SourceManager &SourceMgr;
983 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000984 bool InitializeSourceMgr;
985
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000986public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000987 DriverPreprocessorFactory(const std::string &infile,
988 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000989 TargetInfo &target, SourceManager &SM,
990 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000991 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
992 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
993
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000994
995 virtual ~DriverPreprocessorFactory() {}
996
997 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000998 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
999 SourceMgr, HeaderInfo);
1000
Chris Lattner9d818a22008-04-19 23:25:44 +00001001 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001002 delete PP;
1003 return NULL;
1004 }
1005
1006 InitializeSourceMgr = false;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001007 return PP;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001008 }
1009};
1010}
Chris Lattner4b009652007-07-25 00:24:17 +00001011
Chris Lattner4b009652007-07-25 00:24:17 +00001012//===----------------------------------------------------------------------===//
1013// Basic Parser driver
1014//===----------------------------------------------------------------------===//
1015
Chris Lattner9d818a22008-04-19 23:25:44 +00001016static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001017 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001018 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001019
1020 // Parsing the specified input file.
1021 P.ParseTranslationUnit();
1022 delete PA;
1023}
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");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001098 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001099 return;
1100 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001101
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001102 break;
1103
Chris Lattner4b009652007-07-25 00:24:17 +00001104 case DumpTokens: { // Token dump mode.
1105 Token Tok;
1106 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001107 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001108 do {
1109 PP.Lex(Tok);
1110 PP.DumpToken(Tok, true);
1111 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001112 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001113 ClearSourceMgr = true;
1114 break;
1115 }
1116 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1117 Token Tok;
1118 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001119 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001120 do {
1121 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001122 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001123 ClearSourceMgr = true;
1124 break;
1125 }
1126
1127 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001128 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001129 ClearSourceMgr = true;
1130 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001131
Chris Lattner4b009652007-07-25 00:24:17 +00001132 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001133 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001134 ClearSourceMgr = true;
1135 break;
1136
1137 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001138 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001139 ClearSourceMgr = true;
1140 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001141
Ted Kremenek6856c632007-09-26 18:39:29 +00001142 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001143 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001144 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001145
1146 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001147 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001148 ClearSourceMgr = true;
1149 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001150 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001151
1152 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001153 if (VerifyDiagnostics)
Ted Kremenek50aab982008-08-08 02:46:37 +00001154 exit(CheckASTConsumer(PP, Consumer.get()));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001155
Ted Kremenek50aab982008-08-08 02:46:37 +00001156 ParseAST(PP, Consumer.get(), Stats);
Daniel Dunbarab3288e2008-10-05 01:38:39 +00001157 } else {
1158 if (VerifyDiagnostics)
1159 exit(CheckDiagnostics(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001160 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001161
Chris Lattner4b009652007-07-25 00:24:17 +00001162 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001163 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001164 PP.PrintStats();
1165 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001166 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001167 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001168 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001169 fprintf(stderr, "\n");
1170 }
1171
1172 // For a multi-file compilation, some things are ok with nuking the source
1173 // manager tables, other require stable fileid/macroid's across multiple
1174 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001175 if (ClearSourceMgr)
1176 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001177}
1178
Ted Kremenek80d53372007-12-12 23:41:08 +00001179static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1180 FileManager& FileMgr) {
1181
1182 if (VerifyDiagnostics) {
1183 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1184 exit (1);
1185 }
1186
1187 llvm::sys::Path Filename(InFile);
1188
1189 if (!Filename.isValid()) {
1190 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1191 exit (1);
1192 }
1193
Ted Kremenek863b01f2008-04-23 16:25:39 +00001194 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001195
1196 if (!TU) {
1197 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1198 InFile.c_str());
1199 exit (1);
1200 }
1201
Ted Kremenekab749372007-12-19 19:27:38 +00001202 // Observe that we use the source file name stored in the deserialized
1203 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001204 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001205 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001206 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001207
Ted Kremenek80d53372007-12-12 23:41:08 +00001208 if (!Consumer) {
1209 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1210 exit (1);
1211 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001212
Ted Kremenek863b01f2008-04-23 16:25:39 +00001213 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001214
Chris Lattner8d72ee02008-02-06 01:42:25 +00001215 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001216 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1217 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001218}
1219
1220
Chris Lattner4b009652007-07-25 00:24:17 +00001221static llvm::cl::list<std::string>
1222InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1223
Ted Kremenek80d53372007-12-12 23:41:08 +00001224static bool isSerializedFile(const std::string& InFile) {
1225 if (InFile.size() < 4)
1226 return false;
1227
1228 const char* s = InFile.c_str()+InFile.size()-4;
1229
1230 return s[0] == '.' &&
1231 s[1] == 'a' &&
1232 s[2] == 's' &&
1233 s[3] == 't';
1234}
1235
Chris Lattner4b009652007-07-25 00:24:17 +00001236
1237int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001238 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001239 llvm::sys::PrintStackTraceOnErrorSignal();
1240
1241 // If no input was specified, read from stdin.
1242 if (InputFilenames.empty())
1243 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001244
Chris Lattner4b009652007-07-25 00:24:17 +00001245 // Create a file manager object to provide access to and cache the filesystem.
1246 FileManager FileMgr;
1247
Ted Kremenekb240e822007-12-11 23:28:38 +00001248 // Create the diagnostic client for reporting errors or for
1249 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001250 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001251
Ted Kremenek5c341732008-08-07 17:49:57 +00001252 if (!VerifyDiagnostics) {
1253 // Print diagnostics to stderr by default.
1254 TextDiagClient = new TextDiagnosticPrinter(!NoShowColumn,
1255 !NoCaretDiagnostics);
1256 } else {
1257 // When checking diagnostics, just buffer them up.
1258 TextDiagClient = new TextDiagnosticBuffer();
1259
1260 if (InputFilenames.size() != 1) {
1261 fprintf(stderr,
1262 "-verify only works on single input files for now.\n");
1263 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001264 }
1265 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001266
Chris Lattner4b009652007-07-25 00:24:17 +00001267 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001268 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1269 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001270 InitializeDiagnostics(Diags);
1271
Chris Lattner45a56e02007-12-05 23:24:17 +00001272 // -I- is a deprecated GCC feature, scan for it and reject it.
1273 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1274 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001275 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001276 I_dirs.erase(I_dirs.begin()+i);
1277 --i;
1278 }
1279 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001280
1281 // Get information about the target being compiled for.
1282 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001283 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1284
Chris Lattner2c77d852008-03-14 06:12:05 +00001285 if (Target == 0) {
1286 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1287 Triple.c_str());
1288 fprintf(stderr, "Please use -triple or -arch.\n");
1289 exit(1);
1290 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001291
Ted Kremenek81ea7992008-07-02 00:03:09 +00001292 // Are we invoking one or more source analyses?
1293 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1294 ProgAction = RunAnalysis;
Ted Kremenek5c341732008-08-07 17:49:57 +00001295
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001296 llvm::OwningPtr<SourceManager> SourceMgr;
1297
Chris Lattner4b009652007-07-25 00:24:17 +00001298 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001299 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001300
Ted Kremenek5c341732008-08-07 17:49:57 +00001301 if (isSerializedFile(InFile)) {
1302 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001303 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001304 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001305 else {
1306 /// Create a SourceManager object. This tracks and owns all the file
1307 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001308 if (!SourceMgr)
1309 SourceMgr.reset(new SourceManager());
1310 else
1311 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001312
Ted Kremenek80d53372007-12-12 23:41:08 +00001313 // Initialize language options, inferring file types from input filenames.
1314 LangOptions LangInfo;
1315 InitializeBaseLanguage();
1316 LangKind LK = GetLanguage(InFile);
1317 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar34542952008-08-23 08:43:39 +00001318 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001319 InitializeGCMode(LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001320
1321 // Process the -I options and set them in the HeaderInfo.
1322 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001323
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001324 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001325
Ted Kremenek80d53372007-12-12 23:41:08 +00001326 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001327 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001328 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001329
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001330 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1331
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001332 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001333 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001334
1335 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1336 // always reset to using TextDiagClient.
1337 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001338
Ted Kremenek5c341732008-08-07 17:49:57 +00001339 if (!HTMLDiag.empty()) {
1340 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1341 &PPFactory));
1342 Diags.setClient(TmpClient.get());
1343 }
1344 else
1345 Diags.setClient(TextDiagClient);
1346
1347 // Process the source file.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001348 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001349 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001350
1351 if (Stats)
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001352 SourceMgr->PrintStats();
Ted Kremenek80d53372007-12-12 23:41:08 +00001353 }
Chris Lattner4b009652007-07-25 00:24:17 +00001354 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001355
Ted Kremenekec6c5252008-08-07 18:13:12 +00001356 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001357 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1358 (NumDiagnostics == 1 ? "" : "s"));
1359
1360 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001361 FileMgr.PrintStats();
1362 fprintf(stderr, "\n");
1363 }
1364
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001365 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001366}