blob: 1fdfde4318e27786b61cc28e9a00260996ebd1e6 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000027#include "clang/Driver/CompileOptions.h"
Ted Kremenek21b88b72008-11-03 22:31:48 +000028#include "clang/Driver/PathDiagnosticClients.h"
Nico Weber770e3882008-08-22 09:25:22 +000029#include "clang/Driver/InitHeaderSearch.h"
Nico Weber0e13eaa2008-08-05 23:33:20 +000030#include "clang/Driver/TextDiagnosticBuffer.h"
31#include "clang/Driver/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000032#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000033#include "clang/AST/Decl.h"
Ted Kremenekac881932007-12-18 21:34:28 +000034#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000039#include "clang/Parse/Parser.h"
40#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000041#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000042#include "clang/Basic/FileManager.h"
43#include "clang/Basic/SourceManager.h"
44#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000045#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000046#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000049#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000050#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000051#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000052#include "llvm/Support/PluginLoader.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000053#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000054#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000055#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000056using namespace clang;
57
58//===----------------------------------------------------------------------===//
59// Global options.
60//===----------------------------------------------------------------------===//
61
Daniel Dunbar4efedde2008-10-16 16:54:18 +000062static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000063
Chris Lattner4b009652007-07-25 00:24:17 +000064static llvm::cl::opt<bool>
65Verbose("v", llvm::cl::desc("Enable verbose output"));
66static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000067Stats("print-stats",
68 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000069static llvm::cl::opt<bool>
70DisableFree("disable-free",
71 llvm::cl::desc("Disable freeing of memory on exit"),
72 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000073
74enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000075 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000076 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000077 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000078 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000079 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000080 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000081 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000082 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000083 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000084 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000085 ASTPrint, // Parse ASTs and print them.
86 ASTDump, // Parse ASTs and dump them.
87 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000088 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000089 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000090 ParsePrintCallbacks, // Parse and print each callback.
91 ParseSyntaxOnly, // Parse and perform semantic analysis.
92 ParseNoop, // Parse with noop callbacks.
93 RunPreprocessorOnly, // Just lex, no output.
94 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +000095 DumpTokens, // Dump out preprocessed tokens.
96 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +000097 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +000098 GeneratePCH, // Generate precompiled header.
99 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000100};
101
102static llvm::cl::opt<ProgActions>
103ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
104 llvm::cl::init(ParseSyntaxOnly),
105 llvm::cl::values(
106 clEnumValN(RunPreprocessorOnly, "Eonly",
107 "Just run preprocessor, no output (for timings)"),
108 clEnumValN(PrintPreprocessedInput, "E",
109 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000110 clEnumValN(DumpRawTokens, "dump-raw-tokens",
111 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000112 clEnumValN(RunAnalysis, "analyze",
113 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000114 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000115 "Run preprocessor, dump internal rep of tokens"),
116 clEnumValN(ParseNoop, "parse-noop",
117 "Run parser with noop callbacks (for timings)"),
118 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
119 "Run parser and perform semantic analysis"),
120 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
121 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000122 clEnumValN(EmitHTML, "emit-html",
123 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000124 clEnumValN(ASTPrint, "ast-print",
125 "Build ASTs and then pretty-print them"),
126 clEnumValN(ASTDump, "ast-dump",
127 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000128 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000129 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000130 clEnumValN(PrintDeclContext, "print-decl-contexts",
131 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000132 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000133 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000134 clEnumValN(EmitAssembly, "S",
135 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000136 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000137 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000138 clEnumValN(EmitBC, "emit-llvm-bc",
139 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000140 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000141 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000142 clEnumValN(RewriteTest, "rewrite-test",
143 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000144 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000145 "Rewrite ObjC into C (code rewriter example)"),
146 clEnumValN(RewriteMacros, "rewrite-macros",
147 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000148 clEnumValN(RewriteBlocks, "rewrite-blocks",
149 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000150 clEnumValEnd));
151
Ted Kremenekd01eae62007-12-19 19:47:59 +0000152
153static llvm::cl::opt<std::string>
154OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000155 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000156 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000157
158//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000159// Code Generator Options
160//===----------------------------------------------------------------------===//
161static llvm::cl::opt<bool>
162GenerateDebugInfo("g",
163 llvm::cl::desc("Generate source level debug information"));
164
Ted Kremenek57f25b22008-12-02 19:57:31 +0000165
166//===----------------------------------------------------------------------===//
167// PTH.
168//===----------------------------------------------------------------------===//
169
170static llvm::cl::opt<std::string>
171TokenCache("token-cache", llvm::cl::value_desc("path"),
172 llvm::cl::desc("Use specified token cache file"));
173
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000174//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000175// Diagnostic Options
176//===----------------------------------------------------------------------===//
177
Ted Kremenek10389cf2007-09-26 19:42:19 +0000178static llvm::cl::opt<bool>
179VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000180 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000181
Ted Kremenekfd75e312008-03-27 06:17:42 +0000182static llvm::cl::opt<std::string>
183HTMLDiag("html-diags",
184 llvm::cl::desc("Generate HTML to report diagnostics"),
185 llvm::cl::value_desc("HTML directory"));
186
Nico Weber0e13eaa2008-08-05 23:33:20 +0000187static llvm::cl::opt<bool>
188NoShowColumn("fno-show-column",
189 llvm::cl::desc("Do not include column number on diagnostics"));
190
191static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000192NoShowLocation("fno-show-source-location",
193 llvm::cl::desc("Do not include source location information with"
194 " diagnostics"));
195
196static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000197NoCaretDiagnostics("fno-caret-diagnostics",
198 llvm::cl::desc("Do not include source line and caret with"
199 " diagnostics"));
200
201
Chris Lattner4b009652007-07-25 00:24:17 +0000202//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000203// C++ Visualization.
204//===----------------------------------------------------------------------===//
205
206static llvm::cl::opt<std::string>
207InheritanceViewCls("cxx-inheritance-view",
208 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000209 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000210
211//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000212// Builtin Options
213//===----------------------------------------------------------------------===//
214static llvm::cl::opt<bool>
215Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000216 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000217 "freestanding environment"));
218
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000219static llvm::cl::opt<bool>
220MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000221 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000222 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000223
Douglas Gregor23d23262009-02-14 20:49:29 +0000224//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000225// Language Options
226//===----------------------------------------------------------------------===//
227
228enum LangKind {
229 langkind_unspecified,
230 langkind_c,
231 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000232 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000233 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000234 langkind_cxx,
235 langkind_cxx_cpp,
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000236 langkind_cxx_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000237 langkind_objc,
238 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000239 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000240 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000241 langkind_objcxx_cpp,
242 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000243};
244
245/* TODO: GCC also accepts:
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000246 assembler, ada, f77*, ratfor (!), f95, java, treelang
Chris Lattner4b009652007-07-25 00:24:17 +0000247 */
248static llvm::cl::opt<LangKind>
249BaseLang("x", llvm::cl::desc("Base language to compile"),
250 llvm::cl::init(langkind_unspecified),
251 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
252 clEnumValN(langkind_cxx, "c++", "C++"),
253 clEnumValN(langkind_objc, "objective-c", "Objective C"),
254 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000255 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000256 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000257 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
258 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000259 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000260 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000261 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
262 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000263 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000264 "Preprocessed Objective C++"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000265 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000266 "Precompiled C header"),
267 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000268 "Precompiled Objective-C header"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000269 clEnumValN(langkind_cxx_pch, "c++-header",
270 "Precompiled C++ header"),
Ted Kremenekceacc812009-01-09 00:38:08 +0000271 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
272 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000273 clEnumValEnd));
274
275static llvm::cl::opt<bool>
276LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
277 llvm::cl::Hidden);
278static llvm::cl::opt<bool>
279LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
280 llvm::cl::Hidden);
281
Ted Kremenek11ad8952007-12-05 23:49:08 +0000282/// InitializeBaseLanguage - Handle the -x foo options.
283static void InitializeBaseLanguage() {
284 if (LangObjC)
285 BaseLang = langkind_objc;
286 else if (LangObjCXX)
287 BaseLang = langkind_objcxx;
288}
289
290static LangKind GetLanguage(const std::string &Filename) {
291 if (BaseLang != langkind_unspecified)
292 return BaseLang;
293
294 std::string::size_type DotPos = Filename.rfind('.');
295
296 if (DotPos == std::string::npos) {
297 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000298 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000299 }
300
Ted Kremenek11ad8952007-12-05 23:49:08 +0000301 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
302 // C header: .h
303 // C++ header: .hh or .H;
304 // assembler no preprocessing: .s
305 // assembler: .S
306 if (Ext == "c")
307 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000308 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000309 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000310 else if (Ext == "i")
311 return langkind_c_cpp;
312 else if (Ext == "ii")
313 return langkind_cxx_cpp;
314 else if (Ext == "m")
315 return langkind_objc;
316 else if (Ext == "mi")
317 return langkind_objc_cpp;
318 else if (Ext == "mm" || Ext == "M")
319 return langkind_objcxx;
320 else if (Ext == "mii")
321 return langkind_objcxx_cpp;
322 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
323 Ext == "c++" || Ext == "cp" || Ext == "cxx")
324 return langkind_cxx;
325 else
326 return langkind_c;
327}
328
329
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000330static void InitializeCOptions(LangOptions &Options) {
331 // Do nothing.
332}
333
334static void InitializeObjCOptions(LangOptions &Options) {
335 Options.ObjC1 = Options.ObjC2 = 1;
336}
337
338
339static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000340 // FIXME: implement -fpreprocessed mode.
341 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000342 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000343
344 // Test for 'PCH'.
345 switch (LK) {
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000346 default:
347 break;
348 case langkind_c_pch:
349 LK = langkind_c;
350 PCH = true;
351 break;
352 case langkind_objc_pch:
353 LK = langkind_objc;
354 PCH = true;
355 break;
356 case langkind_cxx_pch:
357 LK = langkind_cxx;
358 PCH = true;
359 break;
360 case langkind_objcxx_pch:
361 LK = langkind_objcxx;
362 PCH = true;
363 break;
Ted Kremenekceacc812009-01-09 00:38:08 +0000364 }
Chris Lattner4b009652007-07-25 00:24:17 +0000365
Ted Kremenek11ad8952007-12-05 23:49:08 +0000366 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000367 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000368 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000369 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000370 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000371 case langkind_c_cpp:
372 NoPreprocess = true;
373 // FALLTHROUGH
374 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000375 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000376 break;
377 case langkind_cxx_cpp:
378 NoPreprocess = true;
379 // FALLTHROUGH
380 case langkind_cxx:
381 Options.CPlusPlus = 1;
382 break;
383 case langkind_objc_cpp:
384 NoPreprocess = true;
385 // FALLTHROUGH
386 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000387 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000388 break;
389 case langkind_objcxx_cpp:
390 NoPreprocess = true;
391 // FALLTHROUGH
392 case langkind_objcxx:
393 Options.ObjC1 = Options.ObjC2 = 1;
394 Options.CPlusPlus = 1;
395 break;
396 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000397
398 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000399}
400
401/// LangStds - Language standards we support.
402enum LangStds {
403 lang_unspecified,
404 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000405 lang_gnu_START,
406 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000407 lang_cxx98, lang_gnucxx98,
408 lang_cxx0x, lang_gnucxx0x
409};
410
411static llvm::cl::opt<LangStds>
412LangStd("std", llvm::cl::desc("Language standard to compile for"),
413 llvm::cl::init(lang_unspecified),
414 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
415 clEnumValN(lang_c89, "c90", "ISO C 1990"),
416 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
417 clEnumValN(lang_c94, "iso9899:199409",
418 "ISO C 1990 with amendment 1"),
419 clEnumValN(lang_c99, "c99", "ISO C 1999"),
420// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
421 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
422// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
423 clEnumValN(lang_gnu89, "gnu89",
424 "ISO C 1990 with GNU extensions (default for C)"),
425 clEnumValN(lang_gnu99, "gnu99",
426 "ISO C 1999 with GNU extensions"),
427 clEnumValN(lang_gnu99, "gnu9x",
428 "ISO C 1999 with GNU extensions"),
429 clEnumValN(lang_cxx98, "c++98",
430 "ISO C++ 1998 with amendments"),
431 clEnumValN(lang_gnucxx98, "gnu++98",
432 "ISO C++ 1998 with amendments and GNU "
433 "extensions (default for C++)"),
434 clEnumValN(lang_cxx0x, "c++0x",
435 "Upcoming ISO C++ 200x with amendments"),
436 clEnumValN(lang_gnucxx0x, "gnu++0x",
437 "Upcoming ISO C++ 200x with amendments and GNU "
438 "extensions (default for C++)"),
439 clEnumValEnd));
440
441static llvm::cl::opt<bool>
442NoOperatorNames("fno-operator-names",
443 llvm::cl::desc("Do not treat C++ operator name keywords as "
444 "synonyms for operators"));
445
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000446static llvm::cl::opt<bool>
447PascalStrings("fpascal-strings",
448 llvm::cl::desc("Recognize and construct Pascal-style "
449 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000450
451static llvm::cl::opt<bool>
452MSExtensions("fms-extensions",
453 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000454 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000455
456static llvm::cl::opt<bool>
457WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000458 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000459
460static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000461NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000462 llvm::cl::desc("Disallow implicit conversions between "
463 "vectors with a different number of "
464 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000465
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000466static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000467EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
468 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
469 llvm::cl::ZeroOrMore);
470
471static llvm::cl::opt<bool>
472ObjCNonFragileABI("fobjc-nonfragile-abi",
473 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000474
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000475static llvm::cl::opt<bool>
476EmitAllDecls("femit-all-decls",
477 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000478
Daniel Dunbar91692d92008-08-11 17:36:14 +0000479// FIXME: This (and all GCC -f options) really come in -f... and
480// -fno-... forms, and additionally support automagic behavior when
481// they are not defined. For example, -fexceptions defaults to on or
482// off depending on the language. We should support this behavior in
483// some form (perhaps just add a facility for distinguishing when an
484// has its default value from when it has been set to its default
485// value).
486static llvm::cl::opt<bool>
487Exceptions("fexceptions",
488 llvm::cl::desc("Enable support for exception handling."));
489
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000490static llvm::cl::opt<bool>
491GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000492 llvm::cl::desc("Generate output compatible with the standard GNU "
493 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000494
495static llvm::cl::opt<bool>
496NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000497 llvm::cl::desc("Generate output compatible with the NeXT "
498 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000499
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000500
501
502static llvm::cl::opt<bool>
503Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
504
505static llvm::cl::opt<bool>
506Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
507
Chris Lattner4b009652007-07-25 00:24:17 +0000508// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000509// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000510static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
511 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000512 // Allow the target to set the default the langauge options as it sees fit.
513 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000514
515 if (Ansi) // "The -ansi option is equivalent to -std=c89."
516 LangStd = lang_c89;
517
Chris Lattner4b009652007-07-25 00:24:17 +0000518 if (LangStd == lang_unspecified) {
519 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000520 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000521 default: assert(0 && "Unknown base language");
522 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000523 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000524 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000525 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000526 case langkind_objc:
527 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000528 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000529 LangStd = lang_gnu99;
530 break;
531 case langkind_cxx:
532 case langkind_cxx_cpp:
533 case langkind_objcxx:
534 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000535 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000536 LangStd = lang_gnucxx98;
537 break;
538 }
539 }
540
541 switch (LangStd) {
542 default: assert(0 && "Unknown language standard!");
543
544 // Fall through from newer standards to older ones. This isn't really right.
545 // FIXME: Enable specifically the right features based on the language stds.
546 case lang_gnucxx0x:
547 case lang_cxx0x:
548 Options.CPlusPlus0x = 1;
549 // FALL THROUGH
550 case lang_gnucxx98:
551 case lang_cxx98:
552 Options.CPlusPlus = 1;
553 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000554 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000555 // FALL THROUGH.
556 case lang_gnu99:
557 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000558 Options.C99 = 1;
559 Options.HexFloats = 1;
560 // FALL THROUGH.
561 case lang_gnu89:
562 Options.BCPLComment = 1; // Only for C99/C++.
563 // FALL THROUGH.
564 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000565 Options.Digraphs = 1; // C94, C99, C++.
566 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000567 case lang_c89:
568 break;
569 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000570
571 if (Options.CPlusPlus) {
572 Options.C99 = 0;
573 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
574 }
Chris Lattner4b009652007-07-25 00:24:17 +0000575
Chris Lattner6ab935b2008-04-05 06:32:51 +0000576 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
577 Options.ImplicitInt = 1;
578 else
579 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000580
581 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
582 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000583 Options.Trigraphs = LangStd < lang_gnu_START;
584 if (Trigraphs.getPosition())
585 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000586
Chris Lattner58d5ba52008-12-05 00:10:44 +0000587 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
588 // even if they are normally on for the target. In GNU modes (e.g.
589 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000590 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
591 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000592 Options.Blocks = 0;
593
Chris Lattner4b009652007-07-25 00:24:17 +0000594 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000595 if (PascalStrings.getPosition())
596 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000597 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000598 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000599 if (NoLaxVectorConversions.getPosition())
600 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000601 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000602 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000603 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000604
Douglas Gregor23d23262009-02-14 20:49:29 +0000605 if (Freestanding)
606 Options.Freestanding = 1;
607
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000608 Options.MathErrno = MathErrno;
609
Chris Lattnerddae7102008-12-04 22:54:33 +0000610 // Override the default runtime if the user requested it.
611 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000612 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000613 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000614 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000615
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000616 if (ObjCNonFragileABI)
617 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000618
619 if (EmitAllDecls)
620 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000621}
622
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000623static llvm::cl::opt<bool>
624ObjCExclusiveGC("fobjc-gc-only",
625 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000626 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000627
628static llvm::cl::opt<bool>
629ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000630 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000631
632void InitializeGCMode(LangOptions &Options) {
633 if (ObjCExclusiveGC)
634 Options.setGCMode(LangOptions::GCOnly);
635 else if (ObjCEnableGC)
636 Options.setGCMode(LangOptions::HybridGC);
637}
638
Chris Lattner4b009652007-07-25 00:24:17 +0000639//===----------------------------------------------------------------------===//
640// Our DiagnosticClient implementation
641//===----------------------------------------------------------------------===//
642
643// FIXME: Werror should take a list of things, -Werror=foo,bar
644static llvm::cl::opt<bool>
645WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
646
647static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000648SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
649
650static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000651WarnOnExtensions("pedantic", llvm::cl::init(false),
652 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
653
654static llvm::cl::opt<bool>
655ErrorOnExtensions("pedantic-errors",
656 llvm::cl::desc("Issue an error on uses of GCC extensions"));
657
658static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000659SuppressSystemWarnings("suppress-system-warnings",
Chris Lattner71af6d62009-02-06 04:16:41 +0000660 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000661 llvm::cl::init(true));
662
663static llvm::cl::opt<bool>
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000664WarnUnusedMacros("Wunused-macros",
Chris Lattner4b009652007-07-25 00:24:17 +0000665 llvm::cl::desc("Warn for unused macros in the main translation unit"));
666
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000667static llvm::cl::opt<bool>
668WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000669 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000670
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000671static llvm::cl::opt<bool>
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000672WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
673 llvm::cl::desc("Warn about readonly properties with writable attributes"));
674
675static llvm::cl::opt<bool>
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000676WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000677 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000678
Chris Lattnera616ee32008-01-23 17:19:46 +0000679static llvm::cl::opt<bool>
680WarnUndefMacros("Wundef",
681 llvm::cl::desc("Warn on use of undefined macros in #if's"));
682
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000683static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000684WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
685 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000686
Steve Naroffb91afca2008-10-21 10:37:50 +0000687static llvm::cl::opt<bool>
688WarnNoStrictSelectorMatch("Wno-strict-selector-match",
Chris Lattner71af6d62009-02-06 04:16:41 +0000689 llvm::cl::desc("Do not warn about duplicate methods that have the same size"
690 " and alignment"),
Steve Naroffb91afca2008-10-21 10:37:50 +0000691 llvm::cl::init(true));
692
Chris Lattner4b009652007-07-25 00:24:17 +0000693/// InitializeDiagnostics - Initialize the diagnostic object, based on the
694/// current command line option settings.
695static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000696 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000697 Diags.setWarningsAsErrors(WarningsAsErrors);
698 Diags.setWarnOnExtensions(WarnOnExtensions);
699 Diags.setErrorOnExtensions(ErrorOnExtensions);
700
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000701 // Suppress warnings in system headers unless requested not to.
702 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
703
Chris Lattner4b009652007-07-25 00:24:17 +0000704 // Silence the "macro is not used" warning unless requested.
705 if (!WarnUnusedMacros)
706 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000707
708 // Silence "floating point comparison" warnings unless requested.
709 if (!WarnFloatEqual)
710 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000711
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000712 if (!WarnPropertyReadonlyAttrs)
713 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
714 diag::MAP_IGNORE);
715
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000716 // Silence "format string is not a string literal" warnings if requested
717 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000718 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
719 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000720 if (!WarnUndefMacros)
721 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000722
Chris Lattner86a24842009-01-29 06:55:46 +0000723 if (WarnImplicitFunctionDeclaration)
724 Diags.setDiagnosticMapping(diag::ext_implicit_function_decl,
725 diag::MAP_WARNING);
726 else
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000727 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
728 diag::MAP_IGNORE);
Chris Lattner71af6d62009-02-06 04:16:41 +0000729
730
731 Diags.setDiagnosticMapping(diag::err_pp_file_not_found, diag::MAP_FATAL);
Chris Lattner4b009652007-07-25 00:24:17 +0000732}
733
734//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000735// Target Triple Processing.
736//===----------------------------------------------------------------------===//
737
738static llvm::cl::opt<std::string>
739TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000740 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000741
Chris Lattnerfc457002008-03-05 01:18:20 +0000742static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000743Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000744
Chris Lattner2b168e02008-09-30 01:13:12 +0000745static llvm::cl::opt<std::string>
746MacOSVersionMin("mmacosx-version-min",
747 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
748
Chris Lattner01de9c82008-09-30 20:16:56 +0000749// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
750// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
751static void HandleMacOSVersionMin(std::string &Triple) {
752 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
753 if (DarwinDashIdx == std::string::npos) {
754 fprintf(stderr,
755 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
756 exit(1);
757 }
758 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
759
Chris Lattner01de9c82008-09-30 20:16:56 +0000760 // Remove the number.
761 Triple.resize(DarwinNumIdx);
762
763 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
764 bool MacOSVersionMinIsInvalid = false;
765 int VersionNum = 0;
766 if (MacOSVersionMin.size() < 4 ||
767 MacOSVersionMin.substr(0, 3) != "10." ||
768 !isdigit(MacOSVersionMin[3])) {
769 MacOSVersionMinIsInvalid = true;
770 } else {
771 const char *Start = MacOSVersionMin.c_str()+3;
772 char *End = 0;
773 VersionNum = (int)strtol(Start, &End, 10);
774
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000775 // The version number must be in the range 0-9.
776 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
777
Chris Lattner01de9c82008-09-30 20:16:56 +0000778 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
779 Triple += llvm::itostr(VersionNum+4);
780
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000781 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
782 // Add the period piece (.7) to the end of the triple. This gives us
783 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000784 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000785 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
786 MacOSVersionMinIsInvalid = true;
787 }
788 }
789
790 if (MacOSVersionMinIsInvalid) {
791 fprintf(stderr,
792 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
793 MacOSVersionMin.c_str());
794 exit(1);
795 }
796}
797
798/// CreateTargetTriple - Process the various options that affect the target
799/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000800static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000801 // Initialize base triple. If a -triple option has been specified, use
802 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000803 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000804 if (Triple.empty()) {
805 Triple = LLVM_HOSTTRIPLE;
806
Daniel Dunbar81caece2008-12-12 18:34:35 +0000807 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
808 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
809 Triple[2] == '8' && Triple[3] == '6')
810 Triple[1] = '3';
811
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000812 // On darwin, we want to update the version to match that of the
813 // host.
814 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
815 if (DarwinDashIdx != std::string::npos) {
816 Triple.resize(DarwinDashIdx + strlen("-darwin"));
817
Daniel Dunbar81caece2008-12-12 18:34:35 +0000818 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000819 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000820 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000821 }
822 }
Ted Kremenek40499482007-12-03 22:06:55 +0000823
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000824 // If -arch foo was specified, remove the architecture from the triple we have
825 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000826 if (!Arch.empty()) {
827 // Decompose the base triple into "arch" and suffix.
828 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000829
Chris Lattner2b168e02008-09-30 01:13:12 +0000830 if (FirstDashIdx == std::string::npos) {
831 fprintf(stderr,
832 "Malformed target triple: \"%s\" ('-' could not be found).\n",
833 Triple.c_str());
834 exit(1);
835 }
Ted Kremenek40499482007-12-03 22:06:55 +0000836
Chris Lattner2b168e02008-09-30 01:13:12 +0000837 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
838 }
839
840 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
841 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000842 if (!MacOSVersionMin.empty())
843 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000844
Chris Lattner2b168e02008-09-30 01:13:12 +0000845 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000846}
847
848//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000849// Preprocessor Initialization
850//===----------------------------------------------------------------------===//
851
852// FIXME: Preprocessor builtins to support.
853// -A... - Play with #assertions
854// -undef - Undefine all predefined macros
855
856static llvm::cl::list<std::string>
857D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
858 llvm::cl::desc("Predefine the specified macro"));
859static llvm::cl::list<std::string>
860U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
861 llvm::cl::desc("Undefine the specified macro"));
862
Chris Lattner008da782008-01-10 01:53:41 +0000863static llvm::cl::list<std::string>
864ImplicitIncludes("include", llvm::cl::value_desc("file"),
865 llvm::cl::desc("Include file before parsing"));
866
867
Chris Lattner4b009652007-07-25 00:24:17 +0000868// Append a #define line to Buf for Macro. Macro should be of the form XXX,
869// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
870// "#define XXX Y z W". To get a #define with no value, use "XXX=".
871static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
872 const char *Command = "#define ") {
873 Buf.insert(Buf.end(), Command, Command+strlen(Command));
874 if (const char *Equal = strchr(Macro, '=')) {
875 // Turn the = into ' '.
876 Buf.insert(Buf.end(), Macro, Equal);
877 Buf.push_back(' ');
878 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
879 } else {
880 // Push "macroname 1".
881 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
882 Buf.push_back(' ');
883 Buf.push_back('1');
884 }
885 Buf.push_back('\n');
886}
887
Chris Lattner008da782008-01-10 01:53:41 +0000888/// AddImplicitInclude - Add an implicit #include of the specified file to the
889/// predefines buffer.
890static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
891 const char *Inc = "#include \"";
892 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
893 Buf.insert(Buf.end(), File.begin(), File.end());
894 Buf.push_back('"');
895 Buf.push_back('\n');
896}
897
Chris Lattner4b009652007-07-25 00:24:17 +0000898
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000899/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000900/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000901///
Chris Lattner9d818a22008-04-19 23:25:44 +0000902static bool InitializePreprocessor(Preprocessor &PP,
903 bool InitializeSourceMgr,
904 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000905 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000906
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000907 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000908 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000909
910 if (InitializeSourceMgr) {
911 if (InFile != "-") {
912 const FileEntry *File = FileMgr.getFile(InFile);
913 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000914 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000915 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000916 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000917 }
918 } else {
919 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
920 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000921 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000922 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000923 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000924 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000925 }
Chris Lattner4b009652007-07-25 00:24:17 +0000926 }
Sam Bishop61a20782008-04-14 14:41:57 +0000927
Chris Lattner47b6a162008-04-19 23:09:31 +0000928 std::vector<char> PredefineBuffer;
929
Chris Lattner4b009652007-07-25 00:24:17 +0000930 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000931 unsigned d = 0, D = D_macros.size();
932 unsigned u = 0, U = U_macros.size();
933 while (d < D || u < U) {
934 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
935 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
936 else
937 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
938 }
939
Chris Lattner008da782008-01-10 01:53:41 +0000940 // FIXME: Read any files specified by -imacros.
941
942 // Add implicit #includes from -include.
943 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
944 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000945
Chris Lattner47b6a162008-04-19 23:09:31 +0000946 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000947 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000948 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000949
950 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000951 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000952}
953
954//===----------------------------------------------------------------------===//
955// Preprocessor include path information.
956//===----------------------------------------------------------------------===//
957
958// This tool exports a large number of command line options to control how the
959// preprocessor searches for header files. At root, however, the Preprocessor
960// object takes a very simple interface: a list of directories to search for
961//
962// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000963// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000964//
Chris Lattner008da782008-01-10 01:53:41 +0000965// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000966
967static llvm::cl::opt<bool>
968nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
969
970// Various command line options. These four add directories to each chain.
971static llvm::cl::list<std::string>
972F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
973 llvm::cl::desc("Add directory to framework include search path"));
974static llvm::cl::list<std::string>
975I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
976 llvm::cl::desc("Add directory to include search path"));
977static llvm::cl::list<std::string>
978idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
979 llvm::cl::desc("Add directory to AFTER include search path"));
980static llvm::cl::list<std::string>
981iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
982 llvm::cl::desc("Add directory to QUOTE include search path"));
983static llvm::cl::list<std::string>
984isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
985 llvm::cl::desc("Add directory to SYSTEM include search path"));
986
987// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
988static llvm::cl::list<std::string>
989iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
990 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
991static llvm::cl::list<std::string>
992iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
993 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
994static llvm::cl::list<std::string>
995iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
996 llvm::cl::Prefix,
997 llvm::cl::desc("Set directory to include search path with prefix"));
998
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000999static llvm::cl::opt<std::string>
1000isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1001 llvm::cl::desc("Set the system root directory (usually /)"));
1002
Chris Lattner4b009652007-07-25 00:24:17 +00001003// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001004
Chris Lattner4b009652007-07-25 00:24:17 +00001005/// InitializeIncludePaths - Process the -I options and set them in the
1006/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001007void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1008 FileManager &FM, const LangOptions &Lang) {
1009 InitHeaderSearch Init(Headers, Verbose, isysroot);
1010
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001011 // Handle -I... and -F... options, walking the lists in parallel.
1012 unsigned Iidx = 0, Fidx = 0;
1013 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1014 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001015 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001016 ++Iidx;
1017 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001018 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001019 ++Fidx;
1020 }
1021 }
Chris Lattner4b009652007-07-25 00:24:17 +00001022
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001023 // Consume what's left from whatever list was longer.
1024 for (; Iidx != I_dirs.size(); ++Iidx)
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 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001027 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001028
1029 // Handle -idirafter... options.
1030 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001031 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1032 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001033
1034 // Handle -iquote... options.
1035 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001036 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001037
1038 // Handle -isystem... options.
1039 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001040 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001041
1042 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1043 // parallel, processing the values in order of occurance to get the right
1044 // prefixes.
1045 {
1046 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1047 unsigned iprefix_idx = 0;
1048 unsigned iwithprefix_idx = 0;
1049 unsigned iwithprefixbefore_idx = 0;
1050 bool iprefix_done = iprefix_vals.empty();
1051 bool iwithprefix_done = iwithprefix_vals.empty();
1052 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1053 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1054 if (!iprefix_done &&
1055 (iwithprefix_done ||
1056 iprefix_vals.getPosition(iprefix_idx) <
1057 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1058 (iwithprefixbefore_done ||
1059 iprefix_vals.getPosition(iprefix_idx) <
1060 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1061 Prefix = iprefix_vals[iprefix_idx];
1062 ++iprefix_idx;
1063 iprefix_done = iprefix_idx == iprefix_vals.size();
1064 } else if (!iwithprefix_done &&
1065 (iwithprefixbefore_done ||
1066 iwithprefix_vals.getPosition(iwithprefix_idx) <
1067 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001068 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1069 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001070 ++iwithprefix_idx;
1071 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1072 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001073 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1074 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001075 ++iwithprefixbefore_idx;
1076 iwithprefixbefore_done =
1077 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1078 }
1079 }
1080 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001081
Nico Weber770e3882008-08-22 09:25:22 +00001082 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001083
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001084 // Add the clang headers, which are relative to the clang driver.
1085 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001086 llvm::sys::Path::GetMainExecutable(Argv0,
1087 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001088 if (!MainExecutablePath.isEmpty()) {
1089 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1090 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1091 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +00001092 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1093 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001094 }
1095
Nico Weber770e3882008-08-22 09:25:22 +00001096 if (!nostdinc)
1097 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001098
1099 // Now that we have collected all of the include paths, merge them all
1100 // together and tell the preprocessor about them.
1101
Nico Weber770e3882008-08-22 09:25:22 +00001102 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001103}
1104
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001105//===----------------------------------------------------------------------===//
1106// Driver PreprocessorFactory - For lazily generating preprocessors ...
1107//===----------------------------------------------------------------------===//
1108
1109namespace {
1110class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001111 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001112 Diagnostic &Diags;
1113 const LangOptions &LangInfo;
1114 TargetInfo &Target;
1115 SourceManager &SourceMgr;
1116 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001117 bool InitializeSourceMgr;
1118
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001119public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001120 DriverPreprocessorFactory(const std::string &infile,
1121 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001122 TargetInfo &target, SourceManager &SM,
1123 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001124 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1125 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1126
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001127
1128 virtual ~DriverPreprocessorFactory() {}
1129
1130 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001131 llvm::OwningPtr<PTHManager> PTHMgr;
1132
1133 // Use PTH?
1134 if (!TokenCache.empty())
Ted Kremenek3d145552009-01-28 20:49:33 +00001135 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001136
1137 // Create the Preprocessor.
1138 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1139 SourceMgr, HeaderInfo,
1140 PTHMgr.get()));
1141
1142 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1143 // That argument is used as the IdentifierInfoLookup argument to
1144 // IdentifierTable's ctor.
1145 if (PTHMgr) {
1146 PTHMgr->setPreprocessor(PP.get());
1147 PP->setPTHManager(PTHMgr.take());
1148 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001149
Chris Lattner9d818a22008-04-19 23:25:44 +00001150 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001151 return NULL;
1152 }
1153
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001154 /// FIXME: PP can only handle one callback
1155 if (ProgAction != PrintPreprocessedInput) {
1156 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001157 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001158 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001159 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001160 return NULL;
1161 }
1162 }
1163
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001164 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001165 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001166 }
1167};
1168}
Chris Lattner4b009652007-07-25 00:24:17 +00001169
Chris Lattner4b009652007-07-25 00:24:17 +00001170//===----------------------------------------------------------------------===//
1171// Basic Parser driver
1172//===----------------------------------------------------------------------===//
1173
Chris Lattner9d818a22008-04-19 23:25:44 +00001174static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001175 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001176 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001177
1178 // Parsing the specified input file.
1179 P.ParseTranslationUnit();
1180 delete PA;
1181}
1182
1183//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001184// Code generation options
1185//===----------------------------------------------------------------------===//
1186
1187static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001188OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001189
1190// It might be nice to add bounds to the CommandLine library directly.
1191struct OptLevelParser : public llvm::cl::parser<unsigned> {
1192 bool parse(llvm::cl::Option &O, const char *ArgName,
1193 const std::string &Arg, unsigned &Val) {
1194 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1195 return true;
1196 // FIXME: Support -O4.
1197 if (Val > 3)
1198 return O.error(": '" + Arg + "' invalid optimization level!");
1199 return false;
1200 }
1201};
1202static llvm::cl::opt<unsigned, false, OptLevelParser>
1203OptLevel("O", llvm::cl::Prefix,
1204 llvm::cl::desc("Optimization level"),
1205 llvm::cl::init(0));
1206
1207static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001208 Opts.OptimizeSize = OptSize;
Daniel Dunbard725b162008-10-29 07:56:11 +00001209 if (OptSize) {
1210 // -Os implies -O2
1211 // FIXME: Diagnose conflicting options.
1212 Opts.OptimizationLevel = 2;
1213 } else {
1214 Opts.OptimizationLevel = OptLevel;
1215 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001216
1217 // FIXME: There are llvm-gcc options to control these selectively.
1218 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1219 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Daniel Dunbar6670e332009-02-15 20:00:15 +00001220 Opts.SimplifyLibCalls = !Freestanding;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001221
1222#ifdef NDEBUG
1223 Opts.VerifyModule = 0;
1224#endif
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001225}
1226
1227//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001228// Main driver
1229//===----------------------------------------------------------------------===//
1230
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001231/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1232/// action. These consumers can operate on both ASTs that are freshly
1233/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001234static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001235 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001236 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001237 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001238 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001239 switch (ProgAction) {
1240 default:
1241 return NULL;
1242
1243 case ASTPrint:
1244 return CreateASTPrinter();
1245
1246 case ASTDump:
1247 return CreateASTDumper();
1248
1249 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001250 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001251
1252 case PrintDeclContext:
1253 return CreateDeclContextPrinter();
Ted Kremenek24612ae2008-03-18 21:19:49 +00001254
1255 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001256 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001257
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001258 case InheritanceView:
1259 return CreateInheritanceViewer(InheritanceViewCls);
1260
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001261 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001262 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001263
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001264 case EmitAssembly:
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001265 case EmitLLVM:
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001266 case EmitBC: {
1267 BackendAction Act;
1268 if (ProgAction == EmitAssembly) {
1269 Act = Backend_EmitAssembly;
1270 } else if (ProgAction == EmitLLVM) {
1271 Act = Backend_EmitLL;
1272 } else {
1273 Act = Backend_EmitBC;
1274 }
1275 CompileOptions Opts;
1276 InitializeCompileOptions(Opts);
1277 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001278 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001279 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001280
Ted Kremenekbde30332007-12-19 17:25:59 +00001281 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001282 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001283 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001284
Steve Naroff44e81222008-04-14 22:03:09 +00001285 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001286 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001287
1288 case RewriteBlocks:
1289 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001290
1291 case RunAnalysis:
Ted Kremenek99ec8f42009-02-17 04:27:41 +00001292 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001293 }
1294}
1295
Chris Lattner4b009652007-07-25 00:24:17 +00001296/// ProcessInputFile - Process a single input file with the specified state.
1297///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001298static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001299 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001300 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001301 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001302
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001303 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001304 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001305 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1306 PP.getFileManager(), PP.getLangOptions(),
1307 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001308
1309 if (!Consumer) {
1310 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001311 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001312 return;
1313 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001314
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001315 break;
1316
Chris Lattneraf669fb2008-10-12 05:03:36 +00001317 case DumpRawTokens: {
1318 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001319 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001320 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001321 RawLex.SetKeepWhitespaceMode(true);
1322
1323 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001324 RawLex.LexFromRawLexer(RawTok);
1325 while (RawTok.isNot(tok::eof)) {
1326 PP.DumpToken(RawTok, true);
1327 fprintf(stderr, "\n");
1328 RawLex.LexFromRawLexer(RawTok);
1329 }
1330 ClearSourceMgr = true;
1331 break;
1332 }
Chris Lattner4b009652007-07-25 00:24:17 +00001333 case DumpTokens: { // Token dump mode.
1334 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001335 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001336 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001337 do {
1338 PP.Lex(Tok);
1339 PP.DumpToken(Tok, true);
1340 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001341 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001342 ClearSourceMgr = true;
1343 break;
1344 }
1345 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1346 Token Tok;
1347 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001348 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001349 do {
1350 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001351 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001352 ClearSourceMgr = true;
1353 break;
1354 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001355
1356 case GeneratePCH: {
1357 CacheTokens(PP, OutputFile);
1358 ClearSourceMgr = true;
1359 break;
1360 }
Chris Lattner4b009652007-07-25 00:24:17 +00001361
1362 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001363 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001364 ClearSourceMgr = true;
1365 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001366
Chris Lattner4b009652007-07-25 00:24:17 +00001367 case ParseNoop: // -parse-noop
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001368 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001369 ClearSourceMgr = true;
1370 break;
1371
1372 case ParsePrintCallbacks:
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001373 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001374 ClearSourceMgr = true;
1375 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001376
Ted Kremenek6856c632007-09-26 18:39:29 +00001377 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001378 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001379 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001380
1381 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001382 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001383 ClearSourceMgr = true;
1384 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001385
1386 case RewriteTest:
1387 DoRewriteTest(PP, InFile, OutputFile);
1388 ClearSourceMgr = true;
1389 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001390 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001391
1392 if (Consumer) {
1393 TranslationUnit *TU = 0;
1394 if (DisableFree) {
1395 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1396 PP.getSourceManager(),
1397 PP.getTargetInfo(),
1398 PP.getIdentifierTable(),
1399 PP.getSelectorTable(),
1400 /* FreeMemory = */ false);
1401 TU = new TranslationUnit(*Context);
1402 }
1403 ParseAST(PP, Consumer.get(), TU, Stats);
1404 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001405
1406 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001407 if (CheckDiagnostics(PP))
1408 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001409
Chris Lattner4b009652007-07-25 00:24:17 +00001410 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001411 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001412 PP.PrintStats();
1413 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001414 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001415 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001416 fprintf(stderr, "\n");
1417 }
1418
1419 // For a multi-file compilation, some things are ok with nuking the source
1420 // manager tables, other require stable fileid/macroid's across multiple
1421 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001422 if (ClearSourceMgr)
1423 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001424
1425 if (DisableFree)
1426 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001427}
1428
Ted Kremenek80d53372007-12-12 23:41:08 +00001429static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1430 FileManager& FileMgr) {
1431
1432 if (VerifyDiagnostics) {
1433 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1434 exit (1);
1435 }
1436
1437 llvm::sys::Path Filename(InFile);
1438
1439 if (!Filename.isValid()) {
1440 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1441 exit (1);
1442 }
1443
Ted Kremenek863b01f2008-04-23 16:25:39 +00001444 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001445
1446 if (!TU) {
1447 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1448 InFile.c_str());
1449 exit (1);
1450 }
1451
Ted Kremenekab749372007-12-19 19:27:38 +00001452 // Observe that we use the source file name stored in the deserialized
1453 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001454 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001455 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001456 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001457
Ted Kremenek80d53372007-12-12 23:41:08 +00001458 if (!Consumer) {
1459 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1460 exit (1);
1461 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001462
Ted Kremenek863b01f2008-04-23 16:25:39 +00001463 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001464
Chris Lattner8d72ee02008-02-06 01:42:25 +00001465 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001466 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1467 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001468}
1469
1470
Chris Lattner4b009652007-07-25 00:24:17 +00001471static llvm::cl::list<std::string>
1472InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1473
Ted Kremenek80d53372007-12-12 23:41:08 +00001474static bool isSerializedFile(const std::string& InFile) {
1475 if (InFile.size() < 4)
1476 return false;
1477
1478 const char* s = InFile.c_str()+InFile.size()-4;
1479
1480 return s[0] == '.' &&
1481 s[1] == 'a' &&
1482 s[2] == 's' &&
1483 s[3] == 't';
1484}
1485
Chris Lattner4b009652007-07-25 00:24:17 +00001486
1487int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001488 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001489 llvm::sys::PrintStackTraceOnErrorSignal();
1490
1491 // If no input was specified, read from stdin.
1492 if (InputFilenames.empty())
1493 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001494
Chris Lattner4b009652007-07-25 00:24:17 +00001495 // Create a file manager object to provide access to and cache the filesystem.
1496 FileManager FileMgr;
1497
Ted Kremenekb240e822007-12-11 23:28:38 +00001498 // Create the diagnostic client for reporting errors or for
1499 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001500 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001501
Ted Kremenek5c341732008-08-07 17:49:57 +00001502 if (!VerifyDiagnostics) {
1503 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001504 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1505 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001506 !NoCaretDiagnostics,
1507 !NoShowLocation);
Ted Kremenek5c341732008-08-07 17:49:57 +00001508 } else {
1509 // When checking diagnostics, just buffer them up.
1510 TextDiagClient = new TextDiagnosticBuffer();
1511
1512 if (InputFilenames.size() != 1) {
1513 fprintf(stderr,
1514 "-verify only works on single input files for now.\n");
1515 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001516 }
1517 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001518
Chris Lattner4b009652007-07-25 00:24:17 +00001519 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001520 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1521 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001522 InitializeDiagnostics(Diags);
1523
Chris Lattner45a56e02007-12-05 23:24:17 +00001524 // -I- is a deprecated GCC feature, scan for it and reject it.
1525 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1526 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001527 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001528 I_dirs.erase(I_dirs.begin()+i);
1529 --i;
1530 }
1531 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001532
1533 // Get information about the target being compiled for.
1534 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001535 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1536
Chris Lattner2c77d852008-03-14 06:12:05 +00001537 if (Target == 0) {
1538 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1539 Triple.c_str());
1540 fprintf(stderr, "Please use -triple or -arch.\n");
1541 exit(1);
1542 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001543
Daniel Dunbar9c321102009-01-20 23:17:32 +00001544 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001545 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001546
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001547 llvm::OwningPtr<SourceManager> SourceMgr;
1548
Chris Lattner4b009652007-07-25 00:24:17 +00001549 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001550 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001551
Ted Kremenek5c341732008-08-07 17:49:57 +00001552 if (isSerializedFile(InFile)) {
1553 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001554 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001555 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001556 else {
1557 /// Create a SourceManager object. This tracks and owns all the file
1558 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001559 if (!SourceMgr)
1560 SourceMgr.reset(new SourceManager());
1561 else
1562 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001563
Ted Kremenek80d53372007-12-12 23:41:08 +00001564 // Initialize language options, inferring file types from input filenames.
1565 LangOptions LangInfo;
1566 InitializeBaseLanguage();
1567 LangKind LK = GetLanguage(InFile);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001568 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001569 InitializeGCMode(LangInfo);
Chris Lattnerddae7102008-12-04 22:54:33 +00001570 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001571
Ted Kremenek80d53372007-12-12 23:41:08 +00001572 // Process the -I options and set them in the HeaderInfo.
1573 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001574
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001575 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001576
Ted Kremenek80d53372007-12-12 23:41:08 +00001577 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001578 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001579 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001580
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001581 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1582
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001583 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001584 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001585
1586 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1587 // always reset to using TextDiagClient.
1588 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001589
Ted Kremenek5c341732008-08-07 17:49:57 +00001590 if (!HTMLDiag.empty()) {
1591 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1592 &PPFactory));
1593 Diags.setClient(TmpClient.get());
1594 }
1595 else
1596 Diags.setClient(TextDiagClient);
1597
1598 // Process the source file.
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001599 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1600
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001601 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001602 }
Chris Lattner4b009652007-07-25 00:24:17 +00001603 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001604
Mike Stump91d01352009-01-28 02:43:35 +00001605 if (Verbose)
1606 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1607 " hosted on " LLVM_HOSTTRIPLE "\n");
1608
Ted Kremenekec6c5252008-08-07 18:13:12 +00001609 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001610 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1611 (NumDiagnostics == 1 ? "" : "s"));
1612
1613 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001614 FileMgr.PrintStats();
1615 fprintf(stderr, "\n");
1616 }
1617
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001618 // If verifying diagnostics and we reached here, all is well.
1619 if (VerifyDiagnostics)
1620 return 0;
1621
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001622 // Managed static deconstruction. Useful for making things like
1623 // -time-passes usable.
1624 llvm::llvm_shutdown();
1625
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001626 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001627}