blob: d7c8beb1d39ffcc810d19499c5f7cacd656155af [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 Lattner1cc01712007-09-15 22:56:56 +000037#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000038#include "clang/Parse/Parser.h"
39#include "clang/Lex/HeaderSearch.h"
40#include "clang/Basic/FileManager.h"
41#include "clang/Basic/SourceManager.h"
42#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000043#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000044#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000045#include "llvm/ADT/StringExtras.h"
46#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000047#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000048#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000049#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000050#include "llvm/Support/PluginLoader.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000051#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000052#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000053#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000054using namespace clang;
55
56//===----------------------------------------------------------------------===//
57// Global options.
58//===----------------------------------------------------------------------===//
59
Daniel Dunbar4efedde2008-10-16 16:54:18 +000060static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000061
Chris Lattner4b009652007-07-25 00:24:17 +000062static llvm::cl::opt<bool>
63Verbose("v", llvm::cl::desc("Enable verbose output"));
64static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000065Stats("print-stats",
66 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000067static llvm::cl::opt<bool>
68DisableFree("disable-free",
69 llvm::cl::desc("Disable freeing of memory on exit"),
70 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000071
72enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000073 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000074 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000075 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000076 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000077 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000078 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000079 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000080 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000081 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000082 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000083 ASTPrint, // Parse ASTs and print them.
84 ASTDump, // Parse ASTs and dump them.
85 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000086 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000087 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000088 ParsePrintCallbacks, // Parse and print each callback.
89 ParseSyntaxOnly, // Parse and perform semantic analysis.
90 ParseNoop, // Parse with noop callbacks.
91 RunPreprocessorOnly, // Just lex, no output.
92 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +000093 DumpTokens, // Dump out preprocessed tokens.
94 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +000095 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +000096 GeneratePCH, // Generate precompiled header.
97 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +000098};
99
100static llvm::cl::opt<ProgActions>
101ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
102 llvm::cl::init(ParseSyntaxOnly),
103 llvm::cl::values(
104 clEnumValN(RunPreprocessorOnly, "Eonly",
105 "Just run preprocessor, no output (for timings)"),
106 clEnumValN(PrintPreprocessedInput, "E",
107 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000108 clEnumValN(DumpRawTokens, "dump-raw-tokens",
109 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000110 clEnumValN(RunAnalysis, "analyze",
111 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000112 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000113 "Run preprocessor, dump internal rep of tokens"),
114 clEnumValN(ParseNoop, "parse-noop",
115 "Run parser with noop callbacks (for timings)"),
116 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
117 "Run parser and perform semantic analysis"),
118 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
119 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000120 clEnumValN(EmitHTML, "emit-html",
121 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000122 clEnumValN(ASTPrint, "ast-print",
123 "Build ASTs and then pretty-print them"),
124 clEnumValN(ASTDump, "ast-dump",
125 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000126 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000127 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000128 clEnumValN(PrintDeclContext, "print-decl-contexts",
129 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000130 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000131 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000132 clEnumValN(EmitAssembly, "S",
133 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000134 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000135 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000136 clEnumValN(EmitBC, "emit-llvm-bc",
137 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000138 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000139 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000140 clEnumValN(RewriteTest, "rewrite-test",
141 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000142 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000143 "Rewrite ObjC into C (code rewriter example)"),
144 clEnumValN(RewriteMacros, "rewrite-macros",
145 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000146 clEnumValN(RewriteBlocks, "rewrite-blocks",
147 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000148 clEnumValEnd));
149
Ted Kremenekd01eae62007-12-19 19:47:59 +0000150
151static llvm::cl::opt<std::string>
152OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000153 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000154 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000155
156//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000157// Code Generator Options
158//===----------------------------------------------------------------------===//
159static llvm::cl::opt<bool>
160GenerateDebugInfo("g",
161 llvm::cl::desc("Generate source level debug information"));
162
Ted Kremenek57f25b22008-12-02 19:57:31 +0000163
164//===----------------------------------------------------------------------===//
165// PTH.
166//===----------------------------------------------------------------------===//
167
168static llvm::cl::opt<std::string>
169TokenCache("token-cache", llvm::cl::value_desc("path"),
170 llvm::cl::desc("Use specified token cache file"));
171
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000172//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000173// Diagnostic Options
174//===----------------------------------------------------------------------===//
175
Ted Kremenek10389cf2007-09-26 19:42:19 +0000176static llvm::cl::opt<bool>
177VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000178 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000179
Ted Kremenekfd75e312008-03-27 06:17:42 +0000180static llvm::cl::opt<std::string>
181HTMLDiag("html-diags",
182 llvm::cl::desc("Generate HTML to report diagnostics"),
183 llvm::cl::value_desc("HTML directory"));
184
Nico Weber0e13eaa2008-08-05 23:33:20 +0000185static llvm::cl::opt<bool>
186NoShowColumn("fno-show-column",
187 llvm::cl::desc("Do not include column number on diagnostics"));
188
189static llvm::cl::opt<bool>
190NoCaretDiagnostics("fno-caret-diagnostics",
191 llvm::cl::desc("Do not include source line and caret with"
192 " diagnostics"));
193
194
Chris Lattner4b009652007-07-25 00:24:17 +0000195//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000196// C++ Visualization.
197//===----------------------------------------------------------------------===//
198
199static llvm::cl::opt<std::string>
200InheritanceViewCls("cxx-inheritance-view",
201 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000202 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000203
204//===----------------------------------------------------------------------===//
205// Analyzer Options.
Ted Kremenek517cb512008-04-14 18:40:58 +0000206//===----------------------------------------------------------------------===//
207
208static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000209VisualizeEGDot("analyzer-viz-egraph-graphviz",
210 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000211
212static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000213VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
214 llvm::cl::desc("Display exploded graph using Ubigraph"));
215
216static llvm::cl::opt<bool>
217AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek517cb512008-04-14 18:40:58 +0000218 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000219 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000220
Ted Kremenek60feb282009-01-23 20:52:26 +0000221static llvm::cl::opt<bool>
222AnalyzerDisplayProgress("analyzer-display-progress",
223 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
224
Ted Kremenek81ea7992008-07-02 00:03:09 +0000225static llvm::cl::list<Analyses>
Ted Kremenekc3803992008-10-24 01:04:59 +0000226AnalysisList(llvm::cl::desc("SCA Checks/Analyses:"),
Ted Kremenek81ea7992008-07-02 00:03:09 +0000227llvm::cl::values(
Ted Kremenekfbda0ef2008-07-15 00:46:02 +0000228#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenek8ce61b32008-07-14 23:41:13 +0000229clEnumValN(NAME, CMDFLAG, DESC),
230#include "Analyses.def"
231clEnumValEnd));
Ted Kremenek81ea7992008-07-02 00:03:09 +0000232
Ted Kremenekc3803992008-10-24 01:04:59 +0000233static llvm::cl::opt<AnalysisStores>
234AnalysisStoreOpt(llvm::cl::desc("SCA Low-Level Options (Store):"),
235 llvm::cl::init(BasicStoreModel),
236 llvm::cl::values(
237#define ANALYSIS_STORE(NAME, CMDFLAG, DESC)\
238clEnumValN(NAME##Model, "analyzer-store-" CMDFLAG, DESC),
239#include "Analyses.def"
240clEnumValEnd));
241
Ted Kremeneka3f825e2008-11-03 23:18:07 +0000242static llvm::cl::opt<AnalysisDiagClients>
243AnalysisDiagOpt(llvm::cl::desc("SCA Output Options:"),
244 llvm::cl::init(PD_HTML),
245 llvm::cl::values(
Ted Kremenekdd485cb2009-01-23 20:06:20 +0000246#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
Ted Kremeneka3f825e2008-11-03 23:18:07 +0000247clEnumValN(PD_##NAME, "analyzer-output-" CMDFLAG, DESC),
248#include "Analyses.def"
249clEnumValEnd));
250
Ted Kremenek517cb512008-04-14 18:40:58 +0000251//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000252// Language Options
253//===----------------------------------------------------------------------===//
254
255enum LangKind {
256 langkind_unspecified,
257 langkind_c,
258 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000259 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000260 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000261 langkind_cxx,
262 langkind_cxx_cpp,
263 langkind_objc,
264 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000265 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000266 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000267 langkind_objcxx_cpp,
268 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000269};
270
271/* TODO: GCC also accepts:
272 c-header c++-header objective-c-header objective-c++-header
Chris Lattnera19689a2008-10-22 17:29:21 +0000273 assembler
Chris Lattner4b009652007-07-25 00:24:17 +0000274 ada, f77*, ratfor (!), f95, java, treelang
275 */
276static llvm::cl::opt<LangKind>
277BaseLang("x", llvm::cl::desc("Base language to compile"),
278 llvm::cl::init(langkind_unspecified),
279 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
280 clEnumValN(langkind_cxx, "c++", "C++"),
281 clEnumValN(langkind_objc, "objective-c", "Objective C"),
282 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
283 clEnumValN(langkind_c_cpp, "c-cpp-output",
284 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000285 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
286 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000287 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000288 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000289 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
290 "Preprocessed Objective C"),
291 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
292 "Preprocessed Objective C++"),
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000293 clEnumValN(langkind_c_pch,"c-header",
294 "Precompiled C header"),
295 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000296 "Precompiled Objective-C header"),
297 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
298 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000299 clEnumValEnd));
300
301static llvm::cl::opt<bool>
302LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
303 llvm::cl::Hidden);
304static llvm::cl::opt<bool>
305LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
306 llvm::cl::Hidden);
307
Ted Kremenek11ad8952007-12-05 23:49:08 +0000308/// InitializeBaseLanguage - Handle the -x foo options.
309static void InitializeBaseLanguage() {
310 if (LangObjC)
311 BaseLang = langkind_objc;
312 else if (LangObjCXX)
313 BaseLang = langkind_objcxx;
314}
315
316static LangKind GetLanguage(const std::string &Filename) {
317 if (BaseLang != langkind_unspecified)
318 return BaseLang;
319
320 std::string::size_type DotPos = Filename.rfind('.');
321
322 if (DotPos == std::string::npos) {
323 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000324 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000325 }
326
Ted Kremenek11ad8952007-12-05 23:49:08 +0000327 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
328 // C header: .h
329 // C++ header: .hh or .H;
330 // assembler no preprocessing: .s
331 // assembler: .S
332 if (Ext == "c")
333 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000334 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000335 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000336 else if (Ext == "i")
337 return langkind_c_cpp;
338 else if (Ext == "ii")
339 return langkind_cxx_cpp;
340 else if (Ext == "m")
341 return langkind_objc;
342 else if (Ext == "mi")
343 return langkind_objc_cpp;
344 else if (Ext == "mm" || Ext == "M")
345 return langkind_objcxx;
346 else if (Ext == "mii")
347 return langkind_objcxx_cpp;
348 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
349 Ext == "c++" || Ext == "cp" || Ext == "cxx")
350 return langkind_cxx;
351 else
352 return langkind_c;
353}
354
355
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000356static void InitializeCOptions(LangOptions &Options) {
357 // Do nothing.
358}
359
360static void InitializeObjCOptions(LangOptions &Options) {
361 Options.ObjC1 = Options.ObjC2 = 1;
362}
363
364
365static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000366 // FIXME: implement -fpreprocessed mode.
367 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000368 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000369
370 // Test for 'PCH'.
371 switch (LK) {
372 default:
373 break;
374 case langkind_c_pch:
375 LK = langkind_c;
376 PCH = true;
377 break;
378 case langkind_objc_pch:
379 LK = langkind_objc;
380 PCH = true;
381 break;
382 case langkind_objcxx_pch:
383 LK = langkind_objcxx;
384 PCH = true;
385 break;
386 }
Chris Lattner4b009652007-07-25 00:24:17 +0000387
Ted Kremenek11ad8952007-12-05 23:49:08 +0000388 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000389 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000390 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000391 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000392 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000393 case langkind_c_cpp:
394 NoPreprocess = true;
395 // FALLTHROUGH
396 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000397 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000398 break;
399 case langkind_cxx_cpp:
400 NoPreprocess = true;
401 // FALLTHROUGH
402 case langkind_cxx:
403 Options.CPlusPlus = 1;
404 break;
405 case langkind_objc_cpp:
406 NoPreprocess = true;
407 // FALLTHROUGH
408 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000409 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000410 break;
411 case langkind_objcxx_cpp:
412 NoPreprocess = true;
413 // FALLTHROUGH
414 case langkind_objcxx:
415 Options.ObjC1 = Options.ObjC2 = 1;
416 Options.CPlusPlus = 1;
417 break;
418 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000419
420 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000421}
422
423/// LangStds - Language standards we support.
424enum LangStds {
425 lang_unspecified,
426 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000427 lang_gnu_START,
428 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000429 lang_cxx98, lang_gnucxx98,
430 lang_cxx0x, lang_gnucxx0x
431};
432
433static llvm::cl::opt<LangStds>
434LangStd("std", llvm::cl::desc("Language standard to compile for"),
435 llvm::cl::init(lang_unspecified),
436 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
437 clEnumValN(lang_c89, "c90", "ISO C 1990"),
438 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
439 clEnumValN(lang_c94, "iso9899:199409",
440 "ISO C 1990 with amendment 1"),
441 clEnumValN(lang_c99, "c99", "ISO C 1999"),
442// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
443 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
444// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
445 clEnumValN(lang_gnu89, "gnu89",
446 "ISO C 1990 with GNU extensions (default for C)"),
447 clEnumValN(lang_gnu99, "gnu99",
448 "ISO C 1999 with GNU extensions"),
449 clEnumValN(lang_gnu99, "gnu9x",
450 "ISO C 1999 with GNU extensions"),
451 clEnumValN(lang_cxx98, "c++98",
452 "ISO C++ 1998 with amendments"),
453 clEnumValN(lang_gnucxx98, "gnu++98",
454 "ISO C++ 1998 with amendments and GNU "
455 "extensions (default for C++)"),
456 clEnumValN(lang_cxx0x, "c++0x",
457 "Upcoming ISO C++ 200x with amendments"),
458 clEnumValN(lang_gnucxx0x, "gnu++0x",
459 "Upcoming ISO C++ 200x with amendments and GNU "
460 "extensions (default for C++)"),
461 clEnumValEnd));
462
463static llvm::cl::opt<bool>
464NoOperatorNames("fno-operator-names",
465 llvm::cl::desc("Do not treat C++ operator name keywords as "
466 "synonyms for operators"));
467
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000468static llvm::cl::opt<bool>
469PascalStrings("fpascal-strings",
470 llvm::cl::desc("Recognize and construct Pascal-style "
471 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000472
473static llvm::cl::opt<bool>
474MSExtensions("fms-extensions",
475 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000476 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000477
478static llvm::cl::opt<bool>
479WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000480 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000481
482static llvm::cl::opt<bool>
483LaxVectorConversions("flax-vector-conversions",
484 llvm::cl::desc("Allow implicit conversions between vectors"
485 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000486 "different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000487static llvm::cl::opt<bool>
488EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
489
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000490static llvm::cl::opt<bool>
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000491ObjCNonFragileABI("fobjc-nonfragile-abi", llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000492
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000493
Daniel Dunbar91692d92008-08-11 17:36:14 +0000494// FIXME: This (and all GCC -f options) really come in -f... and
495// -fno-... forms, and additionally support automagic behavior when
496// they are not defined. For example, -fexceptions defaults to on or
497// off depending on the language. We should support this behavior in
498// some form (perhaps just add a facility for distinguishing when an
499// has its default value from when it has been set to its default
500// value).
501static llvm::cl::opt<bool>
502Exceptions("fexceptions",
503 llvm::cl::desc("Enable support for exception handling."));
504
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000505static llvm::cl::opt<bool>
506GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000507 llvm::cl::desc("Generate output compatible with the standard GNU "
508 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000509
510static llvm::cl::opt<bool>
511NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000512 llvm::cl::desc("Generate output compatible with the NeXT "
513 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000514
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000515
516
517static llvm::cl::opt<bool>
518Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
519
520static llvm::cl::opt<bool>
521Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
522
Chris Lattner4b009652007-07-25 00:24:17 +0000523// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000524// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000525static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
526 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000527 // Allow the target to set the default the langauge options as it sees fit.
528 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000529
530 if (Ansi) // "The -ansi option is equivalent to -std=c89."
531 LangStd = lang_c89;
532
Chris Lattner4b009652007-07-25 00:24:17 +0000533 if (LangStd == lang_unspecified) {
534 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000535 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000536 default: assert(0 && "Unknown base language");
537 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000538 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000539 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000540 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000541 case langkind_objc:
542 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000543 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000544 LangStd = lang_gnu99;
545 break;
546 case langkind_cxx:
547 case langkind_cxx_cpp:
548 case langkind_objcxx:
549 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000550 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000551 LangStd = lang_gnucxx98;
552 break;
553 }
554 }
555
556 switch (LangStd) {
557 default: assert(0 && "Unknown language standard!");
558
559 // Fall through from newer standards to older ones. This isn't really right.
560 // FIXME: Enable specifically the right features based on the language stds.
561 case lang_gnucxx0x:
562 case lang_cxx0x:
563 Options.CPlusPlus0x = 1;
564 // FALL THROUGH
565 case lang_gnucxx98:
566 case lang_cxx98:
567 Options.CPlusPlus = 1;
568 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000569 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000570 // FALL THROUGH.
571 case lang_gnu99:
572 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000573 Options.C99 = 1;
574 Options.HexFloats = 1;
575 // FALL THROUGH.
576 case lang_gnu89:
577 Options.BCPLComment = 1; // Only for C99/C++.
578 // FALL THROUGH.
579 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000580 Options.Digraphs = 1; // C94, C99, C++.
581 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000582 case lang_c89:
583 break;
584 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000585
586 if (Options.CPlusPlus) {
587 Options.C99 = 0;
588 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
589 }
Chris Lattner4b009652007-07-25 00:24:17 +0000590
Chris Lattner6ab935b2008-04-05 06:32:51 +0000591 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
592 Options.ImplicitInt = 1;
593 else
594 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000595
596 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
597 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000598 Options.Trigraphs = LangStd < lang_gnu_START;
599 if (Trigraphs.getPosition())
600 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000601
Chris Lattner58d5ba52008-12-05 00:10:44 +0000602 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
603 // even if they are normally on for the target. In GNU modes (e.g.
604 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000605 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
606 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000607 Options.Blocks = 0;
608
Chris Lattner4b009652007-07-25 00:24:17 +0000609 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000610 if (PascalStrings.getPosition())
611 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000612 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000613 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000614 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000615 Options.Exceptions = Exceptions;
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000616 if (EnableBlocks.getPosition())
617 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000618
Chris Lattnerddae7102008-12-04 22:54:33 +0000619 // Override the default runtime if the user requested it.
620 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000621 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000622 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000623 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000624
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000625 if (ObjCNonFragileABI)
626 Options.ObjCNonFragileABI = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000627}
628
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000629static llvm::cl::opt<bool>
630ObjCExclusiveGC("fobjc-gc-only",
631 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000632 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000633
634static llvm::cl::opt<bool>
635ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000636 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000637
638void InitializeGCMode(LangOptions &Options) {
639 if (ObjCExclusiveGC)
640 Options.setGCMode(LangOptions::GCOnly);
641 else if (ObjCEnableGC)
642 Options.setGCMode(LangOptions::HybridGC);
643}
644
645
Chris Lattner4b009652007-07-25 00:24:17 +0000646//===----------------------------------------------------------------------===//
647// Our DiagnosticClient implementation
648//===----------------------------------------------------------------------===//
649
650// FIXME: Werror should take a list of things, -Werror=foo,bar
651static llvm::cl::opt<bool>
652WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
653
654static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000655SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
656
657static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000658WarnOnExtensions("pedantic", llvm::cl::init(false),
659 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
660
661static llvm::cl::opt<bool>
662ErrorOnExtensions("pedantic-errors",
663 llvm::cl::desc("Issue an error on uses of GCC extensions"));
664
665static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000666SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar35e50942008-09-30 20:49:53 +0000667 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000668 llvm::cl::init(true));
669
670static llvm::cl::opt<bool>
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000671WarnUnusedMacros("Wunused-macros",
Chris Lattner4b009652007-07-25 00:24:17 +0000672 llvm::cl::desc("Warn for unused macros in the main translation unit"));
673
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000674static llvm::cl::opt<bool>
675WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000676 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000677
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000678static llvm::cl::opt<bool>
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000679WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
680 llvm::cl::desc("Warn about readonly properties with writable attributes"));
681
682static llvm::cl::opt<bool>
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000683WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000684 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000685
Chris Lattnera616ee32008-01-23 17:19:46 +0000686static llvm::cl::opt<bool>
687WarnUndefMacros("Wundef",
688 llvm::cl::desc("Warn on use of undefined macros in #if's"));
689
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000690static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000691WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
692 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000693
Steve Naroffb91afca2008-10-21 10:37:50 +0000694static llvm::cl::opt<bool>
695WarnNoStrictSelectorMatch("Wno-strict-selector-match",
696 llvm::cl::desc("Do not warn about duplicate methods that have the same size and alignment"),
697 llvm::cl::init(true));
698
Chris Lattner4b009652007-07-25 00:24:17 +0000699/// InitializeDiagnostics - Initialize the diagnostic object, based on the
700/// current command line option settings.
701static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000702 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000703 Diags.setWarningsAsErrors(WarningsAsErrors);
704 Diags.setWarnOnExtensions(WarnOnExtensions);
705 Diags.setErrorOnExtensions(ErrorOnExtensions);
706
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000707 // Suppress warnings in system headers unless requested not to.
708 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
709
Chris Lattner4b009652007-07-25 00:24:17 +0000710 // Silence the "macro is not used" warning unless requested.
711 if (!WarnUnusedMacros)
712 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000713
714 // Silence "floating point comparison" warnings unless requested.
715 if (!WarnFloatEqual)
716 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000717
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000718 if (!WarnPropertyReadonlyAttrs)
719 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
720 diag::MAP_IGNORE);
721
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000722 // Silence "format string is not a string literal" warnings if requested
723 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000724 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
725 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000726 if (!WarnUndefMacros)
727 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000728
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000729 if (!WarnImplicitFunctionDeclaration)
730 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
731 diag::MAP_IGNORE);
732
Chris Lattner057a2f52008-05-04 23:52:02 +0000733 // If -pedantic-errors is set, turn extensions that warn by default into
734 // errors.
735 if (ErrorOnExtensions) {
736 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
737 diag::MAP_ERROR);
738 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
739 diag::MAP_ERROR);
740 }
Chris Lattner4b009652007-07-25 00:24:17 +0000741}
742
743//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000744// Analysis-specific options.
745//===----------------------------------------------------------------------===//
746
747static llvm::cl::opt<std::string>
748AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000749 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000750
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000751static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000752TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000753 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000754
Ted Kremenek0118bb52008-02-18 21:21:23 +0000755//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000756// Target Triple Processing.
757//===----------------------------------------------------------------------===//
758
759static llvm::cl::opt<std::string>
760TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000761 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000762
Chris Lattnerfc457002008-03-05 01:18:20 +0000763static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000764Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000765
Chris Lattner2b168e02008-09-30 01:13:12 +0000766static llvm::cl::opt<std::string>
767MacOSVersionMin("mmacosx-version-min",
768 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
769
Chris Lattner01de9c82008-09-30 20:16:56 +0000770// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
771// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
772static void HandleMacOSVersionMin(std::string &Triple) {
773 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
774 if (DarwinDashIdx == std::string::npos) {
775 fprintf(stderr,
776 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
777 exit(1);
778 }
779 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
780
Chris Lattner01de9c82008-09-30 20:16:56 +0000781 // Remove the number.
782 Triple.resize(DarwinNumIdx);
783
784 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
785 bool MacOSVersionMinIsInvalid = false;
786 int VersionNum = 0;
787 if (MacOSVersionMin.size() < 4 ||
788 MacOSVersionMin.substr(0, 3) != "10." ||
789 !isdigit(MacOSVersionMin[3])) {
790 MacOSVersionMinIsInvalid = true;
791 } else {
792 const char *Start = MacOSVersionMin.c_str()+3;
793 char *End = 0;
794 VersionNum = (int)strtol(Start, &End, 10);
795
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000796 // The version number must be in the range 0-9.
797 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
798
Chris Lattner01de9c82008-09-30 20:16:56 +0000799 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
800 Triple += llvm::itostr(VersionNum+4);
801
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000802 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
803 // Add the period piece (.7) to the end of the triple. This gives us
804 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000805 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000806 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
807 MacOSVersionMinIsInvalid = true;
808 }
809 }
810
811 if (MacOSVersionMinIsInvalid) {
812 fprintf(stderr,
813 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
814 MacOSVersionMin.c_str());
815 exit(1);
816 }
817}
818
819/// CreateTargetTriple - Process the various options that affect the target
820/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000821static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000822 // Initialize base triple. If a -triple option has been specified, use
823 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000824 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000825 if (Triple.empty()) {
826 Triple = LLVM_HOSTTRIPLE;
827
Daniel Dunbar81caece2008-12-12 18:34:35 +0000828 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
829 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
830 Triple[2] == '8' && Triple[3] == '6')
831 Triple[1] = '3';
832
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000833 // On darwin, we want to update the version to match that of the
834 // host.
835 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
836 if (DarwinDashIdx != std::string::npos) {
837 Triple.resize(DarwinDashIdx + strlen("-darwin"));
838
Daniel Dunbar81caece2008-12-12 18:34:35 +0000839 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000840 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000841 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000842 }
843 }
Ted Kremenek40499482007-12-03 22:06:55 +0000844
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000845 // If -arch foo was specified, remove the architecture from the triple we have
846 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000847 if (!Arch.empty()) {
848 // Decompose the base triple into "arch" and suffix.
849 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000850
Chris Lattner2b168e02008-09-30 01:13:12 +0000851 if (FirstDashIdx == std::string::npos) {
852 fprintf(stderr,
853 "Malformed target triple: \"%s\" ('-' could not be found).\n",
854 Triple.c_str());
855 exit(1);
856 }
Ted Kremenek40499482007-12-03 22:06:55 +0000857
Chris Lattner2b168e02008-09-30 01:13:12 +0000858 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
859 }
860
861 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
862 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000863 if (!MacOSVersionMin.empty())
864 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000865
Chris Lattner2b168e02008-09-30 01:13:12 +0000866 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000867}
868
869//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000870// Preprocessor Initialization
871//===----------------------------------------------------------------------===//
872
873// FIXME: Preprocessor builtins to support.
874// -A... - Play with #assertions
875// -undef - Undefine all predefined macros
876
877static llvm::cl::list<std::string>
878D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
879 llvm::cl::desc("Predefine the specified macro"));
880static llvm::cl::list<std::string>
881U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
882 llvm::cl::desc("Undefine the specified macro"));
883
Chris Lattner008da782008-01-10 01:53:41 +0000884static llvm::cl::list<std::string>
885ImplicitIncludes("include", llvm::cl::value_desc("file"),
886 llvm::cl::desc("Include file before parsing"));
887
888
Chris Lattner4b009652007-07-25 00:24:17 +0000889// Append a #define line to Buf for Macro. Macro should be of the form XXX,
890// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
891// "#define XXX Y z W". To get a #define with no value, use "XXX=".
892static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
893 const char *Command = "#define ") {
894 Buf.insert(Buf.end(), Command, Command+strlen(Command));
895 if (const char *Equal = strchr(Macro, '=')) {
896 // Turn the = into ' '.
897 Buf.insert(Buf.end(), Macro, Equal);
898 Buf.push_back(' ');
899 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
900 } else {
901 // Push "macroname 1".
902 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
903 Buf.push_back(' ');
904 Buf.push_back('1');
905 }
906 Buf.push_back('\n');
907}
908
Chris Lattner008da782008-01-10 01:53:41 +0000909/// AddImplicitInclude - Add an implicit #include of the specified file to the
910/// predefines buffer.
911static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
912 const char *Inc = "#include \"";
913 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
914 Buf.insert(Buf.end(), File.begin(), File.end());
915 Buf.push_back('"');
916 Buf.push_back('\n');
917}
918
Chris Lattner4b009652007-07-25 00:24:17 +0000919
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000920/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000921/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000922///
Chris Lattner9d818a22008-04-19 23:25:44 +0000923static bool InitializePreprocessor(Preprocessor &PP,
924 bool InitializeSourceMgr,
925 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000926 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000927
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000928 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000929 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000930
931 if (InitializeSourceMgr) {
932 if (InFile != "-") {
933 const FileEntry *File = FileMgr.getFile(InFile);
934 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000935 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000936 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000937 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000938 }
939 } else {
940 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
941 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000942 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000943 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000944 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000945 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000946 }
Chris Lattner4b009652007-07-25 00:24:17 +0000947 }
Sam Bishop61a20782008-04-14 14:41:57 +0000948
Chris Lattner47b6a162008-04-19 23:09:31 +0000949 std::vector<char> PredefineBuffer;
950
Chris Lattner4b009652007-07-25 00:24:17 +0000951 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000952 unsigned d = 0, D = D_macros.size();
953 unsigned u = 0, U = U_macros.size();
954 while (d < D || u < U) {
955 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
956 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
957 else
958 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
959 }
960
Chris Lattner008da782008-01-10 01:53:41 +0000961 // FIXME: Read any files specified by -imacros.
962
963 // Add implicit #includes from -include.
964 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
965 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000966
Chris Lattner47b6a162008-04-19 23:09:31 +0000967 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000968 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000969 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000970
971 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000972 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000973}
974
975//===----------------------------------------------------------------------===//
976// Preprocessor include path information.
977//===----------------------------------------------------------------------===//
978
979// This tool exports a large number of command line options to control how the
980// preprocessor searches for header files. At root, however, the Preprocessor
981// object takes a very simple interface: a list of directories to search for
982//
983// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000984// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000985//
Chris Lattner008da782008-01-10 01:53:41 +0000986// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000987
988static llvm::cl::opt<bool>
989nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
990
991// Various command line options. These four add directories to each chain.
992static llvm::cl::list<std::string>
993F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
994 llvm::cl::desc("Add directory to framework include search path"));
995static llvm::cl::list<std::string>
996I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
997 llvm::cl::desc("Add directory to include search path"));
998static llvm::cl::list<std::string>
999idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1000 llvm::cl::desc("Add directory to AFTER include search path"));
1001static llvm::cl::list<std::string>
1002iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1003 llvm::cl::desc("Add directory to QUOTE include search path"));
1004static llvm::cl::list<std::string>
1005isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1006 llvm::cl::desc("Add directory to SYSTEM include search path"));
1007
1008// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1009static llvm::cl::list<std::string>
1010iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1011 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1012static llvm::cl::list<std::string>
1013iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1014 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1015static llvm::cl::list<std::string>
1016iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1017 llvm::cl::Prefix,
1018 llvm::cl::desc("Set directory to include search path with prefix"));
1019
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001020static llvm::cl::opt<std::string>
1021isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1022 llvm::cl::desc("Set the system root directory (usually /)"));
1023
Chris Lattner4b009652007-07-25 00:24:17 +00001024// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001025
Chris Lattner4b009652007-07-25 00:24:17 +00001026/// InitializeIncludePaths - Process the -I options and set them in the
1027/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001028void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1029 FileManager &FM, const LangOptions &Lang) {
1030 InitHeaderSearch Init(Headers, Verbose, isysroot);
1031
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001032 // Handle -I... and -F... options, walking the lists in parallel.
1033 unsigned Iidx = 0, Fidx = 0;
1034 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1035 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001036 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001037 ++Iidx;
1038 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001039 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001040 ++Fidx;
1041 }
1042 }
Chris Lattner4b009652007-07-25 00:24:17 +00001043
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001044 // Consume what's left from whatever list was longer.
1045 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001046 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001047 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001048 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001049
1050 // Handle -idirafter... options.
1051 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001052 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1053 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001054
1055 // Handle -iquote... options.
1056 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001057 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001058
1059 // Handle -isystem... options.
1060 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001061 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001062
1063 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1064 // parallel, processing the values in order of occurance to get the right
1065 // prefixes.
1066 {
1067 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1068 unsigned iprefix_idx = 0;
1069 unsigned iwithprefix_idx = 0;
1070 unsigned iwithprefixbefore_idx = 0;
1071 bool iprefix_done = iprefix_vals.empty();
1072 bool iwithprefix_done = iwithprefix_vals.empty();
1073 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1074 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1075 if (!iprefix_done &&
1076 (iwithprefix_done ||
1077 iprefix_vals.getPosition(iprefix_idx) <
1078 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1079 (iwithprefixbefore_done ||
1080 iprefix_vals.getPosition(iprefix_idx) <
1081 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1082 Prefix = iprefix_vals[iprefix_idx];
1083 ++iprefix_idx;
1084 iprefix_done = iprefix_idx == iprefix_vals.size();
1085 } else if (!iwithprefix_done &&
1086 (iwithprefixbefore_done ||
1087 iwithprefix_vals.getPosition(iwithprefix_idx) <
1088 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001089 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1090 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001091 ++iwithprefix_idx;
1092 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1093 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001094 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1095 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001096 ++iwithprefixbefore_idx;
1097 iwithprefixbefore_done =
1098 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1099 }
1100 }
1101 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001102
Nico Weber770e3882008-08-22 09:25:22 +00001103 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001104
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001105 // Add the clang headers, which are relative to the clang driver.
1106 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001107 llvm::sys::Path::GetMainExecutable(Argv0,
1108 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001109 if (!MainExecutablePath.isEmpty()) {
1110 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1111 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1112 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +00001113 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1114 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001115 }
1116
Nico Weber770e3882008-08-22 09:25:22 +00001117 if (!nostdinc)
1118 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001119
1120 // Now that we have collected all of the include paths, merge them all
1121 // together and tell the preprocessor about them.
1122
Nico Weber770e3882008-08-22 09:25:22 +00001123 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001124}
1125
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001126//===----------------------------------------------------------------------===//
1127// Driver PreprocessorFactory - For lazily generating preprocessors ...
1128//===----------------------------------------------------------------------===//
1129
1130namespace {
1131class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001132 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001133 Diagnostic &Diags;
1134 const LangOptions &LangInfo;
1135 TargetInfo &Target;
1136 SourceManager &SourceMgr;
1137 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001138 bool InitializeSourceMgr;
1139
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001140public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001141 DriverPreprocessorFactory(const std::string &infile,
1142 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001143 TargetInfo &target, SourceManager &SM,
1144 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001145 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1146 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1147
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001148
1149 virtual ~DriverPreprocessorFactory() {}
1150
1151 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001152 llvm::OwningPtr<PTHManager> PTHMgr;
1153
1154 // Use PTH?
1155 if (!TokenCache.empty())
1156 PTHMgr.reset(PTHManager::Create(TokenCache));
1157
1158 // Create the Preprocessor.
1159 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1160 SourceMgr, HeaderInfo,
1161 PTHMgr.get()));
1162
1163 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1164 // That argument is used as the IdentifierInfoLookup argument to
1165 // IdentifierTable's ctor.
1166 if (PTHMgr) {
1167 PTHMgr->setPreprocessor(PP.get());
1168 PP->setPTHManager(PTHMgr.take());
1169 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001170
Chris Lattner9d818a22008-04-19 23:25:44 +00001171 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001172 return NULL;
1173 }
1174
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001175 /// FIXME: PP can only handle one callback
1176 if (ProgAction != PrintPreprocessedInput) {
1177 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001178 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001179 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001180 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001181 return NULL;
1182 }
1183 }
1184
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001185 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001186 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001187 }
1188};
1189}
Chris Lattner4b009652007-07-25 00:24:17 +00001190
Chris Lattner4b009652007-07-25 00:24:17 +00001191//===----------------------------------------------------------------------===//
1192// Basic Parser driver
1193//===----------------------------------------------------------------------===//
1194
Chris Lattner9d818a22008-04-19 23:25:44 +00001195static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001196 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001197 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001198
1199 // Parsing the specified input file.
1200 P.ParseTranslationUnit();
1201 delete PA;
1202}
1203
1204//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001205// Code generation options
1206//===----------------------------------------------------------------------===//
1207
1208static llvm::cl::opt<bool>
1209OptSize("Os",
1210 llvm::cl::desc("Optimize for size"));
1211
1212// It might be nice to add bounds to the CommandLine library directly.
1213struct OptLevelParser : public llvm::cl::parser<unsigned> {
1214 bool parse(llvm::cl::Option &O, const char *ArgName,
1215 const std::string &Arg, unsigned &Val) {
1216 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1217 return true;
1218 // FIXME: Support -O4.
1219 if (Val > 3)
1220 return O.error(": '" + Arg + "' invalid optimization level!");
1221 return false;
1222 }
1223};
1224static llvm::cl::opt<unsigned, false, OptLevelParser>
1225OptLevel("O", llvm::cl::Prefix,
1226 llvm::cl::desc("Optimization level"),
1227 llvm::cl::init(0));
1228
1229static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001230 Opts.OptimizeSize = OptSize;
Daniel Dunbard725b162008-10-29 07:56:11 +00001231 if (OptSize) {
1232 // -Os implies -O2
1233 // FIXME: Diagnose conflicting options.
1234 Opts.OptimizationLevel = 2;
1235 } else {
1236 Opts.OptimizationLevel = OptLevel;
1237 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001238
1239 // FIXME: There are llvm-gcc options to control these selectively.
1240 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1241 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
1242 Opts.SimplifyLibCalls = 1;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001243
1244#ifdef NDEBUG
1245 Opts.VerifyModule = 0;
1246#endif
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001247}
1248
1249//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001250// Main driver
1251//===----------------------------------------------------------------------===//
1252
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001253/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1254/// action. These consumers can operate on both ASTs that are freshly
1255/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001256static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001257 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001258 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001259 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001260 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001261 switch (ProgAction) {
1262 default:
1263 return NULL;
1264
1265 case ASTPrint:
1266 return CreateASTPrinter();
1267
1268 case ASTDump:
1269 return CreateASTDumper();
1270
1271 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001272 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001273
1274 case PrintDeclContext:
1275 return CreateDeclContextPrinter();
Ted Kremenek24612ae2008-03-18 21:19:49 +00001276
1277 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001278 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001279
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001280 case InheritanceView:
1281 return CreateInheritanceViewer(InheritanceViewCls);
1282
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001283 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001284 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001285
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001286 case EmitAssembly:
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001287 case EmitLLVM:
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001288 case EmitBC: {
1289 BackendAction Act;
1290 if (ProgAction == EmitAssembly) {
1291 Act = Backend_EmitAssembly;
1292 } else if (ProgAction == EmitLLVM) {
1293 Act = Backend_EmitLL;
1294 } else {
1295 Act = Backend_EmitBC;
1296 }
1297 CompileOptions Opts;
1298 InitializeCompileOptions(Opts);
1299 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001300 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001301 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001302
Ted Kremenekbde30332007-12-19 17:25:59 +00001303 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001304 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001305 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001306
Steve Naroff44e81222008-04-14 22:03:09 +00001307 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001308 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001309
1310 case RewriteBlocks:
1311 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001312
1313 case RunAnalysis:
Ted Kremenek81ea7992008-07-02 00:03:09 +00001314 return CreateAnalysisConsumer(&AnalysisList[0],
1315 &AnalysisList[0]+AnalysisList.size(),
Ted Kremeneka3f825e2008-11-03 23:18:07 +00001316 AnalysisStoreOpt, AnalysisDiagOpt,
Ted Kremenek81ea7992008-07-02 00:03:09 +00001317 Diag, PP, PPF, LangOpts,
1318 AnalyzeSpecificFunction,
Ted Kremenekcf262252008-08-27 22:31:43 +00001319 OutputFile, VisualizeEGDot, VisualizeEGUbi,
Ted Kremenek60feb282009-01-23 20:52:26 +00001320 TrimGraph, AnalyzeAll,
1321 AnalyzerDisplayProgress);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001322 }
1323}
1324
Chris Lattner4b009652007-07-25 00:24:17 +00001325/// ProcessInputFile - Process a single input file with the specified state.
1326///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001327static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001328 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001329 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001330 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001331
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001332 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001333 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001334 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1335 PP.getFileManager(), PP.getLangOptions(),
1336 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001337
1338 if (!Consumer) {
1339 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001340 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001341 return;
1342 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001343
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001344 break;
1345
Chris Lattneraf669fb2008-10-12 05:03:36 +00001346 case DumpRawTokens: {
1347 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001348 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001349 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001350 RawLex.SetKeepWhitespaceMode(true);
1351
1352 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001353 RawLex.LexFromRawLexer(RawTok);
1354 while (RawTok.isNot(tok::eof)) {
1355 PP.DumpToken(RawTok, true);
1356 fprintf(stderr, "\n");
1357 RawLex.LexFromRawLexer(RawTok);
1358 }
1359 ClearSourceMgr = true;
1360 break;
1361 }
Chris Lattner4b009652007-07-25 00:24:17 +00001362 case DumpTokens: { // Token dump mode.
1363 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001364 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001365 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001366 do {
1367 PP.Lex(Tok);
1368 PP.DumpToken(Tok, true);
1369 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001370 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001371 ClearSourceMgr = true;
1372 break;
1373 }
1374 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1375 Token Tok;
1376 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001377 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001378 do {
1379 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001380 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001381 ClearSourceMgr = true;
1382 break;
1383 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001384
1385 case GeneratePCH: {
1386 CacheTokens(PP, OutputFile);
1387 ClearSourceMgr = true;
1388 break;
1389 }
Chris Lattner4b009652007-07-25 00:24:17 +00001390
1391 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001392 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001393 ClearSourceMgr = true;
1394 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001395
Chris Lattner4b009652007-07-25 00:24:17 +00001396 case ParseNoop: // -parse-noop
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001397 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001398 ClearSourceMgr = true;
1399 break;
1400
1401 case ParsePrintCallbacks:
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001402 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001403 ClearSourceMgr = true;
1404 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001405
Ted Kremenek6856c632007-09-26 18:39:29 +00001406 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001407 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001408 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001409
1410 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001411 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001412 ClearSourceMgr = true;
1413 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001414
1415 case RewriteTest:
1416 DoRewriteTest(PP, InFile, OutputFile);
1417 ClearSourceMgr = true;
1418 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001419 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001420
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001421 if (Consumer)
Daniel Dunbar4efedde2008-10-16 16:54:18 +00001422 ParseAST(PP, Consumer.get(), Stats, !DisableFree);
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001423
1424 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001425 if (CheckDiagnostics(PP))
1426 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001427
Chris Lattner4b009652007-07-25 00:24:17 +00001428 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001429 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001430 PP.PrintStats();
1431 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001432 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001433 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001434 fprintf(stderr, "\n");
1435 }
1436
1437 // For a multi-file compilation, some things are ok with nuking the source
1438 // manager tables, other require stable fileid/macroid's across multiple
1439 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001440 if (ClearSourceMgr)
1441 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001442
1443 if (DisableFree)
1444 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001445}
1446
Ted Kremenek80d53372007-12-12 23:41:08 +00001447static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1448 FileManager& FileMgr) {
1449
1450 if (VerifyDiagnostics) {
1451 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1452 exit (1);
1453 }
1454
1455 llvm::sys::Path Filename(InFile);
1456
1457 if (!Filename.isValid()) {
1458 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1459 exit (1);
1460 }
1461
Ted Kremenek863b01f2008-04-23 16:25:39 +00001462 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001463
1464 if (!TU) {
1465 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1466 InFile.c_str());
1467 exit (1);
1468 }
1469
Ted Kremenekab749372007-12-19 19:27:38 +00001470 // Observe that we use the source file name stored in the deserialized
1471 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001472 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001473 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001474 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001475
Ted Kremenek80d53372007-12-12 23:41:08 +00001476 if (!Consumer) {
1477 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1478 exit (1);
1479 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001480
Ted Kremenek863b01f2008-04-23 16:25:39 +00001481 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001482
Chris Lattner8d72ee02008-02-06 01:42:25 +00001483 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001484 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1485 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001486}
1487
1488
Chris Lattner4b009652007-07-25 00:24:17 +00001489static llvm::cl::list<std::string>
1490InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1491
Ted Kremenek80d53372007-12-12 23:41:08 +00001492static bool isSerializedFile(const std::string& InFile) {
1493 if (InFile.size() < 4)
1494 return false;
1495
1496 const char* s = InFile.c_str()+InFile.size()-4;
1497
1498 return s[0] == '.' &&
1499 s[1] == 'a' &&
1500 s[2] == 's' &&
1501 s[3] == 't';
1502}
1503
Chris Lattner4b009652007-07-25 00:24:17 +00001504
1505int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001506 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001507 llvm::sys::PrintStackTraceOnErrorSignal();
1508
1509 // If no input was specified, read from stdin.
1510 if (InputFilenames.empty())
1511 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001512
Chris Lattner4b009652007-07-25 00:24:17 +00001513 // Create a file manager object to provide access to and cache the filesystem.
1514 FileManager FileMgr;
1515
Ted Kremenekb240e822007-12-11 23:28:38 +00001516 // Create the diagnostic client for reporting errors or for
1517 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001518 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001519
Ted Kremenek5c341732008-08-07 17:49:57 +00001520 if (!VerifyDiagnostics) {
1521 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001522 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1523 !NoShowColumn,
Ted Kremenek5c341732008-08-07 17:49:57 +00001524 !NoCaretDiagnostics);
1525 } else {
1526 // When checking diagnostics, just buffer them up.
1527 TextDiagClient = new TextDiagnosticBuffer();
1528
1529 if (InputFilenames.size() != 1) {
1530 fprintf(stderr,
1531 "-verify only works on single input files for now.\n");
1532 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001533 }
1534 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001535
Chris Lattner4b009652007-07-25 00:24:17 +00001536 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001537 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1538 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001539 InitializeDiagnostics(Diags);
1540
Chris Lattner45a56e02007-12-05 23:24:17 +00001541 // -I- is a deprecated GCC feature, scan for it and reject it.
1542 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1543 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001544 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001545 I_dirs.erase(I_dirs.begin()+i);
1546 --i;
1547 }
1548 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001549
1550 // Get information about the target being compiled for.
1551 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001552 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1553
Chris Lattner2c77d852008-03-14 06:12:05 +00001554 if (Target == 0) {
1555 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1556 Triple.c_str());
1557 fprintf(stderr, "Please use -triple or -arch.\n");
1558 exit(1);
1559 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001560
Daniel Dunbar9c321102009-01-20 23:17:32 +00001561 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001562 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001563
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001564 llvm::OwningPtr<SourceManager> SourceMgr;
1565
Chris Lattner4b009652007-07-25 00:24:17 +00001566 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001567 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001568
Ted Kremenek5c341732008-08-07 17:49:57 +00001569 if (isSerializedFile(InFile)) {
1570 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001571 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001572 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001573 else {
1574 /// Create a SourceManager object. This tracks and owns all the file
1575 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001576 if (!SourceMgr)
1577 SourceMgr.reset(new SourceManager());
1578 else
1579 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001580
Ted Kremenek80d53372007-12-12 23:41:08 +00001581 // Initialize language options, inferring file types from input filenames.
1582 LangOptions LangInfo;
1583 InitializeBaseLanguage();
1584 LangKind LK = GetLanguage(InFile);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001585 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001586 InitializeGCMode(LangInfo);
Chris Lattnerddae7102008-12-04 22:54:33 +00001587 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001588
Ted Kremenek80d53372007-12-12 23:41:08 +00001589 // Process the -I options and set them in the HeaderInfo.
1590 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001591
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001592 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001593
Ted Kremenek80d53372007-12-12 23:41:08 +00001594 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001595 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001596 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001597
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001598 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1599
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001600 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001601 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001602
1603 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1604 // always reset to using TextDiagClient.
1605 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001606
Ted Kremenek5c341732008-08-07 17:49:57 +00001607 if (!HTMLDiag.empty()) {
1608 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1609 &PPFactory));
1610 Diags.setClient(TmpClient.get());
1611 }
1612 else
1613 Diags.setClient(TextDiagClient);
1614
1615 // Process the source file.
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001616 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1617
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001618 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001619 }
Chris Lattner4b009652007-07-25 00:24:17 +00001620 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001621
Ted Kremenekec6c5252008-08-07 18:13:12 +00001622 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001623 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1624 (NumDiagnostics == 1 ? "" : "s"));
1625
1626 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001627 FileMgr.PrintStats();
1628 fprintf(stderr, "\n");
1629 }
1630
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001631 // If verifying diagnostics and we reached here, all is well.
1632 if (VerifyDiagnostics)
1633 return 0;
1634
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001635 // Managed static deconstruction. Useful for making things like
1636 // -time-passes usable.
1637 llvm::llvm_shutdown();
1638
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001639 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001640}