blob: 747f7e164d613d05842fa57b86253df64498dad1 [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 Kremenek81ea7992008-07-02 00:03:09 +0000221static llvm::cl::list<Analyses>
Ted Kremenekc3803992008-10-24 01:04:59 +0000222AnalysisList(llvm::cl::desc("SCA Checks/Analyses:"),
Ted Kremenek81ea7992008-07-02 00:03:09 +0000223llvm::cl::values(
Ted Kremenekfbda0ef2008-07-15 00:46:02 +0000224#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenek8ce61b32008-07-14 23:41:13 +0000225clEnumValN(NAME, CMDFLAG, DESC),
226#include "Analyses.def"
227clEnumValEnd));
Ted Kremenek81ea7992008-07-02 00:03:09 +0000228
Ted Kremenekc3803992008-10-24 01:04:59 +0000229static llvm::cl::opt<AnalysisStores>
230AnalysisStoreOpt(llvm::cl::desc("SCA Low-Level Options (Store):"),
231 llvm::cl::init(BasicStoreModel),
232 llvm::cl::values(
233#define ANALYSIS_STORE(NAME, CMDFLAG, DESC)\
234clEnumValN(NAME##Model, "analyzer-store-" CMDFLAG, DESC),
235#include "Analyses.def"
236clEnumValEnd));
237
Ted Kremeneka3f825e2008-11-03 23:18:07 +0000238static llvm::cl::opt<AnalysisDiagClients>
239AnalysisDiagOpt(llvm::cl::desc("SCA Output Options:"),
240 llvm::cl::init(PD_HTML),
241 llvm::cl::values(
242#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN)\
243clEnumValN(PD_##NAME, "analyzer-output-" CMDFLAG, DESC),
244#include "Analyses.def"
245clEnumValEnd));
246
Ted Kremenek517cb512008-04-14 18:40:58 +0000247//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000248// Language Options
249//===----------------------------------------------------------------------===//
250
251enum LangKind {
252 langkind_unspecified,
253 langkind_c,
254 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000255 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000256 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000257 langkind_cxx,
258 langkind_cxx_cpp,
259 langkind_objc,
260 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000261 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000262 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000263 langkind_objcxx_cpp,
264 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000265};
266
267/* TODO: GCC also accepts:
268 c-header c++-header objective-c-header objective-c++-header
Chris Lattnera19689a2008-10-22 17:29:21 +0000269 assembler
Chris Lattner4b009652007-07-25 00:24:17 +0000270 ada, f77*, ratfor (!), f95, java, treelang
271 */
272static llvm::cl::opt<LangKind>
273BaseLang("x", llvm::cl::desc("Base language to compile"),
274 llvm::cl::init(langkind_unspecified),
275 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
276 clEnumValN(langkind_cxx, "c++", "C++"),
277 clEnumValN(langkind_objc, "objective-c", "Objective C"),
278 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
279 clEnumValN(langkind_c_cpp, "c-cpp-output",
280 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000281 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
282 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000283 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000284 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000285 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
286 "Preprocessed Objective C"),
287 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
288 "Preprocessed Objective C++"),
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000289 clEnumValN(langkind_c_pch,"c-header",
290 "Precompiled C header"),
291 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000292 "Precompiled Objective-C header"),
293 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
294 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000295 clEnumValEnd));
296
297static llvm::cl::opt<bool>
298LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
299 llvm::cl::Hidden);
300static llvm::cl::opt<bool>
301LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
302 llvm::cl::Hidden);
303
Ted Kremenek11ad8952007-12-05 23:49:08 +0000304/// InitializeBaseLanguage - Handle the -x foo options.
305static void InitializeBaseLanguage() {
306 if (LangObjC)
307 BaseLang = langkind_objc;
308 else if (LangObjCXX)
309 BaseLang = langkind_objcxx;
310}
311
312static LangKind GetLanguage(const std::string &Filename) {
313 if (BaseLang != langkind_unspecified)
314 return BaseLang;
315
316 std::string::size_type DotPos = Filename.rfind('.');
317
318 if (DotPos == std::string::npos) {
319 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000320 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000321 }
322
Ted Kremenek11ad8952007-12-05 23:49:08 +0000323 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
324 // C header: .h
325 // C++ header: .hh or .H;
326 // assembler no preprocessing: .s
327 // assembler: .S
328 if (Ext == "c")
329 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000330 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000331 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000332 else if (Ext == "i")
333 return langkind_c_cpp;
334 else if (Ext == "ii")
335 return langkind_cxx_cpp;
336 else if (Ext == "m")
337 return langkind_objc;
338 else if (Ext == "mi")
339 return langkind_objc_cpp;
340 else if (Ext == "mm" || Ext == "M")
341 return langkind_objcxx;
342 else if (Ext == "mii")
343 return langkind_objcxx_cpp;
344 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
345 Ext == "c++" || Ext == "cp" || Ext == "cxx")
346 return langkind_cxx;
347 else
348 return langkind_c;
349}
350
351
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000352static void InitializeCOptions(LangOptions &Options) {
353 // Do nothing.
354}
355
356static void InitializeObjCOptions(LangOptions &Options) {
357 Options.ObjC1 = Options.ObjC2 = 1;
358}
359
360
361static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000362 // FIXME: implement -fpreprocessed mode.
363 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000364 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000365
366 // Test for 'PCH'.
367 switch (LK) {
368 default:
369 break;
370 case langkind_c_pch:
371 LK = langkind_c;
372 PCH = true;
373 break;
374 case langkind_objc_pch:
375 LK = langkind_objc;
376 PCH = true;
377 break;
378 case langkind_objcxx_pch:
379 LK = langkind_objcxx;
380 PCH = true;
381 break;
382 }
Chris Lattner4b009652007-07-25 00:24:17 +0000383
Ted Kremenek11ad8952007-12-05 23:49:08 +0000384 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000385 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000386 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000387 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000388 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000389 case langkind_c_cpp:
390 NoPreprocess = true;
391 // FALLTHROUGH
392 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000393 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000394 break;
395 case langkind_cxx_cpp:
396 NoPreprocess = true;
397 // FALLTHROUGH
398 case langkind_cxx:
399 Options.CPlusPlus = 1;
400 break;
401 case langkind_objc_cpp:
402 NoPreprocess = true;
403 // FALLTHROUGH
404 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000405 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000406 break;
407 case langkind_objcxx_cpp:
408 NoPreprocess = true;
409 // FALLTHROUGH
410 case langkind_objcxx:
411 Options.ObjC1 = Options.ObjC2 = 1;
412 Options.CPlusPlus = 1;
413 break;
414 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000415
416 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000417}
418
419/// LangStds - Language standards we support.
420enum LangStds {
421 lang_unspecified,
422 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000423 lang_gnu_START,
424 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000425 lang_cxx98, lang_gnucxx98,
426 lang_cxx0x, lang_gnucxx0x
427};
428
429static llvm::cl::opt<LangStds>
430LangStd("std", llvm::cl::desc("Language standard to compile for"),
431 llvm::cl::init(lang_unspecified),
432 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
433 clEnumValN(lang_c89, "c90", "ISO C 1990"),
434 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
435 clEnumValN(lang_c94, "iso9899:199409",
436 "ISO C 1990 with amendment 1"),
437 clEnumValN(lang_c99, "c99", "ISO C 1999"),
438// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
439 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
440// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
441 clEnumValN(lang_gnu89, "gnu89",
442 "ISO C 1990 with GNU extensions (default for C)"),
443 clEnumValN(lang_gnu99, "gnu99",
444 "ISO C 1999 with GNU extensions"),
445 clEnumValN(lang_gnu99, "gnu9x",
446 "ISO C 1999 with GNU extensions"),
447 clEnumValN(lang_cxx98, "c++98",
448 "ISO C++ 1998 with amendments"),
449 clEnumValN(lang_gnucxx98, "gnu++98",
450 "ISO C++ 1998 with amendments and GNU "
451 "extensions (default for C++)"),
452 clEnumValN(lang_cxx0x, "c++0x",
453 "Upcoming ISO C++ 200x with amendments"),
454 clEnumValN(lang_gnucxx0x, "gnu++0x",
455 "Upcoming ISO C++ 200x with amendments and GNU "
456 "extensions (default for C++)"),
457 clEnumValEnd));
458
459static llvm::cl::opt<bool>
460NoOperatorNames("fno-operator-names",
461 llvm::cl::desc("Do not treat C++ operator name keywords as "
462 "synonyms for operators"));
463
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000464static llvm::cl::opt<bool>
465PascalStrings("fpascal-strings",
466 llvm::cl::desc("Recognize and construct Pascal-style "
467 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000468
469static llvm::cl::opt<bool>
470MSExtensions("fms-extensions",
471 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000472 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000473
474static llvm::cl::opt<bool>
475WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000476 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000477
478static llvm::cl::opt<bool>
479LaxVectorConversions("flax-vector-conversions",
480 llvm::cl::desc("Allow implicit conversions between vectors"
481 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000482 "different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000483static llvm::cl::opt<bool>
484EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
485
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000486
Daniel Dunbar91692d92008-08-11 17:36:14 +0000487// FIXME: This (and all GCC -f options) really come in -f... and
488// -fno-... forms, and additionally support automagic behavior when
489// they are not defined. For example, -fexceptions defaults to on or
490// off depending on the language. We should support this behavior in
491// some form (perhaps just add a facility for distinguishing when an
492// has its default value from when it has been set to its default
493// value).
494static llvm::cl::opt<bool>
495Exceptions("fexceptions",
496 llvm::cl::desc("Enable support for exception handling."));
497
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000498static llvm::cl::opt<bool>
499GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000500 llvm::cl::desc("Generate output compatible with the standard GNU "
501 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000502
503static llvm::cl::opt<bool>
504NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000505 llvm::cl::desc("Generate output compatible with the NeXT "
506 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000507
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000508
509
510static llvm::cl::opt<bool>
511Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
512
513static llvm::cl::opt<bool>
514Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
515
Chris Lattner4b009652007-07-25 00:24:17 +0000516// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000517// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000518static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
519 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000520 // Allow the target to set the default the langauge options as it sees fit.
521 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000522
523 if (Ansi) // "The -ansi option is equivalent to -std=c89."
524 LangStd = lang_c89;
525
Chris Lattner4b009652007-07-25 00:24:17 +0000526 if (LangStd == lang_unspecified) {
527 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000528 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000529 default: assert(0 && "Unknown base language");
530 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000531 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000532 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000533 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000534 case langkind_objc:
535 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000536 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000537 LangStd = lang_gnu99;
538 break;
539 case langkind_cxx:
540 case langkind_cxx_cpp:
541 case langkind_objcxx:
542 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000543 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000544 LangStd = lang_gnucxx98;
545 break;
546 }
547 }
548
549 switch (LangStd) {
550 default: assert(0 && "Unknown language standard!");
551
552 // Fall through from newer standards to older ones. This isn't really right.
553 // FIXME: Enable specifically the right features based on the language stds.
554 case lang_gnucxx0x:
555 case lang_cxx0x:
556 Options.CPlusPlus0x = 1;
557 // FALL THROUGH
558 case lang_gnucxx98:
559 case lang_cxx98:
560 Options.CPlusPlus = 1;
561 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000562 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000563 // FALL THROUGH.
564 case lang_gnu99:
565 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000566 Options.C99 = 1;
567 Options.HexFloats = 1;
568 // FALL THROUGH.
569 case lang_gnu89:
570 Options.BCPLComment = 1; // Only for C99/C++.
571 // FALL THROUGH.
572 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000573 Options.Digraphs = 1; // C94, C99, C++.
574 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000575 case lang_c89:
576 break;
577 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000578
579 if (Options.CPlusPlus) {
580 Options.C99 = 0;
581 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
582 }
Chris Lattner4b009652007-07-25 00:24:17 +0000583
Chris Lattner6ab935b2008-04-05 06:32:51 +0000584 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
585 Options.ImplicitInt = 1;
586 else
587 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000588
589 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
590 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000591 Options.Trigraphs = LangStd < lang_gnu_START;
592 if (Trigraphs.getPosition())
593 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000594
Chris Lattner58d5ba52008-12-05 00:10:44 +0000595 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
596 // even if they are normally on for the target. In GNU modes (e.g.
597 // -std=gnu99) the default for blocks depends on the target settings.
598 if (LangStd < lang_gnu_START)
599 Options.Blocks = 0;
600
Chris Lattner4b009652007-07-25 00:24:17 +0000601 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000602 if (PascalStrings.getPosition())
603 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000604 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000605 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000606 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000607 Options.Exceptions = Exceptions;
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000608 if (EnableBlocks.getPosition())
609 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000610
Chris Lattnerddae7102008-12-04 22:54:33 +0000611 // Override the default runtime if the user requested it.
612 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000613 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000614 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000615 Options.NeXTRuntime = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000616}
617
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000618static llvm::cl::opt<bool>
619ObjCExclusiveGC("fobjc-gc-only",
620 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000621 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000622
623static llvm::cl::opt<bool>
624ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000625 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000626
627void InitializeGCMode(LangOptions &Options) {
628 if (ObjCExclusiveGC)
629 Options.setGCMode(LangOptions::GCOnly);
630 else if (ObjCEnableGC)
631 Options.setGCMode(LangOptions::HybridGC);
632}
633
634
Chris Lattner4b009652007-07-25 00:24:17 +0000635//===----------------------------------------------------------------------===//
636// Our DiagnosticClient implementation
637//===----------------------------------------------------------------------===//
638
639// FIXME: Werror should take a list of things, -Werror=foo,bar
640static llvm::cl::opt<bool>
641WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
642
643static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000644SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
645
646static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000647WarnOnExtensions("pedantic", llvm::cl::init(false),
648 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
649
650static llvm::cl::opt<bool>
651ErrorOnExtensions("pedantic-errors",
652 llvm::cl::desc("Issue an error on uses of GCC extensions"));
653
654static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000655SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar35e50942008-09-30 20:49:53 +0000656 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000657 llvm::cl::init(true));
658
659static llvm::cl::opt<bool>
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000660WarnUnusedMacros("Wunused-macros",
Chris Lattner4b009652007-07-25 00:24:17 +0000661 llvm::cl::desc("Warn for unused macros in the main translation unit"));
662
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000663static llvm::cl::opt<bool>
664WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000665 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000666
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000667static llvm::cl::opt<bool>
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000668WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
669 llvm::cl::desc("Warn about readonly properties with writable attributes"));
670
671static llvm::cl::opt<bool>
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000672WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000673 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000674
Chris Lattnera616ee32008-01-23 17:19:46 +0000675static llvm::cl::opt<bool>
676WarnUndefMacros("Wundef",
677 llvm::cl::desc("Warn on use of undefined macros in #if's"));
678
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000679static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000680WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
681 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000682
Steve Naroffb91afca2008-10-21 10:37:50 +0000683static llvm::cl::opt<bool>
684WarnNoStrictSelectorMatch("Wno-strict-selector-match",
685 llvm::cl::desc("Do not warn about duplicate methods that have the same size and alignment"),
686 llvm::cl::init(true));
687
Chris Lattner4b009652007-07-25 00:24:17 +0000688/// InitializeDiagnostics - Initialize the diagnostic object, based on the
689/// current command line option settings.
690static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000691 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000692 Diags.setWarningsAsErrors(WarningsAsErrors);
693 Diags.setWarnOnExtensions(WarnOnExtensions);
694 Diags.setErrorOnExtensions(ErrorOnExtensions);
695
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000696 // Suppress warnings in system headers unless requested not to.
697 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
698
Chris Lattner4b009652007-07-25 00:24:17 +0000699 // Silence the "macro is not used" warning unless requested.
700 if (!WarnUnusedMacros)
701 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000702
703 // Silence "floating point comparison" warnings unless requested.
704 if (!WarnFloatEqual)
705 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000706
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000707 if (!WarnPropertyReadonlyAttrs)
708 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
709 diag::MAP_IGNORE);
710
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000711 // Silence "format string is not a string literal" warnings if requested
712 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000713 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
714 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000715 if (!WarnUndefMacros)
716 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000717
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000718 if (!WarnImplicitFunctionDeclaration)
719 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
720 diag::MAP_IGNORE);
721
Chris Lattner057a2f52008-05-04 23:52:02 +0000722 // If -pedantic-errors is set, turn extensions that warn by default into
723 // errors.
724 if (ErrorOnExtensions) {
725 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
726 diag::MAP_ERROR);
727 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
728 diag::MAP_ERROR);
729 }
Chris Lattner4b009652007-07-25 00:24:17 +0000730}
731
732//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000733// Analysis-specific options.
734//===----------------------------------------------------------------------===//
735
736static llvm::cl::opt<std::string>
737AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000738 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000739
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000740static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000741TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000742 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000743
Ted Kremenek0118bb52008-02-18 21:21:23 +0000744//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000745// Target Triple Processing.
746//===----------------------------------------------------------------------===//
747
748static llvm::cl::opt<std::string>
749TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000750 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000751
Chris Lattnerfc457002008-03-05 01:18:20 +0000752static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000753Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000754
Chris Lattner2b168e02008-09-30 01:13:12 +0000755static llvm::cl::opt<std::string>
756MacOSVersionMin("mmacosx-version-min",
757 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
758
Chris Lattner01de9c82008-09-30 20:16:56 +0000759// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
760// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
761static void HandleMacOSVersionMin(std::string &Triple) {
762 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
763 if (DarwinDashIdx == std::string::npos) {
764 fprintf(stderr,
765 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
766 exit(1);
767 }
768 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
769
Chris Lattner01de9c82008-09-30 20:16:56 +0000770 // Remove the number.
771 Triple.resize(DarwinNumIdx);
772
773 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
774 bool MacOSVersionMinIsInvalid = false;
775 int VersionNum = 0;
776 if (MacOSVersionMin.size() < 4 ||
777 MacOSVersionMin.substr(0, 3) != "10." ||
778 !isdigit(MacOSVersionMin[3])) {
779 MacOSVersionMinIsInvalid = true;
780 } else {
781 const char *Start = MacOSVersionMin.c_str()+3;
782 char *End = 0;
783 VersionNum = (int)strtol(Start, &End, 10);
784
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000785 // The version number must be in the range 0-9.
786 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
787
Chris Lattner01de9c82008-09-30 20:16:56 +0000788 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
789 Triple += llvm::itostr(VersionNum+4);
790
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000791 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
792 // Add the period piece (.7) to the end of the triple. This gives us
793 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000794 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000795 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
796 MacOSVersionMinIsInvalid = true;
797 }
798 }
799
800 if (MacOSVersionMinIsInvalid) {
801 fprintf(stderr,
802 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
803 MacOSVersionMin.c_str());
804 exit(1);
805 }
806}
807
808/// CreateTargetTriple - Process the various options that affect the target
809/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000810static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000811 // Initialize base triple. If a -triple option has been specified, use
812 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000813 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000814 if (Triple.empty()) {
815 Triple = LLVM_HOSTTRIPLE;
816
Daniel Dunbar81caece2008-12-12 18:34:35 +0000817 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
818 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
819 Triple[2] == '8' && Triple[3] == '6')
820 Triple[1] = '3';
821
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000822 // On darwin, we want to update the version to match that of the
823 // host.
824 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
825 if (DarwinDashIdx != std::string::npos) {
826 Triple.resize(DarwinDashIdx + strlen("-darwin"));
827
Daniel Dunbar81caece2008-12-12 18:34:35 +0000828 // Only add the major part of the os version.
829 std::string Version = llvm::sys::osVersion();
830 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000831 }
832 }
Ted Kremenek40499482007-12-03 22:06:55 +0000833
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000834 // If -arch foo was specified, remove the architecture from the triple we have
835 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000836 if (!Arch.empty()) {
837 // Decompose the base triple into "arch" and suffix.
838 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000839
Chris Lattner2b168e02008-09-30 01:13:12 +0000840 if (FirstDashIdx == std::string::npos) {
841 fprintf(stderr,
842 "Malformed target triple: \"%s\" ('-' could not be found).\n",
843 Triple.c_str());
844 exit(1);
845 }
Ted Kremenek40499482007-12-03 22:06:55 +0000846
Chris Lattner2b168e02008-09-30 01:13:12 +0000847 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
848 }
849
850 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
851 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000852 if (!MacOSVersionMin.empty())
853 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000854
Chris Lattner2b168e02008-09-30 01:13:12 +0000855 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000856}
857
858//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000859// Preprocessor Initialization
860//===----------------------------------------------------------------------===//
861
862// FIXME: Preprocessor builtins to support.
863// -A... - Play with #assertions
864// -undef - Undefine all predefined macros
865
866static llvm::cl::list<std::string>
867D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
868 llvm::cl::desc("Predefine the specified macro"));
869static llvm::cl::list<std::string>
870U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
871 llvm::cl::desc("Undefine the specified macro"));
872
Chris Lattner008da782008-01-10 01:53:41 +0000873static llvm::cl::list<std::string>
874ImplicitIncludes("include", llvm::cl::value_desc("file"),
875 llvm::cl::desc("Include file before parsing"));
876
877
Chris Lattner4b009652007-07-25 00:24:17 +0000878// Append a #define line to Buf for Macro. Macro should be of the form XXX,
879// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
880// "#define XXX Y z W". To get a #define with no value, use "XXX=".
881static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
882 const char *Command = "#define ") {
883 Buf.insert(Buf.end(), Command, Command+strlen(Command));
884 if (const char *Equal = strchr(Macro, '=')) {
885 // Turn the = into ' '.
886 Buf.insert(Buf.end(), Macro, Equal);
887 Buf.push_back(' ');
888 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
889 } else {
890 // Push "macroname 1".
891 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
892 Buf.push_back(' ');
893 Buf.push_back('1');
894 }
895 Buf.push_back('\n');
896}
897
Chris Lattner008da782008-01-10 01:53:41 +0000898/// AddImplicitInclude - Add an implicit #include of the specified file to the
899/// predefines buffer.
900static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
901 const char *Inc = "#include \"";
902 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
903 Buf.insert(Buf.end(), File.begin(), File.end());
904 Buf.push_back('"');
905 Buf.push_back('\n');
906}
907
Chris Lattner4b009652007-07-25 00:24:17 +0000908
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000909/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000910/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000911///
Chris Lattner9d818a22008-04-19 23:25:44 +0000912static bool InitializePreprocessor(Preprocessor &PP,
913 bool InitializeSourceMgr,
914 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000915 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000916
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000917 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000918 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000919
920 if (InitializeSourceMgr) {
921 if (InFile != "-") {
922 const FileEntry *File = FileMgr.getFile(InFile);
923 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000924 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000925 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000926 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000927 }
928 } else {
929 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
930 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000931 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000932 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000933 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000934 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000935 }
Chris Lattner4b009652007-07-25 00:24:17 +0000936 }
Sam Bishop61a20782008-04-14 14:41:57 +0000937
Chris Lattner47b6a162008-04-19 23:09:31 +0000938 std::vector<char> PredefineBuffer;
939
Chris Lattner4b009652007-07-25 00:24:17 +0000940 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000941 unsigned d = 0, D = D_macros.size();
942 unsigned u = 0, U = U_macros.size();
943 while (d < D || u < U) {
944 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
945 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
946 else
947 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
948 }
949
Chris Lattner008da782008-01-10 01:53:41 +0000950 // FIXME: Read any files specified by -imacros.
951
952 // Add implicit #includes from -include.
953 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
954 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000955
Chris Lattner47b6a162008-04-19 23:09:31 +0000956 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000957 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000958 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000959
960 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000961 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000962}
963
964//===----------------------------------------------------------------------===//
965// Preprocessor include path information.
966//===----------------------------------------------------------------------===//
967
968// This tool exports a large number of command line options to control how the
969// preprocessor searches for header files. At root, however, the Preprocessor
970// object takes a very simple interface: a list of directories to search for
971//
972// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000973// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000974//
Chris Lattner008da782008-01-10 01:53:41 +0000975// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000976
977static llvm::cl::opt<bool>
978nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
979
980// Various command line options. These four add directories to each chain.
981static llvm::cl::list<std::string>
982F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
983 llvm::cl::desc("Add directory to framework include search path"));
984static llvm::cl::list<std::string>
985I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
986 llvm::cl::desc("Add directory to include search path"));
987static llvm::cl::list<std::string>
988idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
989 llvm::cl::desc("Add directory to AFTER include search path"));
990static llvm::cl::list<std::string>
991iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
992 llvm::cl::desc("Add directory to QUOTE include search path"));
993static llvm::cl::list<std::string>
994isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
995 llvm::cl::desc("Add directory to SYSTEM include search path"));
996
997// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
998static llvm::cl::list<std::string>
999iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1000 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1001static llvm::cl::list<std::string>
1002iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1003 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1004static llvm::cl::list<std::string>
1005iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1006 llvm::cl::Prefix,
1007 llvm::cl::desc("Set directory to include search path with prefix"));
1008
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001009static llvm::cl::opt<std::string>
1010isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1011 llvm::cl::desc("Set the system root directory (usually /)"));
1012
Chris Lattner4b009652007-07-25 00:24:17 +00001013// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001014
Chris Lattner4b009652007-07-25 00:24:17 +00001015/// InitializeIncludePaths - Process the -I options and set them in the
1016/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001017void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1018 FileManager &FM, const LangOptions &Lang) {
1019 InitHeaderSearch Init(Headers, Verbose, isysroot);
1020
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001021 // Handle -I... and -F... options, walking the lists in parallel.
1022 unsigned Iidx = 0, Fidx = 0;
1023 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1024 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001025 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001026 ++Iidx;
1027 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001028 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001029 ++Fidx;
1030 }
1031 }
Chris Lattner4b009652007-07-25 00:24:17 +00001032
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001033 // Consume what's left from whatever list was longer.
1034 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001035 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001036 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001037 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001038
1039 // Handle -idirafter... options.
1040 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001041 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1042 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001043
1044 // Handle -iquote... options.
1045 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001046 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001047
1048 // Handle -isystem... options.
1049 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001050 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001051
1052 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1053 // parallel, processing the values in order of occurance to get the right
1054 // prefixes.
1055 {
1056 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1057 unsigned iprefix_idx = 0;
1058 unsigned iwithprefix_idx = 0;
1059 unsigned iwithprefixbefore_idx = 0;
1060 bool iprefix_done = iprefix_vals.empty();
1061 bool iwithprefix_done = iwithprefix_vals.empty();
1062 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1063 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1064 if (!iprefix_done &&
1065 (iwithprefix_done ||
1066 iprefix_vals.getPosition(iprefix_idx) <
1067 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1068 (iwithprefixbefore_done ||
1069 iprefix_vals.getPosition(iprefix_idx) <
1070 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1071 Prefix = iprefix_vals[iprefix_idx];
1072 ++iprefix_idx;
1073 iprefix_done = iprefix_idx == iprefix_vals.size();
1074 } else if (!iwithprefix_done &&
1075 (iwithprefixbefore_done ||
1076 iwithprefix_vals.getPosition(iwithprefix_idx) <
1077 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001078 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1079 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001080 ++iwithprefix_idx;
1081 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1082 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001083 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1084 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001085 ++iwithprefixbefore_idx;
1086 iwithprefixbefore_done =
1087 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1088 }
1089 }
1090 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001091
Nico Weber770e3882008-08-22 09:25:22 +00001092 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001093
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001094 // Add the clang headers, which are relative to the clang driver.
1095 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001096 llvm::sys::Path::GetMainExecutable(Argv0,
1097 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001098 if (!MainExecutablePath.isEmpty()) {
1099 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1100 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1101 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +00001102 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1103 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001104 }
1105
Nico Weber770e3882008-08-22 09:25:22 +00001106 if (!nostdinc)
1107 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001108
1109 // Now that we have collected all of the include paths, merge them all
1110 // together and tell the preprocessor about them.
1111
Nico Weber770e3882008-08-22 09:25:22 +00001112 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001113}
1114
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001115//===----------------------------------------------------------------------===//
1116// Driver PreprocessorFactory - For lazily generating preprocessors ...
1117//===----------------------------------------------------------------------===//
1118
1119namespace {
1120class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001121 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001122 Diagnostic &Diags;
1123 const LangOptions &LangInfo;
1124 TargetInfo &Target;
1125 SourceManager &SourceMgr;
1126 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001127 bool InitializeSourceMgr;
1128
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001129public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001130 DriverPreprocessorFactory(const std::string &infile,
1131 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001132 TargetInfo &target, SourceManager &SM,
1133 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001134 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1135 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1136
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001137
1138 virtual ~DriverPreprocessorFactory() {}
1139
1140 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001141 llvm::OwningPtr<PTHManager> PTHMgr;
1142
1143 // Use PTH?
1144 if (!TokenCache.empty())
1145 PTHMgr.reset(PTHManager::Create(TokenCache));
1146
1147 // Create the Preprocessor.
1148 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1149 SourceMgr, HeaderInfo,
1150 PTHMgr.get()));
1151
1152 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1153 // That argument is used as the IdentifierInfoLookup argument to
1154 // IdentifierTable's ctor.
1155 if (PTHMgr) {
1156 PTHMgr->setPreprocessor(PP.get());
1157 PP->setPTHManager(PTHMgr.take());
1158 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001159
Chris Lattner9d818a22008-04-19 23:25:44 +00001160 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001161 return NULL;
1162 }
1163
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001164 /// FIXME: PP can only handle one callback
1165 if (ProgAction != PrintPreprocessedInput) {
1166 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001167 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001168 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001169 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001170 return NULL;
1171 }
1172 }
1173
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001174 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001175 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001176 }
1177};
1178}
Chris Lattner4b009652007-07-25 00:24:17 +00001179
Chris Lattner4b009652007-07-25 00:24:17 +00001180//===----------------------------------------------------------------------===//
1181// Basic Parser driver
1182//===----------------------------------------------------------------------===//
1183
Chris Lattner9d818a22008-04-19 23:25:44 +00001184static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001185 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001186 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001187
1188 // Parsing the specified input file.
1189 P.ParseTranslationUnit();
1190 delete PA;
1191}
1192
1193//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001194// Code generation options
1195//===----------------------------------------------------------------------===//
1196
1197static llvm::cl::opt<bool>
1198OptSize("Os",
1199 llvm::cl::desc("Optimize for size"));
1200
1201// It might be nice to add bounds to the CommandLine library directly.
1202struct OptLevelParser : public llvm::cl::parser<unsigned> {
1203 bool parse(llvm::cl::Option &O, const char *ArgName,
1204 const std::string &Arg, unsigned &Val) {
1205 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1206 return true;
1207 // FIXME: Support -O4.
1208 if (Val > 3)
1209 return O.error(": '" + Arg + "' invalid optimization level!");
1210 return false;
1211 }
1212};
1213static llvm::cl::opt<unsigned, false, OptLevelParser>
1214OptLevel("O", llvm::cl::Prefix,
1215 llvm::cl::desc("Optimization level"),
1216 llvm::cl::init(0));
1217
1218static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001219 Opts.OptimizeSize = OptSize;
Daniel Dunbard725b162008-10-29 07:56:11 +00001220 if (OptSize) {
1221 // -Os implies -O2
1222 // FIXME: Diagnose conflicting options.
1223 Opts.OptimizationLevel = 2;
1224 } else {
1225 Opts.OptimizationLevel = OptLevel;
1226 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001227
1228 // FIXME: There are llvm-gcc options to control these selectively.
1229 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1230 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
1231 Opts.SimplifyLibCalls = 1;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001232
1233#ifdef NDEBUG
1234 Opts.VerifyModule = 0;
1235#endif
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001236}
1237
1238//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001239// Main driver
1240//===----------------------------------------------------------------------===//
1241
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001242/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1243/// action. These consumers can operate on both ASTs that are freshly
1244/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001245static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001246 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001247 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001248 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001249 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001250 switch (ProgAction) {
1251 default:
1252 return NULL;
1253
1254 case ASTPrint:
1255 return CreateASTPrinter();
1256
1257 case ASTDump:
1258 return CreateASTDumper();
1259
1260 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001261 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001262
1263 case PrintDeclContext:
1264 return CreateDeclContextPrinter();
Ted Kremenek24612ae2008-03-18 21:19:49 +00001265
1266 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001267 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001268
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001269 case InheritanceView:
1270 return CreateInheritanceViewer(InheritanceViewCls);
1271
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001272 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001273 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001274
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001275 case EmitAssembly:
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001276 case EmitLLVM:
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001277 case EmitBC: {
1278 BackendAction Act;
1279 if (ProgAction == EmitAssembly) {
1280 Act = Backend_EmitAssembly;
1281 } else if (ProgAction == EmitLLVM) {
1282 Act = Backend_EmitLL;
1283 } else {
1284 Act = Backend_EmitBC;
1285 }
1286 CompileOptions Opts;
1287 InitializeCompileOptions(Opts);
1288 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001289 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001290 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001291
Ted Kremenekbde30332007-12-19 17:25:59 +00001292 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001293 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001294 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001295
Steve Naroff44e81222008-04-14 22:03:09 +00001296 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001297 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001298
1299 case RewriteBlocks:
1300 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001301
1302 case RunAnalysis:
Ted Kremenek81ea7992008-07-02 00:03:09 +00001303 return CreateAnalysisConsumer(&AnalysisList[0],
1304 &AnalysisList[0]+AnalysisList.size(),
Ted Kremeneka3f825e2008-11-03 23:18:07 +00001305 AnalysisStoreOpt, AnalysisDiagOpt,
Ted Kremenek81ea7992008-07-02 00:03:09 +00001306 Diag, PP, PPF, LangOpts,
1307 AnalyzeSpecificFunction,
Ted Kremenekcf262252008-08-27 22:31:43 +00001308 OutputFile, VisualizeEGDot, VisualizeEGUbi,
1309 TrimGraph, AnalyzeAll);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001310 }
1311}
1312
Chris Lattner4b009652007-07-25 00:24:17 +00001313/// ProcessInputFile - Process a single input file with the specified state.
1314///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001315static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001316 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001317 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001318 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001319
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001320 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001321 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001322 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1323 PP.getFileManager(), PP.getLangOptions(),
1324 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001325
1326 if (!Consumer) {
1327 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001328 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001329 return;
1330 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001331
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001332 break;
1333
Chris Lattneraf669fb2008-10-12 05:03:36 +00001334 case DumpRawTokens: {
1335 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001336 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001337 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001338 RawLex.SetKeepWhitespaceMode(true);
1339
1340 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001341 RawLex.LexFromRawLexer(RawTok);
1342 while (RawTok.isNot(tok::eof)) {
1343 PP.DumpToken(RawTok, true);
1344 fprintf(stderr, "\n");
1345 RawLex.LexFromRawLexer(RawTok);
1346 }
1347 ClearSourceMgr = true;
1348 break;
1349 }
Chris Lattner4b009652007-07-25 00:24:17 +00001350 case DumpTokens: { // Token dump mode.
1351 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001352 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001353 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001354 do {
1355 PP.Lex(Tok);
1356 PP.DumpToken(Tok, true);
1357 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001358 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001359 ClearSourceMgr = true;
1360 break;
1361 }
1362 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1363 Token Tok;
1364 // Start parsing 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);
Chris Lattner3b494152007-10-09 18:03:42 +00001368 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001369 ClearSourceMgr = true;
1370 break;
1371 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001372
1373 case GeneratePCH: {
1374 CacheTokens(PP, OutputFile);
1375 ClearSourceMgr = true;
1376 break;
1377 }
Chris Lattner4b009652007-07-25 00:24:17 +00001378
1379 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001380 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001381 ClearSourceMgr = true;
1382 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001383
Chris Lattner4b009652007-07-25 00:24:17 +00001384 case ParseNoop: // -parse-noop
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001385 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001386 ClearSourceMgr = true;
1387 break;
1388
1389 case ParsePrintCallbacks:
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001390 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001391 ClearSourceMgr = true;
1392 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001393
Ted Kremenek6856c632007-09-26 18:39:29 +00001394 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001395 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001396 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001397
1398 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001399 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001400 ClearSourceMgr = true;
1401 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001402
1403 case RewriteTest:
1404 DoRewriteTest(PP, InFile, OutputFile);
1405 ClearSourceMgr = true;
1406 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001407 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001408
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001409 if (Consumer)
Daniel Dunbar4efedde2008-10-16 16:54:18 +00001410 ParseAST(PP, Consumer.get(), Stats, !DisableFree);
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001411
1412 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001413 if (CheckDiagnostics(PP))
1414 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001415
Chris Lattner4b009652007-07-25 00:24:17 +00001416 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001417 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001418 PP.PrintStats();
1419 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001420 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001421 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001422 fprintf(stderr, "\n");
1423 }
1424
1425 // For a multi-file compilation, some things are ok with nuking the source
1426 // manager tables, other require stable fileid/macroid's across multiple
1427 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001428 if (ClearSourceMgr)
1429 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001430
1431 if (DisableFree)
1432 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001433}
1434
Ted Kremenek80d53372007-12-12 23:41:08 +00001435static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1436 FileManager& FileMgr) {
1437
1438 if (VerifyDiagnostics) {
1439 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1440 exit (1);
1441 }
1442
1443 llvm::sys::Path Filename(InFile);
1444
1445 if (!Filename.isValid()) {
1446 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1447 exit (1);
1448 }
1449
Ted Kremenek863b01f2008-04-23 16:25:39 +00001450 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001451
1452 if (!TU) {
1453 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1454 InFile.c_str());
1455 exit (1);
1456 }
1457
Ted Kremenekab749372007-12-19 19:27:38 +00001458 // Observe that we use the source file name stored in the deserialized
1459 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001460 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001461 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001462 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001463
Ted Kremenek80d53372007-12-12 23:41:08 +00001464 if (!Consumer) {
1465 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1466 exit (1);
1467 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001468
Ted Kremenek863b01f2008-04-23 16:25:39 +00001469 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001470
Chris Lattner8d72ee02008-02-06 01:42:25 +00001471 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001472 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1473 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001474}
1475
1476
Chris Lattner4b009652007-07-25 00:24:17 +00001477static llvm::cl::list<std::string>
1478InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1479
Ted Kremenek80d53372007-12-12 23:41:08 +00001480static bool isSerializedFile(const std::string& InFile) {
1481 if (InFile.size() < 4)
1482 return false;
1483
1484 const char* s = InFile.c_str()+InFile.size()-4;
1485
1486 return s[0] == '.' &&
1487 s[1] == 'a' &&
1488 s[2] == 's' &&
1489 s[3] == 't';
1490}
1491
Chris Lattner4b009652007-07-25 00:24:17 +00001492
1493int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001494 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001495 llvm::sys::PrintStackTraceOnErrorSignal();
1496
1497 // If no input was specified, read from stdin.
1498 if (InputFilenames.empty())
1499 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001500
Chris Lattner4b009652007-07-25 00:24:17 +00001501 // Create a file manager object to provide access to and cache the filesystem.
1502 FileManager FileMgr;
1503
Ted Kremenekb240e822007-12-11 23:28:38 +00001504 // Create the diagnostic client for reporting errors or for
1505 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001506 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001507
Ted Kremenek5c341732008-08-07 17:49:57 +00001508 if (!VerifyDiagnostics) {
1509 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001510 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1511 !NoShowColumn,
Ted Kremenek5c341732008-08-07 17:49:57 +00001512 !NoCaretDiagnostics);
1513 } else {
1514 // When checking diagnostics, just buffer them up.
1515 TextDiagClient = new TextDiagnosticBuffer();
1516
1517 if (InputFilenames.size() != 1) {
1518 fprintf(stderr,
1519 "-verify only works on single input files for now.\n");
1520 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001521 }
1522 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001523
Chris Lattner4b009652007-07-25 00:24:17 +00001524 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001525 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1526 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001527 InitializeDiagnostics(Diags);
1528
Chris Lattner45a56e02007-12-05 23:24:17 +00001529 // -I- is a deprecated GCC feature, scan for it and reject it.
1530 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1531 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001532 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001533 I_dirs.erase(I_dirs.begin()+i);
1534 --i;
1535 }
1536 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001537
1538 // Get information about the target being compiled for.
1539 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001540 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1541
Chris Lattner2c77d852008-03-14 06:12:05 +00001542 if (Target == 0) {
1543 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1544 Triple.c_str());
1545 fprintf(stderr, "Please use -triple or -arch.\n");
1546 exit(1);
1547 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001548
Daniel Dunbar9c321102009-01-20 23:17:32 +00001549 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001550 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001551
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001552 llvm::OwningPtr<SourceManager> SourceMgr;
1553
Chris Lattner4b009652007-07-25 00:24:17 +00001554 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001555 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001556
Ted Kremenek5c341732008-08-07 17:49:57 +00001557 if (isSerializedFile(InFile)) {
1558 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001559 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001560 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001561 else {
1562 /// Create a SourceManager object. This tracks and owns all the file
1563 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001564 if (!SourceMgr)
1565 SourceMgr.reset(new SourceManager());
1566 else
1567 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001568
Ted Kremenek80d53372007-12-12 23:41:08 +00001569 // Initialize language options, inferring file types from input filenames.
1570 LangOptions LangInfo;
1571 InitializeBaseLanguage();
1572 LangKind LK = GetLanguage(InFile);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001573 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001574 InitializeGCMode(LangInfo);
Chris Lattnerddae7102008-12-04 22:54:33 +00001575 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001576
Ted Kremenek80d53372007-12-12 23:41:08 +00001577 // Process the -I options and set them in the HeaderInfo.
1578 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001579
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001580 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001581
Ted Kremenek80d53372007-12-12 23:41:08 +00001582 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001583 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001584 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001585
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001586 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1587
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001588 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001589 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001590
1591 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1592 // always reset to using TextDiagClient.
1593 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001594
Ted Kremenek5c341732008-08-07 17:49:57 +00001595 if (!HTMLDiag.empty()) {
1596 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1597 &PPFactory));
1598 Diags.setClient(TmpClient.get());
1599 }
1600 else
1601 Diags.setClient(TextDiagClient);
1602
1603 // Process the source file.
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001604 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1605
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001606 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001607 }
Chris Lattner4b009652007-07-25 00:24:17 +00001608 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001609
Ted Kremenekec6c5252008-08-07 18:13:12 +00001610 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001611 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1612 (NumDiagnostics == 1 ? "" : "s"));
1613
1614 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001615 FileMgr.PrintStats();
1616 fprintf(stderr, "\n");
1617 }
1618
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001619 // If verifying diagnostics and we reached here, all is well.
1620 if (VerifyDiagnostics)
1621 return 0;
1622
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001623 // Managed static deconstruction. Useful for making things like
1624 // -time-passes usable.
1625 llvm::llvm_shutdown();
1626
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001627 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001628}