blob: fb8be31c27ec05303759bc6032e59976862962ca [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"
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000027#include "clang/Driver/CompileOptions.h"
Ted Kremenek21b88b72008-11-03 22:31:48 +000028#include "clang/Driver/PathDiagnosticClients.h"
Nico Weber770e3882008-08-22 09:25:22 +000029#include "clang/Driver/InitHeaderSearch.h"
Nico Weber0e13eaa2008-08-05 23:33:20 +000030#include "clang/Driver/TextDiagnosticBuffer.h"
31#include "clang/Driver/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000032#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000033#include "clang/AST/Decl.h"
Ted Kremenekac881932007-12-18 21:34:28 +000034#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000039#include "clang/Parse/Parser.h"
40#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000041#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000042#include "clang/Basic/FileManager.h"
43#include "clang/Basic/SourceManager.h"
44#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000045#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000046#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000049#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000050#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000051#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000052#include "llvm/Support/PluginLoader.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000053#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000054#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000055#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000056using namespace clang;
57
58//===----------------------------------------------------------------------===//
59// Global options.
60//===----------------------------------------------------------------------===//
61
Daniel Dunbar4efedde2008-10-16 16:54:18 +000062static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000063
Chris Lattner4b009652007-07-25 00:24:17 +000064static llvm::cl::opt<bool>
65Verbose("v", llvm::cl::desc("Enable verbose output"));
66static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000067Stats("print-stats",
68 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000069static llvm::cl::opt<bool>
70DisableFree("disable-free",
71 llvm::cl::desc("Disable freeing of memory on exit"),
72 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000073
74enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000075 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000076 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000077 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000078 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000079 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000080 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000081 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000082 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000083 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000084 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000085 ASTPrint, // Parse ASTs and print them.
86 ASTDump, // Parse ASTs and dump them.
87 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000088 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000089 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000090 ParsePrintCallbacks, // Parse and print each callback.
91 ParseSyntaxOnly, // Parse and perform semantic analysis.
92 ParseNoop, // Parse with noop callbacks.
93 RunPreprocessorOnly, // Just lex, no output.
94 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +000095 DumpTokens, // Dump out preprocessed tokens.
96 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +000097 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +000098 GeneratePCH, // Generate precompiled header.
99 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000100};
101
102static llvm::cl::opt<ProgActions>
103ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
104 llvm::cl::init(ParseSyntaxOnly),
105 llvm::cl::values(
106 clEnumValN(RunPreprocessorOnly, "Eonly",
107 "Just run preprocessor, no output (for timings)"),
108 clEnumValN(PrintPreprocessedInput, "E",
109 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000110 clEnumValN(DumpRawTokens, "dump-raw-tokens",
111 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000112 clEnumValN(RunAnalysis, "analyze",
113 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000114 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000115 "Run preprocessor, dump internal rep of tokens"),
116 clEnumValN(ParseNoop, "parse-noop",
117 "Run parser with noop callbacks (for timings)"),
118 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
119 "Run parser and perform semantic analysis"),
120 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
121 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000122 clEnumValN(EmitHTML, "emit-html",
123 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000124 clEnumValN(ASTPrint, "ast-print",
125 "Build ASTs and then pretty-print them"),
126 clEnumValN(ASTDump, "ast-dump",
127 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000128 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000129 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000130 clEnumValN(PrintDeclContext, "print-decl-contexts",
131 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000132 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000133 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000134 clEnumValN(EmitAssembly, "S",
135 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000136 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000137 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000138 clEnumValN(EmitBC, "emit-llvm-bc",
139 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000140 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000141 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000142 clEnumValN(RewriteTest, "rewrite-test",
143 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000144 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000145 "Rewrite ObjC into C (code rewriter example)"),
146 clEnumValN(RewriteMacros, "rewrite-macros",
147 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000148 clEnumValN(RewriteBlocks, "rewrite-blocks",
149 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000150 clEnumValEnd));
151
Ted Kremenekd01eae62007-12-19 19:47:59 +0000152
153static llvm::cl::opt<std::string>
154OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000155 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000156 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000157
158//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000159// Code Generator Options
160//===----------------------------------------------------------------------===//
161static llvm::cl::opt<bool>
162GenerateDebugInfo("g",
163 llvm::cl::desc("Generate source level debug information"));
164
Ted Kremenek57f25b22008-12-02 19:57:31 +0000165
166//===----------------------------------------------------------------------===//
167// PTH.
168//===----------------------------------------------------------------------===//
169
170static llvm::cl::opt<std::string>
171TokenCache("token-cache", llvm::cl::value_desc("path"),
172 llvm::cl::desc("Use specified token cache file"));
173
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000174//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000175// Diagnostic Options
176//===----------------------------------------------------------------------===//
177
Ted Kremenek10389cf2007-09-26 19:42:19 +0000178static llvm::cl::opt<bool>
179VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000180 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000181
Ted Kremenekfd75e312008-03-27 06:17:42 +0000182static llvm::cl::opt<std::string>
183HTMLDiag("html-diags",
184 llvm::cl::desc("Generate HTML to report diagnostics"),
185 llvm::cl::value_desc("HTML directory"));
186
Nico Weber0e13eaa2008-08-05 23:33:20 +0000187static llvm::cl::opt<bool>
188NoShowColumn("fno-show-column",
189 llvm::cl::desc("Do not include column number on diagnostics"));
190
191static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000192NoShowLocation("fno-show-source-location",
193 llvm::cl::desc("Do not include source location information with"
194 " diagnostics"));
195
196static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000197NoCaretDiagnostics("fno-caret-diagnostics",
198 llvm::cl::desc("Do not include source line and caret with"
199 " diagnostics"));
200
201
Chris Lattner4b009652007-07-25 00:24:17 +0000202//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000203// C++ Visualization.
204//===----------------------------------------------------------------------===//
205
206static llvm::cl::opt<std::string>
207InheritanceViewCls("cxx-inheritance-view",
208 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000209 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000210
211//===----------------------------------------------------------------------===//
212// Analyzer Options.
Ted Kremenek517cb512008-04-14 18:40:58 +0000213//===----------------------------------------------------------------------===//
214
215static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000216VisualizeEGDot("analyzer-viz-egraph-graphviz",
217 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000218
219static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000220VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
221 llvm::cl::desc("Display exploded graph using Ubigraph"));
222
223static llvm::cl::opt<bool>
224AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek517cb512008-04-14 18:40:58 +0000225 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000226 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000227
Ted Kremenek60feb282009-01-23 20:52:26 +0000228static llvm::cl::opt<bool>
229AnalyzerDisplayProgress("analyzer-display-progress",
230 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
231
Ted Kremenek81ea7992008-07-02 00:03:09 +0000232static llvm::cl::list<Analyses>
Ted Kremenekc3803992008-10-24 01:04:59 +0000233AnalysisList(llvm::cl::desc("SCA Checks/Analyses:"),
Ted Kremenek81ea7992008-07-02 00:03:09 +0000234llvm::cl::values(
Ted Kremenekfbda0ef2008-07-15 00:46:02 +0000235#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenek8ce61b32008-07-14 23:41:13 +0000236clEnumValN(NAME, CMDFLAG, DESC),
237#include "Analyses.def"
238clEnumValEnd));
Ted Kremenek81ea7992008-07-02 00:03:09 +0000239
Ted Kremenekc3803992008-10-24 01:04:59 +0000240static llvm::cl::opt<AnalysisStores>
241AnalysisStoreOpt(llvm::cl::desc("SCA Low-Level Options (Store):"),
242 llvm::cl::init(BasicStoreModel),
243 llvm::cl::values(
244#define ANALYSIS_STORE(NAME, CMDFLAG, DESC)\
245clEnumValN(NAME##Model, "analyzer-store-" CMDFLAG, DESC),
246#include "Analyses.def"
247clEnumValEnd));
248
Ted Kremeneka3f825e2008-11-03 23:18:07 +0000249static llvm::cl::opt<AnalysisDiagClients>
250AnalysisDiagOpt(llvm::cl::desc("SCA Output Options:"),
251 llvm::cl::init(PD_HTML),
252 llvm::cl::values(
Ted Kremenekdd485cb2009-01-23 20:06:20 +0000253#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
Ted Kremeneka3f825e2008-11-03 23:18:07 +0000254clEnumValN(PD_##NAME, "analyzer-output-" CMDFLAG, DESC),
255#include "Analyses.def"
256clEnumValEnd));
257
Ted Kremenek517cb512008-04-14 18:40:58 +0000258//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000259// Language Options
260//===----------------------------------------------------------------------===//
261
262enum LangKind {
263 langkind_unspecified,
264 langkind_c,
265 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000266 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000267 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000268 langkind_cxx,
269 langkind_cxx_cpp,
270 langkind_objc,
271 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000272 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000273 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000274 langkind_objcxx_cpp,
275 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000276};
277
278/* TODO: GCC also accepts:
279 c-header c++-header objective-c-header objective-c++-header
Chris Lattnera19689a2008-10-22 17:29:21 +0000280 assembler
Chris Lattner4b009652007-07-25 00:24:17 +0000281 ada, f77*, ratfor (!), f95, java, treelang
282 */
283static llvm::cl::opt<LangKind>
284BaseLang("x", llvm::cl::desc("Base language to compile"),
285 llvm::cl::init(langkind_unspecified),
286 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
287 clEnumValN(langkind_cxx, "c++", "C++"),
288 clEnumValN(langkind_objc, "objective-c", "Objective C"),
289 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000290 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000291 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000292 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
293 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000294 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000295 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000296 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
297 "Preprocessed Objective C"),
298 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
299 "Preprocessed Objective C++"),
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000300 clEnumValN(langkind_c_pch,"c-header",
301 "Precompiled C header"),
302 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000303 "Precompiled Objective-C header"),
304 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
305 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000306 clEnumValEnd));
307
308static llvm::cl::opt<bool>
309LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
310 llvm::cl::Hidden);
311static llvm::cl::opt<bool>
312LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
313 llvm::cl::Hidden);
314
Ted Kremenek11ad8952007-12-05 23:49:08 +0000315/// InitializeBaseLanguage - Handle the -x foo options.
316static void InitializeBaseLanguage() {
317 if (LangObjC)
318 BaseLang = langkind_objc;
319 else if (LangObjCXX)
320 BaseLang = langkind_objcxx;
321}
322
323static LangKind GetLanguage(const std::string &Filename) {
324 if (BaseLang != langkind_unspecified)
325 return BaseLang;
326
327 std::string::size_type DotPos = Filename.rfind('.');
328
329 if (DotPos == std::string::npos) {
330 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000331 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000332 }
333
Ted Kremenek11ad8952007-12-05 23:49:08 +0000334 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
335 // C header: .h
336 // C++ header: .hh or .H;
337 // assembler no preprocessing: .s
338 // assembler: .S
339 if (Ext == "c")
340 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000341 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000342 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000343 else if (Ext == "i")
344 return langkind_c_cpp;
345 else if (Ext == "ii")
346 return langkind_cxx_cpp;
347 else if (Ext == "m")
348 return langkind_objc;
349 else if (Ext == "mi")
350 return langkind_objc_cpp;
351 else if (Ext == "mm" || Ext == "M")
352 return langkind_objcxx;
353 else if (Ext == "mii")
354 return langkind_objcxx_cpp;
355 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
356 Ext == "c++" || Ext == "cp" || Ext == "cxx")
357 return langkind_cxx;
358 else
359 return langkind_c;
360}
361
362
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000363static void InitializeCOptions(LangOptions &Options) {
364 // Do nothing.
365}
366
367static void InitializeObjCOptions(LangOptions &Options) {
368 Options.ObjC1 = Options.ObjC2 = 1;
369}
370
371
372static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000373 // FIXME: implement -fpreprocessed mode.
374 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000375 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000376
377 // Test for 'PCH'.
378 switch (LK) {
379 default:
380 break;
381 case langkind_c_pch:
382 LK = langkind_c;
383 PCH = true;
384 break;
385 case langkind_objc_pch:
386 LK = langkind_objc;
387 PCH = true;
388 break;
389 case langkind_objcxx_pch:
390 LK = langkind_objcxx;
391 PCH = true;
392 break;
393 }
Chris Lattner4b009652007-07-25 00:24:17 +0000394
Ted Kremenek11ad8952007-12-05 23:49:08 +0000395 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000396 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000397 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000398 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000399 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000400 case langkind_c_cpp:
401 NoPreprocess = true;
402 // FALLTHROUGH
403 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000404 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000405 break;
406 case langkind_cxx_cpp:
407 NoPreprocess = true;
408 // FALLTHROUGH
409 case langkind_cxx:
410 Options.CPlusPlus = 1;
411 break;
412 case langkind_objc_cpp:
413 NoPreprocess = true;
414 // FALLTHROUGH
415 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000416 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000417 break;
418 case langkind_objcxx_cpp:
419 NoPreprocess = true;
420 // FALLTHROUGH
421 case langkind_objcxx:
422 Options.ObjC1 = Options.ObjC2 = 1;
423 Options.CPlusPlus = 1;
424 break;
425 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000426
427 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000428}
429
430/// LangStds - Language standards we support.
431enum LangStds {
432 lang_unspecified,
433 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000434 lang_gnu_START,
435 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000436 lang_cxx98, lang_gnucxx98,
437 lang_cxx0x, lang_gnucxx0x
438};
439
440static llvm::cl::opt<LangStds>
441LangStd("std", llvm::cl::desc("Language standard to compile for"),
442 llvm::cl::init(lang_unspecified),
443 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
444 clEnumValN(lang_c89, "c90", "ISO C 1990"),
445 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
446 clEnumValN(lang_c94, "iso9899:199409",
447 "ISO C 1990 with amendment 1"),
448 clEnumValN(lang_c99, "c99", "ISO C 1999"),
449// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
450 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
451// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
452 clEnumValN(lang_gnu89, "gnu89",
453 "ISO C 1990 with GNU extensions (default for C)"),
454 clEnumValN(lang_gnu99, "gnu99",
455 "ISO C 1999 with GNU extensions"),
456 clEnumValN(lang_gnu99, "gnu9x",
457 "ISO C 1999 with GNU extensions"),
458 clEnumValN(lang_cxx98, "c++98",
459 "ISO C++ 1998 with amendments"),
460 clEnumValN(lang_gnucxx98, "gnu++98",
461 "ISO C++ 1998 with amendments and GNU "
462 "extensions (default for C++)"),
463 clEnumValN(lang_cxx0x, "c++0x",
464 "Upcoming ISO C++ 200x with amendments"),
465 clEnumValN(lang_gnucxx0x, "gnu++0x",
466 "Upcoming ISO C++ 200x with amendments and GNU "
467 "extensions (default for C++)"),
468 clEnumValEnd));
469
470static llvm::cl::opt<bool>
471NoOperatorNames("fno-operator-names",
472 llvm::cl::desc("Do not treat C++ operator name keywords as "
473 "synonyms for operators"));
474
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000475static llvm::cl::opt<bool>
476PascalStrings("fpascal-strings",
477 llvm::cl::desc("Recognize and construct Pascal-style "
478 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000479
480static llvm::cl::opt<bool>
481MSExtensions("fms-extensions",
482 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000483 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000484
485static llvm::cl::opt<bool>
486WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000487 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000488
489static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000490NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000491 llvm::cl::desc("Disallow implicit conversions between "
492 "vectors with a different number of "
493 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000494
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000495static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000496EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
497 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
498 llvm::cl::ZeroOrMore);
499
500static llvm::cl::opt<bool>
501ObjCNonFragileABI("fobjc-nonfragile-abi",
502 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000503
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000504static llvm::cl::opt<bool>
505EmitAllDecls("femit-all-decls",
506 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000507
Daniel Dunbar91692d92008-08-11 17:36:14 +0000508// FIXME: This (and all GCC -f options) really come in -f... and
509// -fno-... forms, and additionally support automagic behavior when
510// they are not defined. For example, -fexceptions defaults to on or
511// off depending on the language. We should support this behavior in
512// some form (perhaps just add a facility for distinguishing when an
513// has its default value from when it has been set to its default
514// value).
515static llvm::cl::opt<bool>
516Exceptions("fexceptions",
517 llvm::cl::desc("Enable support for exception handling."));
518
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000519static llvm::cl::opt<bool>
520GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000521 llvm::cl::desc("Generate output compatible with the standard GNU "
522 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000523
524static llvm::cl::opt<bool>
525NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000526 llvm::cl::desc("Generate output compatible with the NeXT "
527 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000528
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000529
530
531static llvm::cl::opt<bool>
532Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
533
534static llvm::cl::opt<bool>
535Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
536
Chris Lattner4b009652007-07-25 00:24:17 +0000537// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000538// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000539static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
540 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000541 // Allow the target to set the default the langauge options as it sees fit.
542 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000543
544 if (Ansi) // "The -ansi option is equivalent to -std=c89."
545 LangStd = lang_c89;
546
Chris Lattner4b009652007-07-25 00:24:17 +0000547 if (LangStd == lang_unspecified) {
548 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000549 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000550 default: assert(0 && "Unknown base language");
551 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000552 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000553 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000554 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000555 case langkind_objc:
556 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000557 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000558 LangStd = lang_gnu99;
559 break;
560 case langkind_cxx:
561 case langkind_cxx_cpp:
562 case langkind_objcxx:
563 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000564 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000565 LangStd = lang_gnucxx98;
566 break;
567 }
568 }
569
570 switch (LangStd) {
571 default: assert(0 && "Unknown language standard!");
572
573 // Fall through from newer standards to older ones. This isn't really right.
574 // FIXME: Enable specifically the right features based on the language stds.
575 case lang_gnucxx0x:
576 case lang_cxx0x:
577 Options.CPlusPlus0x = 1;
578 // FALL THROUGH
579 case lang_gnucxx98:
580 case lang_cxx98:
581 Options.CPlusPlus = 1;
582 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000583 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000584 // FALL THROUGH.
585 case lang_gnu99:
586 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000587 Options.C99 = 1;
588 Options.HexFloats = 1;
589 // FALL THROUGH.
590 case lang_gnu89:
591 Options.BCPLComment = 1; // Only for C99/C++.
592 // FALL THROUGH.
593 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000594 Options.Digraphs = 1; // C94, C99, C++.
595 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000596 case lang_c89:
597 break;
598 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000599
600 if (Options.CPlusPlus) {
601 Options.C99 = 0;
602 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
603 }
Chris Lattner4b009652007-07-25 00:24:17 +0000604
Chris Lattner6ab935b2008-04-05 06:32:51 +0000605 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
606 Options.ImplicitInt = 1;
607 else
608 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000609
610 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
611 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000612 Options.Trigraphs = LangStd < lang_gnu_START;
613 if (Trigraphs.getPosition())
614 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000615
Chris Lattner58d5ba52008-12-05 00:10:44 +0000616 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
617 // even if they are normally on for the target. In GNU modes (e.g.
618 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000619 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
620 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000621 Options.Blocks = 0;
622
Chris Lattner4b009652007-07-25 00:24:17 +0000623 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000624 if (PascalStrings.getPosition())
625 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000626 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000627 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000628 if (NoLaxVectorConversions.getPosition())
629 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000630 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000631 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000632 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000633
Chris Lattnerddae7102008-12-04 22:54:33 +0000634 // Override the default runtime if the user requested it.
635 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000636 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000637 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000638 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000639
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000640 if (ObjCNonFragileABI)
641 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000642
643 if (EmitAllDecls)
644 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000645}
646
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000647static llvm::cl::opt<bool>
648ObjCExclusiveGC("fobjc-gc-only",
649 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000650 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000651
652static llvm::cl::opt<bool>
653ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000654 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000655
656void InitializeGCMode(LangOptions &Options) {
657 if (ObjCExclusiveGC)
658 Options.setGCMode(LangOptions::GCOnly);
659 else if (ObjCEnableGC)
660 Options.setGCMode(LangOptions::HybridGC);
661}
662
663
Chris Lattner4b009652007-07-25 00:24:17 +0000664//===----------------------------------------------------------------------===//
665// Our DiagnosticClient implementation
666//===----------------------------------------------------------------------===//
667
668// FIXME: Werror should take a list of things, -Werror=foo,bar
669static llvm::cl::opt<bool>
670WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
671
672static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000673SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
674
675static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000676WarnOnExtensions("pedantic", llvm::cl::init(false),
677 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
678
679static llvm::cl::opt<bool>
680ErrorOnExtensions("pedantic-errors",
681 llvm::cl::desc("Issue an error on uses of GCC extensions"));
682
683static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000684SuppressSystemWarnings("suppress-system-warnings",
Chris Lattner71af6d62009-02-06 04:16:41 +0000685 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000686 llvm::cl::init(true));
687
688static llvm::cl::opt<bool>
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000689WarnUnusedMacros("Wunused-macros",
Chris Lattner4b009652007-07-25 00:24:17 +0000690 llvm::cl::desc("Warn for unused macros in the main translation unit"));
691
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000692static llvm::cl::opt<bool>
693WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000694 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000695
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000696static llvm::cl::opt<bool>
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000697WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
698 llvm::cl::desc("Warn about readonly properties with writable attributes"));
699
700static llvm::cl::opt<bool>
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000701WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000702 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000703
Chris Lattnera616ee32008-01-23 17:19:46 +0000704static llvm::cl::opt<bool>
705WarnUndefMacros("Wundef",
706 llvm::cl::desc("Warn on use of undefined macros in #if's"));
707
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000708static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000709WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
710 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000711
Steve Naroffb91afca2008-10-21 10:37:50 +0000712static llvm::cl::opt<bool>
713WarnNoStrictSelectorMatch("Wno-strict-selector-match",
Chris Lattner71af6d62009-02-06 04:16:41 +0000714 llvm::cl::desc("Do not warn about duplicate methods that have the same size"
715 " and alignment"),
Steve Naroffb91afca2008-10-21 10:37:50 +0000716 llvm::cl::init(true));
717
Chris Lattner4b009652007-07-25 00:24:17 +0000718/// InitializeDiagnostics - Initialize the diagnostic object, based on the
719/// current command line option settings.
720static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000721 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000722 Diags.setWarningsAsErrors(WarningsAsErrors);
723 Diags.setWarnOnExtensions(WarnOnExtensions);
724 Diags.setErrorOnExtensions(ErrorOnExtensions);
725
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000726 // Suppress warnings in system headers unless requested not to.
727 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
728
Chris Lattner4b009652007-07-25 00:24:17 +0000729 // Silence the "macro is not used" warning unless requested.
730 if (!WarnUnusedMacros)
731 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000732
733 // Silence "floating point comparison" warnings unless requested.
734 if (!WarnFloatEqual)
735 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000736
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000737 if (!WarnPropertyReadonlyAttrs)
738 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
739 diag::MAP_IGNORE);
740
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000741 // Silence "format string is not a string literal" warnings if requested
742 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000743 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
744 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000745 if (!WarnUndefMacros)
746 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000747
Chris Lattner86a24842009-01-29 06:55:46 +0000748 if (WarnImplicitFunctionDeclaration)
749 Diags.setDiagnosticMapping(diag::ext_implicit_function_decl,
750 diag::MAP_WARNING);
751 else
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000752 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
753 diag::MAP_IGNORE);
Chris Lattner71af6d62009-02-06 04:16:41 +0000754
755
756 Diags.setDiagnosticMapping(diag::err_pp_file_not_found, diag::MAP_FATAL);
Chris Lattner4b009652007-07-25 00:24:17 +0000757}
758
759//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000760// Analysis-specific options.
761//===----------------------------------------------------------------------===//
762
763static llvm::cl::opt<std::string>
764AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000765 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000766
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000767static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000768TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000769 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000770
Ted Kremenek0118bb52008-02-18 21:21:23 +0000771//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000772// Target Triple Processing.
773//===----------------------------------------------------------------------===//
774
775static llvm::cl::opt<std::string>
776TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000777 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000778
Chris Lattnerfc457002008-03-05 01:18:20 +0000779static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000780Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000781
Chris Lattner2b168e02008-09-30 01:13:12 +0000782static llvm::cl::opt<std::string>
783MacOSVersionMin("mmacosx-version-min",
784 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
785
Chris Lattner01de9c82008-09-30 20:16:56 +0000786// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
787// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
788static void HandleMacOSVersionMin(std::string &Triple) {
789 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
790 if (DarwinDashIdx == std::string::npos) {
791 fprintf(stderr,
792 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
793 exit(1);
794 }
795 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
796
Chris Lattner01de9c82008-09-30 20:16:56 +0000797 // Remove the number.
798 Triple.resize(DarwinNumIdx);
799
800 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
801 bool MacOSVersionMinIsInvalid = false;
802 int VersionNum = 0;
803 if (MacOSVersionMin.size() < 4 ||
804 MacOSVersionMin.substr(0, 3) != "10." ||
805 !isdigit(MacOSVersionMin[3])) {
806 MacOSVersionMinIsInvalid = true;
807 } else {
808 const char *Start = MacOSVersionMin.c_str()+3;
809 char *End = 0;
810 VersionNum = (int)strtol(Start, &End, 10);
811
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000812 // The version number must be in the range 0-9.
813 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
814
Chris Lattner01de9c82008-09-30 20:16:56 +0000815 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
816 Triple += llvm::itostr(VersionNum+4);
817
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000818 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
819 // Add the period piece (.7) to the end of the triple. This gives us
820 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000821 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000822 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
823 MacOSVersionMinIsInvalid = true;
824 }
825 }
826
827 if (MacOSVersionMinIsInvalid) {
828 fprintf(stderr,
829 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
830 MacOSVersionMin.c_str());
831 exit(1);
832 }
833}
834
835/// CreateTargetTriple - Process the various options that affect the target
836/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000837static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000838 // Initialize base triple. If a -triple option has been specified, use
839 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000840 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000841 if (Triple.empty()) {
842 Triple = LLVM_HOSTTRIPLE;
843
Daniel Dunbar81caece2008-12-12 18:34:35 +0000844 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
845 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
846 Triple[2] == '8' && Triple[3] == '6')
847 Triple[1] = '3';
848
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000849 // On darwin, we want to update the version to match that of the
850 // host.
851 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
852 if (DarwinDashIdx != std::string::npos) {
853 Triple.resize(DarwinDashIdx + strlen("-darwin"));
854
Daniel Dunbar81caece2008-12-12 18:34:35 +0000855 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000856 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000857 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000858 }
859 }
Ted Kremenek40499482007-12-03 22:06:55 +0000860
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000861 // If -arch foo was specified, remove the architecture from the triple we have
862 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000863 if (!Arch.empty()) {
864 // Decompose the base triple into "arch" and suffix.
865 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000866
Chris Lattner2b168e02008-09-30 01:13:12 +0000867 if (FirstDashIdx == std::string::npos) {
868 fprintf(stderr,
869 "Malformed target triple: \"%s\" ('-' could not be found).\n",
870 Triple.c_str());
871 exit(1);
872 }
Ted Kremenek40499482007-12-03 22:06:55 +0000873
Chris Lattner2b168e02008-09-30 01:13:12 +0000874 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
875 }
876
877 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
878 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000879 if (!MacOSVersionMin.empty())
880 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000881
Chris Lattner2b168e02008-09-30 01:13:12 +0000882 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000883}
884
885//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000886// Preprocessor Initialization
887//===----------------------------------------------------------------------===//
888
889// FIXME: Preprocessor builtins to support.
890// -A... - Play with #assertions
891// -undef - Undefine all predefined macros
892
893static llvm::cl::list<std::string>
894D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
895 llvm::cl::desc("Predefine the specified macro"));
896static llvm::cl::list<std::string>
897U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
898 llvm::cl::desc("Undefine the specified macro"));
899
Chris Lattner008da782008-01-10 01:53:41 +0000900static llvm::cl::list<std::string>
901ImplicitIncludes("include", llvm::cl::value_desc("file"),
902 llvm::cl::desc("Include file before parsing"));
903
904
Chris Lattner4b009652007-07-25 00:24:17 +0000905// Append a #define line to Buf for Macro. Macro should be of the form XXX,
906// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
907// "#define XXX Y z W". To get a #define with no value, use "XXX=".
908static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
909 const char *Command = "#define ") {
910 Buf.insert(Buf.end(), Command, Command+strlen(Command));
911 if (const char *Equal = strchr(Macro, '=')) {
912 // Turn the = into ' '.
913 Buf.insert(Buf.end(), Macro, Equal);
914 Buf.push_back(' ');
915 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
916 } else {
917 // Push "macroname 1".
918 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
919 Buf.push_back(' ');
920 Buf.push_back('1');
921 }
922 Buf.push_back('\n');
923}
924
Chris Lattner008da782008-01-10 01:53:41 +0000925/// AddImplicitInclude - Add an implicit #include of the specified file to the
926/// predefines buffer.
927static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
928 const char *Inc = "#include \"";
929 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
930 Buf.insert(Buf.end(), File.begin(), File.end());
931 Buf.push_back('"');
932 Buf.push_back('\n');
933}
934
Chris Lattner4b009652007-07-25 00:24:17 +0000935
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000936/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000937/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000938///
Chris Lattner9d818a22008-04-19 23:25:44 +0000939static bool InitializePreprocessor(Preprocessor &PP,
940 bool InitializeSourceMgr,
941 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000942 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000943
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000944 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000945 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000946
947 if (InitializeSourceMgr) {
948 if (InFile != "-") {
949 const FileEntry *File = FileMgr.getFile(InFile);
950 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000951 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000952 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000953 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000954 }
955 } else {
956 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
957 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000958 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000959 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000960 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000961 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000962 }
Chris Lattner4b009652007-07-25 00:24:17 +0000963 }
Sam Bishop61a20782008-04-14 14:41:57 +0000964
Chris Lattner47b6a162008-04-19 23:09:31 +0000965 std::vector<char> PredefineBuffer;
966
Chris Lattner4b009652007-07-25 00:24:17 +0000967 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000968 unsigned d = 0, D = D_macros.size();
969 unsigned u = 0, U = U_macros.size();
970 while (d < D || u < U) {
971 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
972 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
973 else
974 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
975 }
976
Chris Lattner008da782008-01-10 01:53:41 +0000977 // FIXME: Read any files specified by -imacros.
978
979 // Add implicit #includes from -include.
980 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
981 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000982
Chris Lattner47b6a162008-04-19 23:09:31 +0000983 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000984 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000985 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000986
987 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000988 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000989}
990
991//===----------------------------------------------------------------------===//
992// Preprocessor include path information.
993//===----------------------------------------------------------------------===//
994
995// This tool exports a large number of command line options to control how the
996// preprocessor searches for header files. At root, however, the Preprocessor
997// object takes a very simple interface: a list of directories to search for
998//
999// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001000// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001001//
Chris Lattner008da782008-01-10 01:53:41 +00001002// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +00001003
1004static llvm::cl::opt<bool>
1005nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1006
1007// Various command line options. These four add directories to each chain.
1008static llvm::cl::list<std::string>
1009F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1010 llvm::cl::desc("Add directory to framework include search path"));
1011static llvm::cl::list<std::string>
1012I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1013 llvm::cl::desc("Add directory to include search path"));
1014static llvm::cl::list<std::string>
1015idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1016 llvm::cl::desc("Add directory to AFTER include search path"));
1017static llvm::cl::list<std::string>
1018iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1019 llvm::cl::desc("Add directory to QUOTE include search path"));
1020static llvm::cl::list<std::string>
1021isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1022 llvm::cl::desc("Add directory to SYSTEM include search path"));
1023
1024// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1025static llvm::cl::list<std::string>
1026iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1027 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1028static llvm::cl::list<std::string>
1029iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1030 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1031static llvm::cl::list<std::string>
1032iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1033 llvm::cl::Prefix,
1034 llvm::cl::desc("Set directory to include search path with prefix"));
1035
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001036static llvm::cl::opt<std::string>
1037isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1038 llvm::cl::desc("Set the system root directory (usually /)"));
1039
Chris Lattner4b009652007-07-25 00:24:17 +00001040// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001041
Chris Lattner4b009652007-07-25 00:24:17 +00001042/// InitializeIncludePaths - Process the -I options and set them in the
1043/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001044void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1045 FileManager &FM, const LangOptions &Lang) {
1046 InitHeaderSearch Init(Headers, Verbose, isysroot);
1047
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001048 // Handle -I... and -F... options, walking the lists in parallel.
1049 unsigned Iidx = 0, Fidx = 0;
1050 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1051 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001052 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001053 ++Iidx;
1054 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001055 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001056 ++Fidx;
1057 }
1058 }
Chris Lattner4b009652007-07-25 00:24:17 +00001059
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001060 // Consume what's left from whatever list was longer.
1061 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001062 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001063 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001064 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001065
1066 // Handle -idirafter... options.
1067 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001068 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1069 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001070
1071 // Handle -iquote... options.
1072 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001073 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001074
1075 // Handle -isystem... options.
1076 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001077 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001078
1079 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1080 // parallel, processing the values in order of occurance to get the right
1081 // prefixes.
1082 {
1083 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1084 unsigned iprefix_idx = 0;
1085 unsigned iwithprefix_idx = 0;
1086 unsigned iwithprefixbefore_idx = 0;
1087 bool iprefix_done = iprefix_vals.empty();
1088 bool iwithprefix_done = iwithprefix_vals.empty();
1089 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1090 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1091 if (!iprefix_done &&
1092 (iwithprefix_done ||
1093 iprefix_vals.getPosition(iprefix_idx) <
1094 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1095 (iwithprefixbefore_done ||
1096 iprefix_vals.getPosition(iprefix_idx) <
1097 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1098 Prefix = iprefix_vals[iprefix_idx];
1099 ++iprefix_idx;
1100 iprefix_done = iprefix_idx == iprefix_vals.size();
1101 } else if (!iwithprefix_done &&
1102 (iwithprefixbefore_done ||
1103 iwithprefix_vals.getPosition(iwithprefix_idx) <
1104 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001105 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1106 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001107 ++iwithprefix_idx;
1108 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1109 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001110 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1111 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001112 ++iwithprefixbefore_idx;
1113 iwithprefixbefore_done =
1114 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1115 }
1116 }
1117 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001118
Nico Weber770e3882008-08-22 09:25:22 +00001119 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001120
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001121 // Add the clang headers, which are relative to the clang driver.
1122 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001123 llvm::sys::Path::GetMainExecutable(Argv0,
1124 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001125 if (!MainExecutablePath.isEmpty()) {
1126 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1127 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1128 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +00001129 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1130 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001131 }
1132
Nico Weber770e3882008-08-22 09:25:22 +00001133 if (!nostdinc)
1134 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001135
1136 // Now that we have collected all of the include paths, merge them all
1137 // together and tell the preprocessor about them.
1138
Nico Weber770e3882008-08-22 09:25:22 +00001139 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001140}
1141
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001142//===----------------------------------------------------------------------===//
1143// Driver PreprocessorFactory - For lazily generating preprocessors ...
1144//===----------------------------------------------------------------------===//
1145
1146namespace {
1147class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001148 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001149 Diagnostic &Diags;
1150 const LangOptions &LangInfo;
1151 TargetInfo &Target;
1152 SourceManager &SourceMgr;
1153 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001154 bool InitializeSourceMgr;
1155
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001156public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001157 DriverPreprocessorFactory(const std::string &infile,
1158 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001159 TargetInfo &target, SourceManager &SM,
1160 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001161 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1162 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1163
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001164
1165 virtual ~DriverPreprocessorFactory() {}
1166
1167 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001168 llvm::OwningPtr<PTHManager> PTHMgr;
1169
1170 // Use PTH?
1171 if (!TokenCache.empty())
Ted Kremenek3d145552009-01-28 20:49:33 +00001172 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001173
1174 // Create the Preprocessor.
1175 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1176 SourceMgr, HeaderInfo,
1177 PTHMgr.get()));
1178
1179 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1180 // That argument is used as the IdentifierInfoLookup argument to
1181 // IdentifierTable's ctor.
1182 if (PTHMgr) {
1183 PTHMgr->setPreprocessor(PP.get());
1184 PP->setPTHManager(PTHMgr.take());
1185 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001186
Chris Lattner9d818a22008-04-19 23:25:44 +00001187 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001188 return NULL;
1189 }
1190
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001191 /// FIXME: PP can only handle one callback
1192 if (ProgAction != PrintPreprocessedInput) {
1193 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001194 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001195 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001196 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001197 return NULL;
1198 }
1199 }
1200
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001201 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001202 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001203 }
1204};
1205}
Chris Lattner4b009652007-07-25 00:24:17 +00001206
Chris Lattner4b009652007-07-25 00:24:17 +00001207//===----------------------------------------------------------------------===//
1208// Basic Parser driver
1209//===----------------------------------------------------------------------===//
1210
Chris Lattner9d818a22008-04-19 23:25:44 +00001211static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001212 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001213 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001214
1215 // Parsing the specified input file.
1216 P.ParseTranslationUnit();
1217 delete PA;
1218}
1219
1220//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001221// Code generation options
1222//===----------------------------------------------------------------------===//
1223
1224static llvm::cl::opt<bool>
1225OptSize("Os",
1226 llvm::cl::desc("Optimize for size"));
1227
1228// It might be nice to add bounds to the CommandLine library directly.
1229struct OptLevelParser : public llvm::cl::parser<unsigned> {
1230 bool parse(llvm::cl::Option &O, const char *ArgName,
1231 const std::string &Arg, unsigned &Val) {
1232 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1233 return true;
1234 // FIXME: Support -O4.
1235 if (Val > 3)
1236 return O.error(": '" + Arg + "' invalid optimization level!");
1237 return false;
1238 }
1239};
1240static llvm::cl::opt<unsigned, false, OptLevelParser>
1241OptLevel("O", llvm::cl::Prefix,
1242 llvm::cl::desc("Optimization level"),
1243 llvm::cl::init(0));
1244
1245static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001246 Opts.OptimizeSize = OptSize;
Daniel Dunbard725b162008-10-29 07:56:11 +00001247 if (OptSize) {
1248 // -Os implies -O2
1249 // FIXME: Diagnose conflicting options.
1250 Opts.OptimizationLevel = 2;
1251 } else {
1252 Opts.OptimizationLevel = OptLevel;
1253 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001254
1255 // FIXME: There are llvm-gcc options to control these selectively.
1256 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1257 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
1258 Opts.SimplifyLibCalls = 1;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001259
1260#ifdef NDEBUG
1261 Opts.VerifyModule = 0;
1262#endif
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001263}
1264
1265//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001266// Main driver
1267//===----------------------------------------------------------------------===//
1268
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001269/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1270/// action. These consumers can operate on both ASTs that are freshly
1271/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001272static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001273 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001274 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001275 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001276 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001277 switch (ProgAction) {
1278 default:
1279 return NULL;
1280
1281 case ASTPrint:
1282 return CreateASTPrinter();
1283
1284 case ASTDump:
1285 return CreateASTDumper();
1286
1287 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001288 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001289
1290 case PrintDeclContext:
1291 return CreateDeclContextPrinter();
Ted Kremenek24612ae2008-03-18 21:19:49 +00001292
1293 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001294 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001295
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001296 case InheritanceView:
1297 return CreateInheritanceViewer(InheritanceViewCls);
1298
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001299 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001300 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001301
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001302 case EmitAssembly:
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001303 case EmitLLVM:
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001304 case EmitBC: {
1305 BackendAction Act;
1306 if (ProgAction == EmitAssembly) {
1307 Act = Backend_EmitAssembly;
1308 } else if (ProgAction == EmitLLVM) {
1309 Act = Backend_EmitLL;
1310 } else {
1311 Act = Backend_EmitBC;
1312 }
1313 CompileOptions Opts;
1314 InitializeCompileOptions(Opts);
1315 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001316 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001317 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001318
Ted Kremenekbde30332007-12-19 17:25:59 +00001319 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001320 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001321 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001322
Steve Naroff44e81222008-04-14 22:03:09 +00001323 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001324 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001325
1326 case RewriteBlocks:
1327 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001328
1329 case RunAnalysis:
Ted Kremenek81ea7992008-07-02 00:03:09 +00001330 return CreateAnalysisConsumer(&AnalysisList[0],
1331 &AnalysisList[0]+AnalysisList.size(),
Ted Kremeneka3f825e2008-11-03 23:18:07 +00001332 AnalysisStoreOpt, AnalysisDiagOpt,
Ted Kremenek81ea7992008-07-02 00:03:09 +00001333 Diag, PP, PPF, LangOpts,
1334 AnalyzeSpecificFunction,
Ted Kremenekcf262252008-08-27 22:31:43 +00001335 OutputFile, VisualizeEGDot, VisualizeEGUbi,
Ted Kremenek60feb282009-01-23 20:52:26 +00001336 TrimGraph, AnalyzeAll,
1337 AnalyzerDisplayProgress);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001338 }
1339}
1340
Chris Lattner4b009652007-07-25 00:24:17 +00001341/// ProcessInputFile - Process a single input file with the specified state.
1342///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001343static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001344 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001345 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001346 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001347
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001348 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001349 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001350 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1351 PP.getFileManager(), PP.getLangOptions(),
1352 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001353
1354 if (!Consumer) {
1355 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001356 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001357 return;
1358 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001359
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001360 break;
1361
Chris Lattneraf669fb2008-10-12 05:03:36 +00001362 case DumpRawTokens: {
1363 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001364 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001365 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001366 RawLex.SetKeepWhitespaceMode(true);
1367
1368 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001369 RawLex.LexFromRawLexer(RawTok);
1370 while (RawTok.isNot(tok::eof)) {
1371 PP.DumpToken(RawTok, true);
1372 fprintf(stderr, "\n");
1373 RawLex.LexFromRawLexer(RawTok);
1374 }
1375 ClearSourceMgr = true;
1376 break;
1377 }
Chris Lattner4b009652007-07-25 00:24:17 +00001378 case DumpTokens: { // Token dump mode.
1379 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001380 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001381 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001382 do {
1383 PP.Lex(Tok);
1384 PP.DumpToken(Tok, true);
1385 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001386 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001387 ClearSourceMgr = true;
1388 break;
1389 }
1390 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1391 Token Tok;
1392 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001393 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001394 do {
1395 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001396 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001397 ClearSourceMgr = true;
1398 break;
1399 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001400
1401 case GeneratePCH: {
1402 CacheTokens(PP, OutputFile);
1403 ClearSourceMgr = true;
1404 break;
1405 }
Chris Lattner4b009652007-07-25 00:24:17 +00001406
1407 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001408 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001409 ClearSourceMgr = true;
1410 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001411
Chris Lattner4b009652007-07-25 00:24:17 +00001412 case ParseNoop: // -parse-noop
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001413 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001414 ClearSourceMgr = true;
1415 break;
1416
1417 case ParsePrintCallbacks:
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001418 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001419 ClearSourceMgr = true;
1420 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001421
Ted Kremenek6856c632007-09-26 18:39:29 +00001422 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001423 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001424 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001425
1426 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001427 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001428 ClearSourceMgr = true;
1429 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001430
1431 case RewriteTest:
1432 DoRewriteTest(PP, InFile, OutputFile);
1433 ClearSourceMgr = true;
1434 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001435 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001436
1437 if (Consumer) {
1438 TranslationUnit *TU = 0;
1439 if (DisableFree) {
1440 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1441 PP.getSourceManager(),
1442 PP.getTargetInfo(),
1443 PP.getIdentifierTable(),
1444 PP.getSelectorTable(),
1445 /* FreeMemory = */ false);
1446 TU = new TranslationUnit(*Context);
1447 }
1448 ParseAST(PP, Consumer.get(), TU, Stats);
1449 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001450
1451 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001452 if (CheckDiagnostics(PP))
1453 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001454
Chris Lattner4b009652007-07-25 00:24:17 +00001455 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001456 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001457 PP.PrintStats();
1458 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001459 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001460 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001461 fprintf(stderr, "\n");
1462 }
1463
1464 // For a multi-file compilation, some things are ok with nuking the source
1465 // manager tables, other require stable fileid/macroid's across multiple
1466 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001467 if (ClearSourceMgr)
1468 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001469
1470 if (DisableFree)
1471 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001472}
1473
Ted Kremenek80d53372007-12-12 23:41:08 +00001474static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1475 FileManager& FileMgr) {
1476
1477 if (VerifyDiagnostics) {
1478 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1479 exit (1);
1480 }
1481
1482 llvm::sys::Path Filename(InFile);
1483
1484 if (!Filename.isValid()) {
1485 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1486 exit (1);
1487 }
1488
Ted Kremenek863b01f2008-04-23 16:25:39 +00001489 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001490
1491 if (!TU) {
1492 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1493 InFile.c_str());
1494 exit (1);
1495 }
1496
Ted Kremenekab749372007-12-19 19:27:38 +00001497 // Observe that we use the source file name stored in the deserialized
1498 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001499 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001500 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001501 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001502
Ted Kremenek80d53372007-12-12 23:41:08 +00001503 if (!Consumer) {
1504 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1505 exit (1);
1506 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001507
Ted Kremenek863b01f2008-04-23 16:25:39 +00001508 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001509
Chris Lattner8d72ee02008-02-06 01:42:25 +00001510 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001511 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1512 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001513}
1514
1515
Chris Lattner4b009652007-07-25 00:24:17 +00001516static llvm::cl::list<std::string>
1517InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1518
Ted Kremenek80d53372007-12-12 23:41:08 +00001519static bool isSerializedFile(const std::string& InFile) {
1520 if (InFile.size() < 4)
1521 return false;
1522
1523 const char* s = InFile.c_str()+InFile.size()-4;
1524
1525 return s[0] == '.' &&
1526 s[1] == 'a' &&
1527 s[2] == 's' &&
1528 s[3] == 't';
1529}
1530
Chris Lattner4b009652007-07-25 00:24:17 +00001531
1532int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001533 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001534 llvm::sys::PrintStackTraceOnErrorSignal();
1535
1536 // If no input was specified, read from stdin.
1537 if (InputFilenames.empty())
1538 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001539
Chris Lattner4b009652007-07-25 00:24:17 +00001540 // Create a file manager object to provide access to and cache the filesystem.
1541 FileManager FileMgr;
1542
Ted Kremenekb240e822007-12-11 23:28:38 +00001543 // Create the diagnostic client for reporting errors or for
1544 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001545 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001546
Ted Kremenek5c341732008-08-07 17:49:57 +00001547 if (!VerifyDiagnostics) {
1548 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001549 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1550 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001551 !NoCaretDiagnostics,
1552 !NoShowLocation);
Ted Kremenek5c341732008-08-07 17:49:57 +00001553 } else {
1554 // When checking diagnostics, just buffer them up.
1555 TextDiagClient = new TextDiagnosticBuffer();
1556
1557 if (InputFilenames.size() != 1) {
1558 fprintf(stderr,
1559 "-verify only works on single input files for now.\n");
1560 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001561 }
1562 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001563
Chris Lattner4b009652007-07-25 00:24:17 +00001564 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001565 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1566 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001567 InitializeDiagnostics(Diags);
1568
Chris Lattner45a56e02007-12-05 23:24:17 +00001569 // -I- is a deprecated GCC feature, scan for it and reject it.
1570 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1571 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001572 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001573 I_dirs.erase(I_dirs.begin()+i);
1574 --i;
1575 }
1576 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001577
1578 // Get information about the target being compiled for.
1579 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001580 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1581
Chris Lattner2c77d852008-03-14 06:12:05 +00001582 if (Target == 0) {
1583 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1584 Triple.c_str());
1585 fprintf(stderr, "Please use -triple or -arch.\n");
1586 exit(1);
1587 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001588
Daniel Dunbar9c321102009-01-20 23:17:32 +00001589 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001590 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001591
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001592 llvm::OwningPtr<SourceManager> SourceMgr;
1593
Chris Lattner4b009652007-07-25 00:24:17 +00001594 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001595 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001596
Ted Kremenek5c341732008-08-07 17:49:57 +00001597 if (isSerializedFile(InFile)) {
1598 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001599 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001600 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001601 else {
1602 /// Create a SourceManager object. This tracks and owns all the file
1603 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001604 if (!SourceMgr)
1605 SourceMgr.reset(new SourceManager());
1606 else
1607 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001608
Ted Kremenek80d53372007-12-12 23:41:08 +00001609 // Initialize language options, inferring file types from input filenames.
1610 LangOptions LangInfo;
1611 InitializeBaseLanguage();
1612 LangKind LK = GetLanguage(InFile);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001613 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001614 InitializeGCMode(LangInfo);
Chris Lattnerddae7102008-12-04 22:54:33 +00001615 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001616
Ted Kremenek80d53372007-12-12 23:41:08 +00001617 // Process the -I options and set them in the HeaderInfo.
1618 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001619
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001620 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001621
Ted Kremenek80d53372007-12-12 23:41:08 +00001622 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001623 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001624 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001625
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001626 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1627
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001628 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001629 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001630
1631 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1632 // always reset to using TextDiagClient.
1633 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001634
Ted Kremenek5c341732008-08-07 17:49:57 +00001635 if (!HTMLDiag.empty()) {
1636 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1637 &PPFactory));
1638 Diags.setClient(TmpClient.get());
1639 }
1640 else
1641 Diags.setClient(TextDiagClient);
1642
1643 // Process the source file.
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001644 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1645
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001646 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001647 }
Chris Lattner4b009652007-07-25 00:24:17 +00001648 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001649
Mike Stump91d01352009-01-28 02:43:35 +00001650 if (Verbose)
1651 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1652 " hosted on " LLVM_HOSTTRIPLE "\n");
1653
Ted Kremenekec6c5252008-08-07 18:13:12 +00001654 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001655 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1656 (NumDiagnostics == 1 ? "" : "s"));
1657
1658 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001659 FileMgr.PrintStats();
1660 fprintf(stderr, "\n");
1661 }
1662
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001663 // If verifying diagnostics and we reached here, all is well.
1664 if (VerifyDiagnostics)
1665 return 0;
1666
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001667 // Managed static deconstruction. Useful for making things like
1668 // -time-passes usable.
1669 llvm::llvm_shutdown();
1670
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001671 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001672}