blob: d188f37c5a4d76dbbb54304c2af241b3622cf213 [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//
Chris Lattner39fb14e2009-02-18 01:17:01 +000020// -Wfatal-errors
Chris Lattner4b009652007-07-25 00:24:17 +000021// -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//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000214
215static llvm::cl::opt<bool>
216TimeReport("ftime-report",
217 llvm::cl::desc("Print the amount of time each "
218 "phase of compilation takes"));
219
Douglas Gregor23d23262009-02-14 20:49:29 +0000220static llvm::cl::opt<bool>
221Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000222 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000223 "freestanding environment"));
224
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000225static llvm::cl::opt<bool>
226MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000227 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000228 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000229
Douglas Gregor23d23262009-02-14 20:49:29 +0000230//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000231// Language Options
232//===----------------------------------------------------------------------===//
233
234enum LangKind {
235 langkind_unspecified,
236 langkind_c,
237 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000238 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000239 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000240 langkind_cxx,
241 langkind_cxx_cpp,
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000242 langkind_cxx_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000243 langkind_objc,
244 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000245 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000246 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000247 langkind_objcxx_cpp,
248 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000249};
250
Chris Lattner4b009652007-07-25 00:24:17 +0000251static llvm::cl::opt<LangKind>
252BaseLang("x", llvm::cl::desc("Base language to compile"),
253 llvm::cl::init(langkind_unspecified),
254 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
255 clEnumValN(langkind_cxx, "c++", "C++"),
256 clEnumValN(langkind_objc, "objective-c", "Objective C"),
257 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000258 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000259 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000260 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
261 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000262 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000263 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000264 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
265 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000266 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000267 "Preprocessed Objective C++"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000268 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000269 "Precompiled C header"),
270 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000271 "Precompiled Objective-C header"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000272 clEnumValN(langkind_cxx_pch, "c++-header",
273 "Precompiled C++ header"),
Ted Kremenekceacc812009-01-09 00:38:08 +0000274 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
275 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000276 clEnumValEnd));
277
278static llvm::cl::opt<bool>
279LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
280 llvm::cl::Hidden);
281static llvm::cl::opt<bool>
282LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
283 llvm::cl::Hidden);
284
Ted Kremenek11ad8952007-12-05 23:49:08 +0000285/// InitializeBaseLanguage - Handle the -x foo options.
286static void InitializeBaseLanguage() {
287 if (LangObjC)
288 BaseLang = langkind_objc;
289 else if (LangObjCXX)
290 BaseLang = langkind_objcxx;
291}
292
293static LangKind GetLanguage(const std::string &Filename) {
294 if (BaseLang != langkind_unspecified)
295 return BaseLang;
296
297 std::string::size_type DotPos = Filename.rfind('.');
298
299 if (DotPos == std::string::npos) {
300 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000301 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000302 }
303
Ted Kremenek11ad8952007-12-05 23:49:08 +0000304 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
305 // C header: .h
306 // C++ header: .hh or .H;
307 // assembler no preprocessing: .s
308 // assembler: .S
309 if (Ext == "c")
310 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000311 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000312 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000313 else if (Ext == "i")
314 return langkind_c_cpp;
315 else if (Ext == "ii")
316 return langkind_cxx_cpp;
317 else if (Ext == "m")
318 return langkind_objc;
319 else if (Ext == "mi")
320 return langkind_objc_cpp;
321 else if (Ext == "mm" || Ext == "M")
322 return langkind_objcxx;
323 else if (Ext == "mii")
324 return langkind_objcxx_cpp;
325 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
326 Ext == "c++" || Ext == "cp" || Ext == "cxx")
327 return langkind_cxx;
328 else
329 return langkind_c;
330}
331
332
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000333static void InitializeCOptions(LangOptions &Options) {
334 // Do nothing.
335}
336
337static void InitializeObjCOptions(LangOptions &Options) {
338 Options.ObjC1 = Options.ObjC2 = 1;
339}
340
341
342static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000343 // FIXME: implement -fpreprocessed mode.
344 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000345 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000346
347 // Test for 'PCH'.
348 switch (LK) {
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000349 default:
350 break;
351 case langkind_c_pch:
352 LK = langkind_c;
353 PCH = true;
354 break;
355 case langkind_objc_pch:
356 LK = langkind_objc;
357 PCH = true;
358 break;
359 case langkind_cxx_pch:
360 LK = langkind_cxx;
361 PCH = true;
362 break;
363 case langkind_objcxx_pch:
364 LK = langkind_objcxx;
365 PCH = true;
366 break;
Ted Kremenekceacc812009-01-09 00:38:08 +0000367 }
Chris Lattner4b009652007-07-25 00:24:17 +0000368
Ted Kremenek11ad8952007-12-05 23:49:08 +0000369 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000370 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000371 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000372 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000373 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000374 case langkind_c_cpp:
375 NoPreprocess = true;
376 // FALLTHROUGH
377 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000378 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000379 break;
380 case langkind_cxx_cpp:
381 NoPreprocess = true;
382 // FALLTHROUGH
383 case langkind_cxx:
384 Options.CPlusPlus = 1;
385 break;
386 case langkind_objc_cpp:
387 NoPreprocess = true;
388 // FALLTHROUGH
389 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000390 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000391 break;
392 case langkind_objcxx_cpp:
393 NoPreprocess = true;
394 // FALLTHROUGH
395 case langkind_objcxx:
396 Options.ObjC1 = Options.ObjC2 = 1;
397 Options.CPlusPlus = 1;
398 break;
399 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000400
401 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000402}
403
404/// LangStds - Language standards we support.
405enum LangStds {
406 lang_unspecified,
407 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000408 lang_gnu_START,
409 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000410 lang_cxx98, lang_gnucxx98,
411 lang_cxx0x, lang_gnucxx0x
412};
413
414static llvm::cl::opt<LangStds>
415LangStd("std", llvm::cl::desc("Language standard to compile for"),
416 llvm::cl::init(lang_unspecified),
417 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
418 clEnumValN(lang_c89, "c90", "ISO C 1990"),
419 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
420 clEnumValN(lang_c94, "iso9899:199409",
421 "ISO C 1990 with amendment 1"),
422 clEnumValN(lang_c99, "c99", "ISO C 1999"),
423// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
424 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
425// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
426 clEnumValN(lang_gnu89, "gnu89",
427 "ISO C 1990 with GNU extensions (default for C)"),
428 clEnumValN(lang_gnu99, "gnu99",
429 "ISO C 1999 with GNU extensions"),
430 clEnumValN(lang_gnu99, "gnu9x",
431 "ISO C 1999 with GNU extensions"),
432 clEnumValN(lang_cxx98, "c++98",
433 "ISO C++ 1998 with amendments"),
434 clEnumValN(lang_gnucxx98, "gnu++98",
435 "ISO C++ 1998 with amendments and GNU "
436 "extensions (default for C++)"),
437 clEnumValN(lang_cxx0x, "c++0x",
438 "Upcoming ISO C++ 200x with amendments"),
439 clEnumValN(lang_gnucxx0x, "gnu++0x",
440 "Upcoming ISO C++ 200x with amendments and GNU "
441 "extensions (default for C++)"),
442 clEnumValEnd));
443
444static llvm::cl::opt<bool>
445NoOperatorNames("fno-operator-names",
446 llvm::cl::desc("Do not treat C++ operator name keywords as "
447 "synonyms for operators"));
448
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000449static llvm::cl::opt<bool>
450PascalStrings("fpascal-strings",
451 llvm::cl::desc("Recognize and construct Pascal-style "
452 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000453
454static llvm::cl::opt<bool>
455MSExtensions("fms-extensions",
456 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000457 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000458
459static llvm::cl::opt<bool>
460WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000461 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000462
463static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000464NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000465 llvm::cl::desc("Disallow implicit conversions between "
466 "vectors with a different number of "
467 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000468
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000469static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000470EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
471 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
472 llvm::cl::ZeroOrMore);
473
474static llvm::cl::opt<bool>
475ObjCNonFragileABI("fobjc-nonfragile-abi",
476 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000477
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000478static llvm::cl::opt<bool>
479EmitAllDecls("femit-all-decls",
480 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000481
Daniel Dunbar91692d92008-08-11 17:36:14 +0000482// FIXME: This (and all GCC -f options) really come in -f... and
483// -fno-... forms, and additionally support automagic behavior when
484// they are not defined. For example, -fexceptions defaults to on or
485// off depending on the language. We should support this behavior in
486// some form (perhaps just add a facility for distinguishing when an
487// has its default value from when it has been set to its default
488// value).
489static llvm::cl::opt<bool>
490Exceptions("fexceptions",
491 llvm::cl::desc("Enable support for exception handling."));
492
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000493static llvm::cl::opt<bool>
494GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000495 llvm::cl::desc("Generate output compatible with the standard GNU "
496 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000497
498static llvm::cl::opt<bool>
499NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000500 llvm::cl::desc("Generate output compatible with the NeXT "
501 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000502
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000503
504
505static llvm::cl::opt<bool>
506Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
507
508static llvm::cl::opt<bool>
509Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
510
Chris Lattner4b009652007-07-25 00:24:17 +0000511// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000512// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000513static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
514 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000515 // Allow the target to set the default the langauge options as it sees fit.
516 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000517
518 if (Ansi) // "The -ansi option is equivalent to -std=c89."
519 LangStd = lang_c89;
520
Chris Lattner4b009652007-07-25 00:24:17 +0000521 if (LangStd == lang_unspecified) {
522 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000523 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000524 default: assert(0 && "Unknown base language");
525 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000526 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000527 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000528 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000529 case langkind_objc:
530 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000531 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000532 LangStd = lang_gnu99;
533 break;
534 case langkind_cxx:
535 case langkind_cxx_cpp:
536 case langkind_objcxx:
537 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000538 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000539 LangStd = lang_gnucxx98;
540 break;
541 }
542 }
543
544 switch (LangStd) {
545 default: assert(0 && "Unknown language standard!");
546
547 // Fall through from newer standards to older ones. This isn't really right.
548 // FIXME: Enable specifically the right features based on the language stds.
549 case lang_gnucxx0x:
550 case lang_cxx0x:
551 Options.CPlusPlus0x = 1;
552 // FALL THROUGH
553 case lang_gnucxx98:
554 case lang_cxx98:
555 Options.CPlusPlus = 1;
556 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000557 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000558 // FALL THROUGH.
559 case lang_gnu99:
560 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000561 Options.C99 = 1;
562 Options.HexFloats = 1;
563 // FALL THROUGH.
564 case lang_gnu89:
565 Options.BCPLComment = 1; // Only for C99/C++.
566 // FALL THROUGH.
567 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000568 Options.Digraphs = 1; // C94, C99, C++.
569 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000570 case lang_c89:
571 break;
572 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000573
574 if (Options.CPlusPlus) {
575 Options.C99 = 0;
576 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
577 }
Chris Lattner4b009652007-07-25 00:24:17 +0000578
Chris Lattner6ab935b2008-04-05 06:32:51 +0000579 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
580 Options.ImplicitInt = 1;
581 else
582 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000583
584 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
585 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000586 Options.Trigraphs = LangStd < lang_gnu_START;
587 if (Trigraphs.getPosition())
588 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000589
Chris Lattner58d5ba52008-12-05 00:10:44 +0000590 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
591 // even if they are normally on for the target. In GNU modes (e.g.
592 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000593 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
594 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000595 Options.Blocks = 0;
596
Chris Lattner4b009652007-07-25 00:24:17 +0000597 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000598 if (PascalStrings.getPosition())
599 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000600 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000601 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000602 if (NoLaxVectorConversions.getPosition())
603 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000604 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000605 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000606 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000607
Douglas Gregor23d23262009-02-14 20:49:29 +0000608 if (Freestanding)
609 Options.Freestanding = 1;
610
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000611 Options.MathErrno = MathErrno;
612
Chris Lattnerddae7102008-12-04 22:54:33 +0000613 // Override the default runtime if the user requested it.
614 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000615 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000616 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000617 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000618
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000619 if (ObjCNonFragileABI)
620 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000621
622 if (EmitAllDecls)
623 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000624}
625
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000626static llvm::cl::opt<bool>
627ObjCExclusiveGC("fobjc-gc-only",
628 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000629 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000630
631static llvm::cl::opt<bool>
632ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000633 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000634
635void InitializeGCMode(LangOptions &Options) {
636 if (ObjCExclusiveGC)
637 Options.setGCMode(LangOptions::GCOnly);
638 else if (ObjCEnableGC)
639 Options.setGCMode(LangOptions::HybridGC);
640}
641
Chris Lattner4b009652007-07-25 00:24:17 +0000642//===----------------------------------------------------------------------===//
643// Our DiagnosticClient implementation
644//===----------------------------------------------------------------------===//
645
646// FIXME: Werror should take a list of things, -Werror=foo,bar
647static llvm::cl::opt<bool>
648WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
649
650static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000651SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
652
653static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000654WarnOnExtensions("pedantic", llvm::cl::init(false),
655 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
656
657static llvm::cl::opt<bool>
658ErrorOnExtensions("pedantic-errors",
659 llvm::cl::desc("Issue an error on uses of GCC extensions"));
660
661static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000662SuppressSystemWarnings("suppress-system-warnings",
Chris Lattner71af6d62009-02-06 04:16:41 +0000663 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000664 llvm::cl::init(true));
665
666static llvm::cl::opt<bool>
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000667WarnUnusedMacros("Wunused-macros",
Chris Lattner4b009652007-07-25 00:24:17 +0000668 llvm::cl::desc("Warn for unused macros in the main translation unit"));
669
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000670static llvm::cl::opt<bool>
671WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000672 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000673
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000674static llvm::cl::opt<bool>
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000675WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
676 llvm::cl::desc("Warn about readonly properties with writable attributes"));
677
678static llvm::cl::opt<bool>
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000679WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000680 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000681
Chris Lattnera616ee32008-01-23 17:19:46 +0000682static llvm::cl::opt<bool>
683WarnUndefMacros("Wundef",
684 llvm::cl::desc("Warn on use of undefined macros in #if's"));
685
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000686static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000687WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
688 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000689
Steve Naroffb91afca2008-10-21 10:37:50 +0000690static llvm::cl::opt<bool>
691WarnNoStrictSelectorMatch("Wno-strict-selector-match",
Chris Lattner71af6d62009-02-06 04:16:41 +0000692 llvm::cl::desc("Do not warn about duplicate methods that have the same size"
693 " and alignment"),
Steve Naroffb91afca2008-10-21 10:37:50 +0000694 llvm::cl::init(true));
695
Chris Lattner4b009652007-07-25 00:24:17 +0000696/// InitializeDiagnostics - Initialize the diagnostic object, based on the
697/// current command line option settings.
698static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000699 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000700 Diags.setWarningsAsErrors(WarningsAsErrors);
701 Diags.setWarnOnExtensions(WarnOnExtensions);
702 Diags.setErrorOnExtensions(ErrorOnExtensions);
703
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000704 // Suppress warnings in system headers unless requested not to.
705 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
706
Chris Lattner4b009652007-07-25 00:24:17 +0000707 // Silence the "macro is not used" warning unless requested.
708 if (!WarnUnusedMacros)
709 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000710
711 // Silence "floating point comparison" warnings unless requested.
712 if (!WarnFloatEqual)
713 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000714
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000715 if (!WarnPropertyReadonlyAttrs)
716 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
717 diag::MAP_IGNORE);
718
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000719 // Silence "format string is not a string literal" warnings if requested
720 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000721 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
722 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000723 if (!WarnUndefMacros)
724 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000725
Chris Lattner86a24842009-01-29 06:55:46 +0000726 if (WarnImplicitFunctionDeclaration)
727 Diags.setDiagnosticMapping(diag::ext_implicit_function_decl,
728 diag::MAP_WARNING);
729 else
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000730 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
731 diag::MAP_IGNORE);
Chris Lattner71af6d62009-02-06 04:16:41 +0000732
733
734 Diags.setDiagnosticMapping(diag::err_pp_file_not_found, diag::MAP_FATAL);
Chris Lattner4b009652007-07-25 00:24:17 +0000735}
736
737//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000738// Target Triple Processing.
739//===----------------------------------------------------------------------===//
740
741static llvm::cl::opt<std::string>
742TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000743 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000744
Chris Lattnerfc457002008-03-05 01:18:20 +0000745static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000746Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000747
Chris Lattner2b168e02008-09-30 01:13:12 +0000748static llvm::cl::opt<std::string>
749MacOSVersionMin("mmacosx-version-min",
750 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
751
Chris Lattner01de9c82008-09-30 20:16:56 +0000752// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
753// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
754static void HandleMacOSVersionMin(std::string &Triple) {
755 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
756 if (DarwinDashIdx == std::string::npos) {
757 fprintf(stderr,
758 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
759 exit(1);
760 }
761 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
762
Chris Lattner01de9c82008-09-30 20:16:56 +0000763 // Remove the number.
764 Triple.resize(DarwinNumIdx);
765
766 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
767 bool MacOSVersionMinIsInvalid = false;
768 int VersionNum = 0;
769 if (MacOSVersionMin.size() < 4 ||
770 MacOSVersionMin.substr(0, 3) != "10." ||
771 !isdigit(MacOSVersionMin[3])) {
772 MacOSVersionMinIsInvalid = true;
773 } else {
774 const char *Start = MacOSVersionMin.c_str()+3;
775 char *End = 0;
776 VersionNum = (int)strtol(Start, &End, 10);
777
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000778 // The version number must be in the range 0-9.
779 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
780
Chris Lattner01de9c82008-09-30 20:16:56 +0000781 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
782 Triple += llvm::itostr(VersionNum+4);
783
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000784 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
785 // Add the period piece (.7) to the end of the triple. This gives us
786 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000787 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000788 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
789 MacOSVersionMinIsInvalid = true;
790 }
791 }
792
793 if (MacOSVersionMinIsInvalid) {
794 fprintf(stderr,
795 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
796 MacOSVersionMin.c_str());
797 exit(1);
798 }
799}
800
801/// CreateTargetTriple - Process the various options that affect the target
802/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000803static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000804 // Initialize base triple. If a -triple option has been specified, use
805 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000806 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000807 if (Triple.empty()) {
808 Triple = LLVM_HOSTTRIPLE;
809
Daniel Dunbar81caece2008-12-12 18:34:35 +0000810 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
811 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
812 Triple[2] == '8' && Triple[3] == '6')
813 Triple[1] = '3';
814
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000815 // On darwin, we want to update the version to match that of the
816 // host.
817 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
818 if (DarwinDashIdx != std::string::npos) {
819 Triple.resize(DarwinDashIdx + strlen("-darwin"));
820
Daniel Dunbar81caece2008-12-12 18:34:35 +0000821 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000822 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000823 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000824 }
825 }
Ted Kremenek40499482007-12-03 22:06:55 +0000826
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000827 // If -arch foo was specified, remove the architecture from the triple we have
828 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000829 if (!Arch.empty()) {
830 // Decompose the base triple into "arch" and suffix.
831 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000832
Chris Lattner2b168e02008-09-30 01:13:12 +0000833 if (FirstDashIdx == std::string::npos) {
834 fprintf(stderr,
835 "Malformed target triple: \"%s\" ('-' could not be found).\n",
836 Triple.c_str());
837 exit(1);
838 }
Ted Kremenek40499482007-12-03 22:06:55 +0000839
Chris Lattner2b168e02008-09-30 01:13:12 +0000840 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
841 }
842
843 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
844 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000845 if (!MacOSVersionMin.empty())
846 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000847
Chris Lattner2b168e02008-09-30 01:13:12 +0000848 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000849}
850
851//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000852// Preprocessor Initialization
853//===----------------------------------------------------------------------===//
854
855// FIXME: Preprocessor builtins to support.
856// -A... - Play with #assertions
857// -undef - Undefine all predefined macros
858
859static llvm::cl::list<std::string>
860D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
861 llvm::cl::desc("Predefine the specified macro"));
862static llvm::cl::list<std::string>
863U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
864 llvm::cl::desc("Undefine the specified macro"));
865
Chris Lattner008da782008-01-10 01:53:41 +0000866static llvm::cl::list<std::string>
867ImplicitIncludes("include", llvm::cl::value_desc("file"),
868 llvm::cl::desc("Include file before parsing"));
869
870
Chris Lattner4b009652007-07-25 00:24:17 +0000871// Append a #define line to Buf for Macro. Macro should be of the form XXX,
872// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
873// "#define XXX Y z W". To get a #define with no value, use "XXX=".
874static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
875 const char *Command = "#define ") {
876 Buf.insert(Buf.end(), Command, Command+strlen(Command));
877 if (const char *Equal = strchr(Macro, '=')) {
878 // Turn the = into ' '.
879 Buf.insert(Buf.end(), Macro, Equal);
880 Buf.push_back(' ');
881 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
882 } else {
883 // Push "macroname 1".
884 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
885 Buf.push_back(' ');
886 Buf.push_back('1');
887 }
888 Buf.push_back('\n');
889}
890
Chris Lattner008da782008-01-10 01:53:41 +0000891/// AddImplicitInclude - Add an implicit #include of the specified file to the
892/// predefines buffer.
893static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
894 const char *Inc = "#include \"";
895 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
896 Buf.insert(Buf.end(), File.begin(), File.end());
897 Buf.push_back('"');
898 Buf.push_back('\n');
899}
900
Chris Lattner4b009652007-07-25 00:24:17 +0000901
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000902/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000903/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000904///
Chris Lattner9d818a22008-04-19 23:25:44 +0000905static bool InitializePreprocessor(Preprocessor &PP,
906 bool InitializeSourceMgr,
907 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000908 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000909
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000910 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000911 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000912
913 if (InitializeSourceMgr) {
914 if (InFile != "-") {
915 const FileEntry *File = FileMgr.getFile(InFile);
916 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000917 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000918 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000919 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000920 }
921 } else {
922 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
923 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000924 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000925 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000926 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000927 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000928 }
Chris Lattner4b009652007-07-25 00:24:17 +0000929 }
Sam Bishop61a20782008-04-14 14:41:57 +0000930
Chris Lattner47b6a162008-04-19 23:09:31 +0000931 std::vector<char> PredefineBuffer;
932
Chris Lattner4b009652007-07-25 00:24:17 +0000933 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000934 unsigned d = 0, D = D_macros.size();
935 unsigned u = 0, U = U_macros.size();
936 while (d < D || u < U) {
937 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
938 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
939 else
940 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
941 }
942
Chris Lattner008da782008-01-10 01:53:41 +0000943 // FIXME: Read any files specified by -imacros.
944
945 // Add implicit #includes from -include.
946 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
947 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000948
Chris Lattner47b6a162008-04-19 23:09:31 +0000949 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000950 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000951 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000952
953 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000954 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000955}
956
957//===----------------------------------------------------------------------===//
958// Preprocessor include path information.
959//===----------------------------------------------------------------------===//
960
961// This tool exports a large number of command line options to control how the
962// preprocessor searches for header files. At root, however, the Preprocessor
963// object takes a very simple interface: a list of directories to search for
964//
965// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000966// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000967//
Chris Lattner008da782008-01-10 01:53:41 +0000968// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000969
970static llvm::cl::opt<bool>
971nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
972
973// Various command line options. These four add directories to each chain.
974static llvm::cl::list<std::string>
975F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
976 llvm::cl::desc("Add directory to framework include search path"));
977static llvm::cl::list<std::string>
978I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
979 llvm::cl::desc("Add directory to include search path"));
980static llvm::cl::list<std::string>
981idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
982 llvm::cl::desc("Add directory to AFTER include search path"));
983static llvm::cl::list<std::string>
984iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
985 llvm::cl::desc("Add directory to QUOTE include search path"));
986static llvm::cl::list<std::string>
987isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
988 llvm::cl::desc("Add directory to SYSTEM include search path"));
989
990// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
991static llvm::cl::list<std::string>
992iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
993 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
994static llvm::cl::list<std::string>
995iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
996 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
997static llvm::cl::list<std::string>
998iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
999 llvm::cl::Prefix,
1000 llvm::cl::desc("Set directory to include search path with prefix"));
1001
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001002static llvm::cl::opt<std::string>
1003isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1004 llvm::cl::desc("Set the system root directory (usually /)"));
1005
Chris Lattner4b009652007-07-25 00:24:17 +00001006// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001007
Chris Lattner4b009652007-07-25 00:24:17 +00001008/// InitializeIncludePaths - Process the -I options and set them in the
1009/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001010void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1011 FileManager &FM, const LangOptions &Lang) {
1012 InitHeaderSearch Init(Headers, Verbose, isysroot);
1013
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001014 // Handle -I... and -F... options, walking the lists in parallel.
1015 unsigned Iidx = 0, Fidx = 0;
1016 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1017 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001018 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001019 ++Iidx;
1020 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001021 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001022 ++Fidx;
1023 }
1024 }
Chris Lattner4b009652007-07-25 00:24:17 +00001025
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001026 // Consume what's left from whatever list was longer.
1027 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001028 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001029 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001030 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001031
1032 // Handle -idirafter... options.
1033 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001034 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1035 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001036
1037 // Handle -iquote... options.
1038 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001039 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001040
1041 // Handle -isystem... options.
1042 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001043 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001044
1045 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1046 // parallel, processing the values in order of occurance to get the right
1047 // prefixes.
1048 {
1049 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1050 unsigned iprefix_idx = 0;
1051 unsigned iwithprefix_idx = 0;
1052 unsigned iwithprefixbefore_idx = 0;
1053 bool iprefix_done = iprefix_vals.empty();
1054 bool iwithprefix_done = iwithprefix_vals.empty();
1055 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1056 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1057 if (!iprefix_done &&
1058 (iwithprefix_done ||
1059 iprefix_vals.getPosition(iprefix_idx) <
1060 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1061 (iwithprefixbefore_done ||
1062 iprefix_vals.getPosition(iprefix_idx) <
1063 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1064 Prefix = iprefix_vals[iprefix_idx];
1065 ++iprefix_idx;
1066 iprefix_done = iprefix_idx == iprefix_vals.size();
1067 } else if (!iwithprefix_done &&
1068 (iwithprefixbefore_done ||
1069 iwithprefix_vals.getPosition(iwithprefix_idx) <
1070 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001071 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1072 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001073 ++iwithprefix_idx;
1074 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1075 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001076 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1077 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001078 ++iwithprefixbefore_idx;
1079 iwithprefixbefore_done =
1080 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1081 }
1082 }
1083 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001084
Nico Weber770e3882008-08-22 09:25:22 +00001085 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001086
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001087 // Add the clang headers, which are relative to the clang driver.
1088 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001089 llvm::sys::Path::GetMainExecutable(Argv0,
1090 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001091 if (!MainExecutablePath.isEmpty()) {
1092 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1093 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1094 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +00001095 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1096 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001097 }
1098
Nico Weber770e3882008-08-22 09:25:22 +00001099 if (!nostdinc)
1100 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001101
1102 // Now that we have collected all of the include paths, merge them all
1103 // together and tell the preprocessor about them.
1104
Nico Weber770e3882008-08-22 09:25:22 +00001105 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001106}
1107
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001108//===----------------------------------------------------------------------===//
1109// Driver PreprocessorFactory - For lazily generating preprocessors ...
1110//===----------------------------------------------------------------------===//
1111
1112namespace {
1113class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001114 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001115 Diagnostic &Diags;
1116 const LangOptions &LangInfo;
1117 TargetInfo &Target;
1118 SourceManager &SourceMgr;
1119 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001120 bool InitializeSourceMgr;
1121
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001122public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001123 DriverPreprocessorFactory(const std::string &infile,
1124 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001125 TargetInfo &target, SourceManager &SM,
1126 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001127 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1128 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1129
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001130
1131 virtual ~DriverPreprocessorFactory() {}
1132
1133 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001134 llvm::OwningPtr<PTHManager> PTHMgr;
1135
1136 // Use PTH?
1137 if (!TokenCache.empty())
Ted Kremenek3d145552009-01-28 20:49:33 +00001138 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001139
1140 // Create the Preprocessor.
1141 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1142 SourceMgr, HeaderInfo,
1143 PTHMgr.get()));
1144
1145 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1146 // That argument is used as the IdentifierInfoLookup argument to
1147 // IdentifierTable's ctor.
1148 if (PTHMgr) {
1149 PTHMgr->setPreprocessor(PP.get());
1150 PP->setPTHManager(PTHMgr.take());
1151 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001152
Chris Lattner9d818a22008-04-19 23:25:44 +00001153 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001154 return NULL;
1155 }
1156
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001157 /// FIXME: PP can only handle one callback
1158 if (ProgAction != PrintPreprocessedInput) {
1159 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001160 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001161 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001162 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001163 return NULL;
1164 }
1165 }
1166
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001167 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001168 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001169 }
1170};
1171}
Chris Lattner4b009652007-07-25 00:24:17 +00001172
Chris Lattner4b009652007-07-25 00:24:17 +00001173//===----------------------------------------------------------------------===//
1174// Basic Parser driver
1175//===----------------------------------------------------------------------===//
1176
Chris Lattner9d818a22008-04-19 23:25:44 +00001177static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001178 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001179 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001180
1181 // Parsing the specified input file.
1182 P.ParseTranslationUnit();
1183 delete PA;
1184}
1185
1186//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001187// Code generation options
1188//===----------------------------------------------------------------------===//
1189
1190static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001191OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001192
1193// It might be nice to add bounds to the CommandLine library directly.
1194struct OptLevelParser : public llvm::cl::parser<unsigned> {
1195 bool parse(llvm::cl::Option &O, const char *ArgName,
1196 const std::string &Arg, unsigned &Val) {
1197 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1198 return true;
1199 // FIXME: Support -O4.
1200 if (Val > 3)
1201 return O.error(": '" + Arg + "' invalid optimization level!");
1202 return false;
1203 }
1204};
1205static llvm::cl::opt<unsigned, false, OptLevelParser>
1206OptLevel("O", llvm::cl::Prefix,
1207 llvm::cl::desc("Optimization level"),
1208 llvm::cl::init(0));
1209
Daniel Dunbar9101a632009-02-17 19:47:34 +00001210static llvm::cl::opt<std::string>
1211TargetCPU("mcpu",
1212 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1213
1214static llvm::cl::list<std::string>
1215TargetFeatures("mattr",
1216 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
1217
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001218static 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);
Daniel Dunbar6670e332009-02-15 20:00:15 +00001231 Opts.SimplifyLibCalls = !Freestanding;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001232
1233#ifdef NDEBUG
1234 Opts.VerifyModule = 0;
1235#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001236
1237 Opts.CPU = TargetCPU;
1238 Opts.Features.insert(Opts.Features.end(),
1239 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001240
1241 // Handle -ftime-report.
1242 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001243}
1244
1245//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001246// Main driver
1247//===----------------------------------------------------------------------===//
1248
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001249/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1250/// action. These consumers can operate on both ASTs that are freshly
1251/// parsed from source files as well as those deserialized from Bitcode.
Chris Lattner7f902922009-02-18 01:20:05 +00001252static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001253 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001254 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001255 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001256 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001257 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001258 default:
1259 return NULL;
1260
1261 case ASTPrint:
1262 return CreateASTPrinter();
1263
1264 case ASTDump:
1265 return CreateASTDumper();
1266
1267 case ASTView:
1268 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001269
Chris Lattner7f902922009-02-18 01:20:05 +00001270 case PrintDeclContext:
1271 return CreateDeclContextPrinter();
1272
1273 case EmitHTML:
1274 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001275
Chris Lattner7f902922009-02-18 01:20:05 +00001276 case InheritanceView:
1277 return CreateInheritanceViewer(InheritanceViewCls);
1278
1279 case TestSerialization:
1280 return CreateSerializationTest(Diag, FileMgr);
1281
1282 case EmitAssembly:
1283 case EmitLLVM:
1284 case EmitBC: {
1285 BackendAction Act;
1286 if (ProgAction == EmitAssembly)
1287 Act = Backend_EmitAssembly;
1288 else if (ProgAction == EmitLLVM)
1289 Act = Backend_EmitLL;
1290 else
1291 Act = Backend_EmitBC;
1292
1293 CompileOptions Opts;
1294 InitializeCompileOptions(Opts);
1295 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
1296 InFile, OutputFile, GenerateDebugInfo);
1297 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001298
Chris Lattner7f902922009-02-18 01:20:05 +00001299 case SerializeAST:
1300 // FIXME: Allow user to tailor where the file is written.
1301 return CreateASTSerializer(InFile, OutputFile, Diag);
1302
1303 case RewriteObjC:
1304 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001305
Chris Lattner7f902922009-02-18 01:20:05 +00001306 case RewriteBlocks:
1307 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1308
1309 case RunAnalysis:
1310 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001311 }
1312}
1313
Chris Lattner4b009652007-07-25 00:24:17 +00001314/// ProcessInputFile - Process a single input file with the specified state.
1315///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001316static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001317 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001318 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001319 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001320
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001321 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001322 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001323 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1324 PP.getFileManager(), PP.getLangOptions(),
1325 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001326
1327 if (!Consumer) {
1328 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001329 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001330 return;
1331 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001332
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001333 break;
1334
Chris Lattneraf669fb2008-10-12 05:03:36 +00001335 case DumpRawTokens: {
1336 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001337 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001338 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001339 RawLex.SetKeepWhitespaceMode(true);
1340
1341 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001342 RawLex.LexFromRawLexer(RawTok);
1343 while (RawTok.isNot(tok::eof)) {
1344 PP.DumpToken(RawTok, true);
1345 fprintf(stderr, "\n");
1346 RawLex.LexFromRawLexer(RawTok);
1347 }
1348 ClearSourceMgr = true;
1349 break;
1350 }
Chris Lattner4b009652007-07-25 00:24:17 +00001351 case DumpTokens: { // Token dump mode.
1352 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001353 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001354 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001355 do {
1356 PP.Lex(Tok);
1357 PP.DumpToken(Tok, true);
1358 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001359 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001360 ClearSourceMgr = true;
1361 break;
1362 }
1363 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1364 Token Tok;
1365 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001366 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001367 do {
1368 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001369 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001370 ClearSourceMgr = true;
1371 break;
1372 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001373
1374 case GeneratePCH: {
1375 CacheTokens(PP, OutputFile);
1376 ClearSourceMgr = true;
1377 break;
1378 }
Chris Lattner4b009652007-07-25 00:24:17 +00001379
1380 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001381 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001382 ClearSourceMgr = true;
1383 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001384
Chris Lattner4b009652007-07-25 00:24:17 +00001385 case ParseNoop: // -parse-noop
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001386 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001387 ClearSourceMgr = true;
1388 break;
1389
1390 case ParsePrintCallbacks:
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001391 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001392 ClearSourceMgr = true;
1393 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001394
Ted Kremenek6856c632007-09-26 18:39:29 +00001395 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001396 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001397 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001398
1399 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001400 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001401 ClearSourceMgr = true;
1402 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001403
1404 case RewriteTest:
1405 DoRewriteTest(PP, InFile, OutputFile);
1406 ClearSourceMgr = true;
1407 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001408 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001409
1410 if (Consumer) {
1411 TranslationUnit *TU = 0;
1412 if (DisableFree) {
1413 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1414 PP.getSourceManager(),
1415 PP.getTargetInfo(),
1416 PP.getIdentifierTable(),
1417 PP.getSelectorTable(),
1418 /* FreeMemory = */ false);
1419 TU = new TranslationUnit(*Context);
1420 }
1421 ParseAST(PP, Consumer.get(), TU, Stats);
1422 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001423
1424 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001425 if (CheckDiagnostics(PP))
1426 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001427
Chris Lattner4b009652007-07-25 00:24:17 +00001428 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001429 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001430 PP.PrintStats();
1431 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001432 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001433 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001434 fprintf(stderr, "\n");
1435 }
1436
1437 // For a multi-file compilation, some things are ok with nuking the source
1438 // manager tables, other require stable fileid/macroid's across multiple
1439 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001440 if (ClearSourceMgr)
1441 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001442
1443 if (DisableFree)
1444 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001445}
1446
Ted Kremenek80d53372007-12-12 23:41:08 +00001447static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1448 FileManager& FileMgr) {
1449
1450 if (VerifyDiagnostics) {
1451 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1452 exit (1);
1453 }
1454
1455 llvm::sys::Path Filename(InFile);
1456
1457 if (!Filename.isValid()) {
1458 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1459 exit (1);
1460 }
1461
Ted Kremenek863b01f2008-04-23 16:25:39 +00001462 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001463
1464 if (!TU) {
1465 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1466 InFile.c_str());
1467 exit (1);
1468 }
1469
Ted Kremenekab749372007-12-19 19:27:38 +00001470 // Observe that we use the source file name stored in the deserialized
1471 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001472 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001473 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001474 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001475
Ted Kremenek80d53372007-12-12 23:41:08 +00001476 if (!Consumer) {
1477 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1478 exit (1);
1479 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001480
Ted Kremenek863b01f2008-04-23 16:25:39 +00001481 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001482
Chris Lattner8d72ee02008-02-06 01:42:25 +00001483 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001484 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1485 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001486}
1487
1488
Chris Lattner4b009652007-07-25 00:24:17 +00001489static llvm::cl::list<std::string>
1490InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1491
Ted Kremenek80d53372007-12-12 23:41:08 +00001492static bool isSerializedFile(const std::string& InFile) {
1493 if (InFile.size() < 4)
1494 return false;
1495
1496 const char* s = InFile.c_str()+InFile.size()-4;
1497
1498 return s[0] == '.' &&
1499 s[1] == 'a' &&
1500 s[2] == 's' &&
1501 s[3] == 't';
1502}
1503
Chris Lattner4b009652007-07-25 00:24:17 +00001504
1505int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001506 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001507 llvm::sys::PrintStackTraceOnErrorSignal();
1508
1509 // If no input was specified, read from stdin.
1510 if (InputFilenames.empty())
1511 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001512
Chris Lattner4b009652007-07-25 00:24:17 +00001513 // Create a file manager object to provide access to and cache the filesystem.
1514 FileManager FileMgr;
1515
Ted Kremenekb240e822007-12-11 23:28:38 +00001516 // Create the diagnostic client for reporting errors or for
1517 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001518 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001519
Ted Kremenek5c341732008-08-07 17:49:57 +00001520 if (!VerifyDiagnostics) {
1521 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001522 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1523 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001524 !NoCaretDiagnostics,
1525 !NoShowLocation);
Ted Kremenek5c341732008-08-07 17:49:57 +00001526 } else {
1527 // When checking diagnostics, just buffer them up.
1528 TextDiagClient = new TextDiagnosticBuffer();
1529
1530 if (InputFilenames.size() != 1) {
1531 fprintf(stderr,
1532 "-verify only works on single input files for now.\n");
1533 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001534 }
1535 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001536
Chris Lattner4b009652007-07-25 00:24:17 +00001537 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001538 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1539 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001540 InitializeDiagnostics(Diags);
1541
Chris Lattner45a56e02007-12-05 23:24:17 +00001542 // -I- is a deprecated GCC feature, scan for it and reject it.
1543 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1544 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001545 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001546 I_dirs.erase(I_dirs.begin()+i);
1547 --i;
1548 }
1549 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001550
1551 // Get information about the target being compiled for.
1552 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001553 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1554
Chris Lattner2c77d852008-03-14 06:12:05 +00001555 if (Target == 0) {
1556 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1557 Triple.c_str());
1558 fprintf(stderr, "Please use -triple or -arch.\n");
1559 exit(1);
1560 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001561
Daniel Dunbar9c321102009-01-20 23:17:32 +00001562 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001563 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001564
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001565 llvm::OwningPtr<SourceManager> SourceMgr;
1566
Chris Lattner4b009652007-07-25 00:24:17 +00001567 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001568 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001569
Ted Kremenek5c341732008-08-07 17:49:57 +00001570 if (isSerializedFile(InFile)) {
1571 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001572 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001573 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001574 else {
1575 /// Create a SourceManager object. This tracks and owns all the file
1576 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001577 if (!SourceMgr)
1578 SourceMgr.reset(new SourceManager());
1579 else
1580 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001581
Ted Kremenek80d53372007-12-12 23:41:08 +00001582 // Initialize language options, inferring file types from input filenames.
1583 LangOptions LangInfo;
1584 InitializeBaseLanguage();
1585 LangKind LK = GetLanguage(InFile);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001586 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001587 InitializeGCMode(LangInfo);
Chris Lattnerddae7102008-12-04 22:54:33 +00001588 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001589
Ted Kremenek80d53372007-12-12 23:41:08 +00001590 // Process the -I options and set them in the HeaderInfo.
1591 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001592
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001593 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001594
Ted Kremenek80d53372007-12-12 23:41:08 +00001595 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001596 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001597 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001598
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001599 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1600
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001601 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001602 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001603
1604 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1605 // always reset to using TextDiagClient.
1606 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001607
Ted Kremenek5c341732008-08-07 17:49:57 +00001608 if (!HTMLDiag.empty()) {
1609 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1610 &PPFactory));
1611 Diags.setClient(TmpClient.get());
1612 }
1613 else
1614 Diags.setClient(TextDiagClient);
1615
1616 // Process the source file.
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001617 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1618
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001619 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001620 }
Chris Lattner4b009652007-07-25 00:24:17 +00001621 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001622
Mike Stump91d01352009-01-28 02:43:35 +00001623 if (Verbose)
1624 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1625 " hosted on " LLVM_HOSTTRIPLE "\n");
1626
Ted Kremenekec6c5252008-08-07 18:13:12 +00001627 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001628 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1629 (NumDiagnostics == 1 ? "" : "s"));
1630
1631 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001632 FileMgr.PrintStats();
1633 fprintf(stderr, "\n");
1634 }
1635
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001636 // If verifying diagnostics and we reached here, all is well.
1637 if (VerifyDiagnostics)
1638 return 0;
1639
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001640 // Managed static deconstruction. Useful for making things like
1641 // -time-passes usable.
1642 llvm::llvm_shutdown();
1643
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001644 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001645}