blob: c4145c01a7a3c86d162741e72382456f2f5c9b05 [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 Dunbar68952de2009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
28#include "clang/Frontend/PathDiagnosticClients.h"
29#include "clang/Frontend/InitHeaderSearch.h"
30#include "clang/Frontend/TextDiagnosticBuffer.h"
31#include "clang/Frontend/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"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000053#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000054#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000055#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000056#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000057#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000058using namespace clang;
59
60//===----------------------------------------------------------------------===//
61// Global options.
62//===----------------------------------------------------------------------===//
63
Chris Lattnerefe33382009-02-18 01:51:21 +000064/// ClangFrontendTimer - The front-end activities should charge time to it with
65/// TimeRegion. The -ftime-report option controls whether this will do
66/// anything.
67llvm::Timer *ClangFrontendTimer = 0;
68
Daniel Dunbar4efedde2008-10-16 16:54:18 +000069static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000070
Chris Lattner4b009652007-07-25 00:24:17 +000071static llvm::cl::opt<bool>
72Verbose("v", llvm::cl::desc("Enable verbose output"));
73static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000074Stats("print-stats",
75 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000076static llvm::cl::opt<bool>
77DisableFree("disable-free",
78 llvm::cl::desc("Disable freeing of memory on exit"),
79 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000080
81enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000082 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000083 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000084 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000085 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000086 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000087 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000088 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000089 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +000090 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek397de012007-12-13 00:37:31 +000091 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000092 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000093 ASTPrint, // Parse ASTs and print them.
94 ASTDump, // Parse ASTs and dump them.
95 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000096 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000097 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000098 ParsePrintCallbacks, // Parse and print each callback.
99 ParseSyntaxOnly, // Parse and perform semantic analysis.
100 ParseNoop, // Parse with noop callbacks.
101 RunPreprocessorOnly, // Just lex, no output.
102 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000103 DumpTokens, // Dump out preprocessed tokens.
104 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000105 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000106 GeneratePCH, // Generate precompiled header.
107 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000108};
109
110static llvm::cl::opt<ProgActions>
111ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
112 llvm::cl::init(ParseSyntaxOnly),
113 llvm::cl::values(
114 clEnumValN(RunPreprocessorOnly, "Eonly",
115 "Just run preprocessor, no output (for timings)"),
116 clEnumValN(PrintPreprocessedInput, "E",
117 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000118 clEnumValN(DumpRawTokens, "dump-raw-tokens",
119 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000120 clEnumValN(RunAnalysis, "analyze",
121 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000122 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000123 "Run preprocessor, dump internal rep of tokens"),
124 clEnumValN(ParseNoop, "parse-noop",
125 "Run parser with noop callbacks (for timings)"),
126 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
127 "Run parser and perform semantic analysis"),
128 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
129 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000130 clEnumValN(EmitHTML, "emit-html",
131 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000132 clEnumValN(ASTPrint, "ast-print",
133 "Build ASTs and then pretty-print them"),
134 clEnumValN(ASTDump, "ast-dump",
135 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000136 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000137 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000138 clEnumValN(PrintDeclContext, "print-decl-contexts",
139 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000140 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000141 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000142 clEnumValN(EmitAssembly, "S",
143 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000144 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000145 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000146 clEnumValN(EmitBC, "emit-llvm-bc",
147 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000148 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
149 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000150 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000151 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000152 clEnumValN(RewriteTest, "rewrite-test",
153 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000154 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000155 "Rewrite ObjC into C (code rewriter example)"),
156 clEnumValN(RewriteMacros, "rewrite-macros",
157 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000158 clEnumValN(RewriteBlocks, "rewrite-blocks",
159 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000160 clEnumValEnd));
161
Ted Kremenekd01eae62007-12-19 19:47:59 +0000162
163static llvm::cl::opt<std::string>
164OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000165 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000166 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000167
Ted Kremenek57f25b22008-12-02 19:57:31 +0000168
169//===----------------------------------------------------------------------===//
170// PTH.
171//===----------------------------------------------------------------------===//
172
173static llvm::cl::opt<std::string>
174TokenCache("token-cache", llvm::cl::value_desc("path"),
175 llvm::cl::desc("Use specified token cache file"));
176
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000177//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000178// Diagnostic Options
179//===----------------------------------------------------------------------===//
180
Ted Kremenek10389cf2007-09-26 19:42:19 +0000181static llvm::cl::opt<bool>
182VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000183 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000184
Ted Kremenekfd75e312008-03-27 06:17:42 +0000185static llvm::cl::opt<std::string>
186HTMLDiag("html-diags",
187 llvm::cl::desc("Generate HTML to report diagnostics"),
188 llvm::cl::value_desc("HTML directory"));
189
Nico Weber0e13eaa2008-08-05 23:33:20 +0000190static llvm::cl::opt<bool>
191NoShowColumn("fno-show-column",
192 llvm::cl::desc("Do not include column number on diagnostics"));
193
194static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000195NoShowLocation("fno-show-source-location",
196 llvm::cl::desc("Do not include source location information with"
197 " diagnostics"));
198
199static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000200NoCaretDiagnostics("fno-caret-diagnostics",
201 llvm::cl::desc("Do not include source line and caret with"
202 " diagnostics"));
203
204
Chris Lattner4b009652007-07-25 00:24:17 +0000205//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000206// C++ Visualization.
207//===----------------------------------------------------------------------===//
208
209static llvm::cl::opt<std::string>
210InheritanceViewCls("cxx-inheritance-view",
211 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000212 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000213
214//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000215// Builtin Options
216//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000217
218static llvm::cl::opt<bool>
219TimeReport("ftime-report",
220 llvm::cl::desc("Print the amount of time each "
221 "phase of compilation takes"));
222
Douglas Gregor23d23262009-02-14 20:49:29 +0000223static llvm::cl::opt<bool>
224Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000225 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000226 "freestanding environment"));
227
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000228static llvm::cl::opt<bool>
229MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000230 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000231 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000232
Douglas Gregor23d23262009-02-14 20:49:29 +0000233//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000234// Language Options
235//===----------------------------------------------------------------------===//
236
237enum LangKind {
238 langkind_unspecified,
239 langkind_c,
240 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000241 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000242 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000243 langkind_cxx,
244 langkind_cxx_cpp,
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000245 langkind_cxx_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000246 langkind_objc,
247 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000248 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000249 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000250 langkind_objcxx_cpp,
251 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000252};
253
Chris Lattner4b009652007-07-25 00:24:17 +0000254static llvm::cl::opt<LangKind>
255BaseLang("x", llvm::cl::desc("Base language to compile"),
256 llvm::cl::init(langkind_unspecified),
257 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
258 clEnumValN(langkind_cxx, "c++", "C++"),
259 clEnumValN(langkind_objc, "objective-c", "Objective C"),
260 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000261 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000262 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000263 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
264 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000265 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000266 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000267 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
268 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000269 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000270 "Preprocessed Objective C++"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000271 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000272 "Precompiled C header"),
273 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000274 "Precompiled Objective-C header"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000275 clEnumValN(langkind_cxx_pch, "c++-header",
276 "Precompiled C++ header"),
Ted Kremenekceacc812009-01-09 00:38:08 +0000277 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
278 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000279 clEnumValEnd));
280
281static llvm::cl::opt<bool>
282LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
283 llvm::cl::Hidden);
284static llvm::cl::opt<bool>
285LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
286 llvm::cl::Hidden);
287
Ted Kremenek11ad8952007-12-05 23:49:08 +0000288/// InitializeBaseLanguage - Handle the -x foo options.
289static void InitializeBaseLanguage() {
290 if (LangObjC)
291 BaseLang = langkind_objc;
292 else if (LangObjCXX)
293 BaseLang = langkind_objcxx;
294}
295
296static LangKind GetLanguage(const std::string &Filename) {
297 if (BaseLang != langkind_unspecified)
298 return BaseLang;
299
300 std::string::size_type DotPos = Filename.rfind('.');
301
302 if (DotPos == std::string::npos) {
303 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000304 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000305 }
306
Ted Kremenek11ad8952007-12-05 23:49:08 +0000307 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
308 // C header: .h
309 // C++ header: .hh or .H;
310 // assembler no preprocessing: .s
311 // assembler: .S
312 if (Ext == "c")
313 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000314 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000315 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000316 else if (Ext == "i")
317 return langkind_c_cpp;
318 else if (Ext == "ii")
319 return langkind_cxx_cpp;
320 else if (Ext == "m")
321 return langkind_objc;
322 else if (Ext == "mi")
323 return langkind_objc_cpp;
324 else if (Ext == "mm" || Ext == "M")
325 return langkind_objcxx;
326 else if (Ext == "mii")
327 return langkind_objcxx_cpp;
328 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
329 Ext == "c++" || Ext == "cp" || Ext == "cxx")
330 return langkind_cxx;
331 else
332 return langkind_c;
333}
334
335
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000336static void InitializeCOptions(LangOptions &Options) {
337 // Do nothing.
338}
339
340static void InitializeObjCOptions(LangOptions &Options) {
341 Options.ObjC1 = Options.ObjC2 = 1;
342}
343
344
345static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000346 // FIXME: implement -fpreprocessed mode.
347 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000348 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000349
350 // Test for 'PCH'.
351 switch (LK) {
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000352 default:
353 break;
354 case langkind_c_pch:
355 LK = langkind_c;
356 PCH = true;
357 break;
358 case langkind_objc_pch:
359 LK = langkind_objc;
360 PCH = true;
361 break;
362 case langkind_cxx_pch:
363 LK = langkind_cxx;
364 PCH = true;
365 break;
366 case langkind_objcxx_pch:
367 LK = langkind_objcxx;
368 PCH = true;
369 break;
Ted Kremenekceacc812009-01-09 00:38:08 +0000370 }
Chris Lattner4b009652007-07-25 00:24:17 +0000371
Ted Kremenek11ad8952007-12-05 23:49:08 +0000372 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000373 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000374 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000375 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000376 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000377 case langkind_c_cpp:
378 NoPreprocess = true;
379 // FALLTHROUGH
380 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000381 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000382 break;
383 case langkind_cxx_cpp:
384 NoPreprocess = true;
385 // FALLTHROUGH
386 case langkind_cxx:
387 Options.CPlusPlus = 1;
388 break;
389 case langkind_objc_cpp:
390 NoPreprocess = true;
391 // FALLTHROUGH
392 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000393 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000394 break;
395 case langkind_objcxx_cpp:
396 NoPreprocess = true;
397 // FALLTHROUGH
398 case langkind_objcxx:
399 Options.ObjC1 = Options.ObjC2 = 1;
400 Options.CPlusPlus = 1;
401 break;
402 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000403
404 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000405}
406
407/// LangStds - Language standards we support.
408enum LangStds {
409 lang_unspecified,
410 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000411 lang_gnu_START,
412 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000413 lang_cxx98, lang_gnucxx98,
414 lang_cxx0x, lang_gnucxx0x
415};
416
417static llvm::cl::opt<LangStds>
418LangStd("std", llvm::cl::desc("Language standard to compile for"),
419 llvm::cl::init(lang_unspecified),
420 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
421 clEnumValN(lang_c89, "c90", "ISO C 1990"),
422 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
423 clEnumValN(lang_c94, "iso9899:199409",
424 "ISO C 1990 with amendment 1"),
425 clEnumValN(lang_c99, "c99", "ISO C 1999"),
426// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
427 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
428// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
429 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000430 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000431 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000432 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000433 clEnumValN(lang_gnu99, "gnu9x",
434 "ISO C 1999 with GNU extensions"),
435 clEnumValN(lang_cxx98, "c++98",
436 "ISO C++ 1998 with amendments"),
437 clEnumValN(lang_gnucxx98, "gnu++98",
438 "ISO C++ 1998 with amendments and GNU "
439 "extensions (default for C++)"),
440 clEnumValN(lang_cxx0x, "c++0x",
441 "Upcoming ISO C++ 200x with amendments"),
442 clEnumValN(lang_gnucxx0x, "gnu++0x",
443 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000444 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000445 clEnumValEnd));
446
447static llvm::cl::opt<bool>
448NoOperatorNames("fno-operator-names",
449 llvm::cl::desc("Do not treat C++ operator name keywords as "
450 "synonyms for operators"));
451
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000452static llvm::cl::opt<bool>
453PascalStrings("fpascal-strings",
454 llvm::cl::desc("Recognize and construct Pascal-style "
455 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000456
457static llvm::cl::opt<bool>
458MSExtensions("fms-extensions",
459 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000460 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000461
462static llvm::cl::opt<bool>
463WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000464 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000465
466static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000467NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000468 llvm::cl::desc("Disallow implicit conversions between "
469 "vectors with a different number of "
470 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000471
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000472static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000473EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
474 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
475 llvm::cl::ZeroOrMore);
476
477static llvm::cl::opt<bool>
478ObjCNonFragileABI("fobjc-nonfragile-abi",
479 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000480
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000481static llvm::cl::opt<bool>
482EmitAllDecls("femit-all-decls",
483 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000484
Daniel Dunbar91692d92008-08-11 17:36:14 +0000485// FIXME: This (and all GCC -f options) really come in -f... and
486// -fno-... forms, and additionally support automagic behavior when
487// they are not defined. For example, -fexceptions defaults to on or
488// off depending on the language. We should support this behavior in
489// some form (perhaps just add a facility for distinguishing when an
490// has its default value from when it has been set to its default
491// value).
492static llvm::cl::opt<bool>
493Exceptions("fexceptions",
494 llvm::cl::desc("Enable support for exception handling."));
495
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000496static llvm::cl::opt<bool>
497GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000498 llvm::cl::desc("Generate output compatible with the standard GNU "
499 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000500
501static llvm::cl::opt<bool>
502NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000503 llvm::cl::desc("Generate output compatible with the NeXT "
504 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000505
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000506
507
508static llvm::cl::opt<bool>
509Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
510
511static llvm::cl::opt<bool>
512Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
513
Chris Lattner738d3f62009-03-02 22:11:07 +0000514static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000515TargetFeatures("mattr", llvm::cl::CommaSeparated,
516 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
517
Douglas Gregor375733c2009-03-10 00:06:19 +0000518static llvm::cl::opt<unsigned>
519TemplateDepth("ftemplate-depth", llvm::cl::init(99),
520 llvm::cl::desc("Maximum depth of recursive template "
521 "instantiation"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000522
Chris Lattner4b009652007-07-25 00:24:17 +0000523// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000524// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000525static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
526 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000527 // Allow the target to set the default the langauge options as it sees fit.
528 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000529
Chris Lattnerf6790a82009-03-03 19:56:18 +0000530 // If there are any -mattr options, pass them to the target for validation and
531 // processing. The driver should have already consolidated all the
532 // target-feature settings and passed them to us in the -mattr list. The
533 // -mattr list is treated by the code generator as a diff against the -mcpu
534 // setting, but the driver should pass all enabled options as "+" settings.
535 // This means that the target should only look at + settings.
536 if (!TargetFeatures.empty()
537 // FIXME: The driver is not quite yet ready for this.
538 && 0) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000539 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000540 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
541 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000542 if (Opt != -1) {
543 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000544 fprintf(stderr, "invalid feature '%s'\n",
545 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000546 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000547 fprintf(stderr, "feature '%s': %s\n",
548 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000549 exit(1);
550 }
551 }
552
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000553 if (Ansi) // "The -ansi option is equivalent to -std=c89."
554 LangStd = lang_c89;
555
Chris Lattner4b009652007-07-25 00:24:17 +0000556 if (LangStd == lang_unspecified) {
557 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000558 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000559 default: assert(0 && "Unknown base language");
560 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000561 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000562 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000563 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000564 case langkind_objc:
565 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000566 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000567 LangStd = lang_gnu99;
568 break;
569 case langkind_cxx:
570 case langkind_cxx_cpp:
571 case langkind_objcxx:
572 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000573 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000574 LangStd = lang_gnucxx98;
575 break;
576 }
577 }
578
579 switch (LangStd) {
580 default: assert(0 && "Unknown language standard!");
581
582 // Fall through from newer standards to older ones. This isn't really right.
583 // FIXME: Enable specifically the right features based on the language stds.
584 case lang_gnucxx0x:
585 case lang_cxx0x:
586 Options.CPlusPlus0x = 1;
587 // FALL THROUGH
588 case lang_gnucxx98:
589 case lang_cxx98:
590 Options.CPlusPlus = 1;
591 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000592 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000593 // FALL THROUGH.
594 case lang_gnu99:
595 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000596 Options.C99 = 1;
597 Options.HexFloats = 1;
598 // FALL THROUGH.
599 case lang_gnu89:
600 Options.BCPLComment = 1; // Only for C99/C++.
601 // FALL THROUGH.
602 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000603 Options.Digraphs = 1; // C94, C99, C++.
604 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000605 case lang_c89:
606 break;
607 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000608
609 if (Options.CPlusPlus) {
610 Options.C99 = 0;
611 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
612 }
Chris Lattner4b009652007-07-25 00:24:17 +0000613
Chris Lattner6ab935b2008-04-05 06:32:51 +0000614 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
615 Options.ImplicitInt = 1;
616 else
617 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000618
619 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
620 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000621 Options.Trigraphs = LangStd < lang_gnu_START;
622 if (Trigraphs.getPosition())
623 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000624
Chris Lattner58d5ba52008-12-05 00:10:44 +0000625 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
626 // even if they are normally on for the target. In GNU modes (e.g.
627 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000628 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
629 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000630 Options.Blocks = 0;
631
Chris Lattner4b009652007-07-25 00:24:17 +0000632 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000633 if (PascalStrings.getPosition())
634 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000635 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000636 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000637 if (NoLaxVectorConversions.getPosition())
638 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000639 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000640 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000641 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000642
Douglas Gregor23d23262009-02-14 20:49:29 +0000643 if (Freestanding)
644 Options.Freestanding = 1;
645
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000646 Options.MathErrno = MathErrno;
647
Douglas Gregor375733c2009-03-10 00:06:19 +0000648 Options.InstantiationDepth = TemplateDepth;
649
Chris Lattnerddae7102008-12-04 22:54:33 +0000650 // Override the default runtime if the user requested it.
651 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000652 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000653 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000654 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000655
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000656 if (ObjCNonFragileABI)
657 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000658
659 if (EmitAllDecls)
660 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000661}
662
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000663static llvm::cl::opt<bool>
664ObjCExclusiveGC("fobjc-gc-only",
665 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000666 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000667
668static llvm::cl::opt<bool>
669ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000670 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000671
672void InitializeGCMode(LangOptions &Options) {
673 if (ObjCExclusiveGC)
674 Options.setGCMode(LangOptions::GCOnly);
675 else if (ObjCEnableGC)
676 Options.setGCMode(LangOptions::HybridGC);
677}
678
Chris Lattner4b009652007-07-25 00:24:17 +0000679//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000680// Target Triple Processing.
681//===----------------------------------------------------------------------===//
682
683static llvm::cl::opt<std::string>
684TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000685 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000686
Chris Lattnerfc457002008-03-05 01:18:20 +0000687static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000688Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000689
Chris Lattner2b168e02008-09-30 01:13:12 +0000690static llvm::cl::opt<std::string>
691MacOSVersionMin("mmacosx-version-min",
692 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
693
Chris Lattner01de9c82008-09-30 20:16:56 +0000694// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
695// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
696static void HandleMacOSVersionMin(std::string &Triple) {
697 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
698 if (DarwinDashIdx == std::string::npos) {
699 fprintf(stderr,
700 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
701 exit(1);
702 }
703 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
704
Chris Lattner01de9c82008-09-30 20:16:56 +0000705 // Remove the number.
706 Triple.resize(DarwinNumIdx);
707
708 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
709 bool MacOSVersionMinIsInvalid = false;
710 int VersionNum = 0;
711 if (MacOSVersionMin.size() < 4 ||
712 MacOSVersionMin.substr(0, 3) != "10." ||
713 !isdigit(MacOSVersionMin[3])) {
714 MacOSVersionMinIsInvalid = true;
715 } else {
716 const char *Start = MacOSVersionMin.c_str()+3;
717 char *End = 0;
718 VersionNum = (int)strtol(Start, &End, 10);
719
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000720 // The version number must be in the range 0-9.
721 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
722
Chris Lattner01de9c82008-09-30 20:16:56 +0000723 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
724 Triple += llvm::itostr(VersionNum+4);
725
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000726 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
727 // Add the period piece (.7) to the end of the triple. This gives us
728 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000729 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000730 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
731 MacOSVersionMinIsInvalid = true;
732 }
733 }
734
735 if (MacOSVersionMinIsInvalid) {
736 fprintf(stderr,
737 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
738 MacOSVersionMin.c_str());
739 exit(1);
740 }
741}
742
743/// CreateTargetTriple - Process the various options that affect the target
744/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000745static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000746 // Initialize base triple. If a -triple option has been specified, use
747 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000748 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000749 if (Triple.empty()) {
750 Triple = LLVM_HOSTTRIPLE;
751
Daniel Dunbar81caece2008-12-12 18:34:35 +0000752 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
753 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
754 Triple[2] == '8' && Triple[3] == '6')
755 Triple[1] = '3';
756
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000757 // On darwin, we want to update the version to match that of the
758 // host.
759 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
760 if (DarwinDashIdx != std::string::npos) {
761 Triple.resize(DarwinDashIdx + strlen("-darwin"));
762
Daniel Dunbar81caece2008-12-12 18:34:35 +0000763 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000764 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000765 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000766 }
767 }
Ted Kremenek40499482007-12-03 22:06:55 +0000768
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000769 // If -arch foo was specified, remove the architecture from the triple we have
770 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000771 if (!Arch.empty()) {
772 // Decompose the base triple into "arch" and suffix.
773 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000774
Chris Lattner2b168e02008-09-30 01:13:12 +0000775 if (FirstDashIdx == std::string::npos) {
776 fprintf(stderr,
777 "Malformed target triple: \"%s\" ('-' could not be found).\n",
778 Triple.c_str());
779 exit(1);
780 }
Ted Kremenek40499482007-12-03 22:06:55 +0000781
Chris Lattner2b168e02008-09-30 01:13:12 +0000782 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
783 }
784
785 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
786 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000787 if (!MacOSVersionMin.empty())
788 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000789
Chris Lattner2b168e02008-09-30 01:13:12 +0000790 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000791}
792
793//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000794// Preprocessor Initialization
795//===----------------------------------------------------------------------===//
796
797// FIXME: Preprocessor builtins to support.
798// -A... - Play with #assertions
799// -undef - Undefine all predefined macros
800
801static llvm::cl::list<std::string>
802D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
803 llvm::cl::desc("Predefine the specified macro"));
804static llvm::cl::list<std::string>
805U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
806 llvm::cl::desc("Undefine the specified macro"));
807
Chris Lattner008da782008-01-10 01:53:41 +0000808static llvm::cl::list<std::string>
809ImplicitIncludes("include", llvm::cl::value_desc("file"),
810 llvm::cl::desc("Include file before parsing"));
811
812
Chris Lattner4b009652007-07-25 00:24:17 +0000813// Append a #define line to Buf for Macro. Macro should be of the form XXX,
814// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
815// "#define XXX Y z W". To get a #define with no value, use "XXX=".
816static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
817 const char *Command = "#define ") {
818 Buf.insert(Buf.end(), Command, Command+strlen(Command));
819 if (const char *Equal = strchr(Macro, '=')) {
820 // Turn the = into ' '.
821 Buf.insert(Buf.end(), Macro, Equal);
822 Buf.push_back(' ');
823 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
824 } else {
825 // Push "macroname 1".
826 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
827 Buf.push_back(' ');
828 Buf.push_back('1');
829 }
830 Buf.push_back('\n');
831}
832
Chris Lattner008da782008-01-10 01:53:41 +0000833/// AddImplicitInclude - Add an implicit #include of the specified file to the
834/// predefines buffer.
835static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
836 const char *Inc = "#include \"";
837 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
838 Buf.insert(Buf.end(), File.begin(), File.end());
839 Buf.push_back('"');
840 Buf.push_back('\n');
841}
842
Chris Lattner4b009652007-07-25 00:24:17 +0000843
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000844/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000845/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000846///
Chris Lattner9d818a22008-04-19 23:25:44 +0000847static bool InitializePreprocessor(Preprocessor &PP,
848 bool InitializeSourceMgr,
849 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000850 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000851
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000852 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000853 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000854
855 if (InitializeSourceMgr) {
856 if (InFile != "-") {
857 const FileEntry *File = FileMgr.getFile(InFile);
858 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000859 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000860 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000861 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000862 }
863 } else {
864 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
865 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000866 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000867 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000868 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000869 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000870 }
Chris Lattner4b009652007-07-25 00:24:17 +0000871 }
Sam Bishop61a20782008-04-14 14:41:57 +0000872
Chris Lattner47b6a162008-04-19 23:09:31 +0000873 std::vector<char> PredefineBuffer;
874
Chris Lattner4b009652007-07-25 00:24:17 +0000875 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000876 unsigned d = 0, D = D_macros.size();
877 unsigned u = 0, U = U_macros.size();
878 while (d < D || u < U) {
879 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
880 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
881 else
882 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
883 }
884
Chris Lattner008da782008-01-10 01:53:41 +0000885 // FIXME: Read any files specified by -imacros.
886
887 // Add implicit #includes from -include.
888 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
889 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000890
Chris Lattner47b6a162008-04-19 23:09:31 +0000891 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000892 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000893 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000894
895 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000896 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000897}
898
899//===----------------------------------------------------------------------===//
900// Preprocessor include path information.
901//===----------------------------------------------------------------------===//
902
903// This tool exports a large number of command line options to control how the
904// preprocessor searches for header files. At root, however, the Preprocessor
905// object takes a very simple interface: a list of directories to search for
906//
907// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000908// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000909//
Chris Lattner008da782008-01-10 01:53:41 +0000910// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000911
912static llvm::cl::opt<bool>
913nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
914
915// Various command line options. These four add directories to each chain.
916static llvm::cl::list<std::string>
917F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
918 llvm::cl::desc("Add directory to framework include search path"));
919static llvm::cl::list<std::string>
920I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
921 llvm::cl::desc("Add directory to include search path"));
922static llvm::cl::list<std::string>
923idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
924 llvm::cl::desc("Add directory to AFTER include search path"));
925static llvm::cl::list<std::string>
926iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
927 llvm::cl::desc("Add directory to QUOTE include search path"));
928static llvm::cl::list<std::string>
929isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
930 llvm::cl::desc("Add directory to SYSTEM include search path"));
931
932// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
933static llvm::cl::list<std::string>
934iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
935 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
936static llvm::cl::list<std::string>
937iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
938 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
939static llvm::cl::list<std::string>
940iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
941 llvm::cl::Prefix,
942 llvm::cl::desc("Set directory to include search path with prefix"));
943
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000944static llvm::cl::opt<std::string>
945isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
946 llvm::cl::desc("Set the system root directory (usually /)"));
947
Chris Lattner4b009652007-07-25 00:24:17 +0000948// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +0000949
Chris Lattner4b009652007-07-25 00:24:17 +0000950/// InitializeIncludePaths - Process the -I options and set them in the
951/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +0000952void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
953 FileManager &FM, const LangOptions &Lang) {
954 InitHeaderSearch Init(Headers, Verbose, isysroot);
955
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000956 // Handle -I... and -F... options, walking the lists in parallel.
957 unsigned Iidx = 0, Fidx = 0;
958 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
959 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +0000960 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000961 ++Iidx;
962 } else {
Nico Weber770e3882008-08-22 09:25:22 +0000963 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000964 ++Fidx;
965 }
966 }
Chris Lattner4b009652007-07-25 00:24:17 +0000967
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000968 // Consume what's left from whatever list was longer.
969 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +0000970 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000971 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +0000972 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000973
974 // Handle -idirafter... options.
975 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000976 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
977 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000978
979 // Handle -iquote... options.
980 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000981 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000982
983 // Handle -isystem... options.
984 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000985 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000986
987 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
988 // parallel, processing the values in order of occurance to get the right
989 // prefixes.
990 {
991 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
992 unsigned iprefix_idx = 0;
993 unsigned iwithprefix_idx = 0;
994 unsigned iwithprefixbefore_idx = 0;
995 bool iprefix_done = iprefix_vals.empty();
996 bool iwithprefix_done = iwithprefix_vals.empty();
997 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
998 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
999 if (!iprefix_done &&
1000 (iwithprefix_done ||
1001 iprefix_vals.getPosition(iprefix_idx) <
1002 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1003 (iwithprefixbefore_done ||
1004 iprefix_vals.getPosition(iprefix_idx) <
1005 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1006 Prefix = iprefix_vals[iprefix_idx];
1007 ++iprefix_idx;
1008 iprefix_done = iprefix_idx == iprefix_vals.size();
1009 } else if (!iwithprefix_done &&
1010 (iwithprefixbefore_done ||
1011 iwithprefix_vals.getPosition(iwithprefix_idx) <
1012 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001013 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1014 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001015 ++iwithprefix_idx;
1016 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1017 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001018 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1019 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001020 ++iwithprefixbefore_idx;
1021 iwithprefixbefore_done =
1022 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1023 }
1024 }
1025 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001026
Nico Weber770e3882008-08-22 09:25:22 +00001027 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001028
Daniel Dunbar4e604292009-02-21 20:52:41 +00001029 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001030 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001031 llvm::sys::Path::GetMainExecutable(Argv0,
1032 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001033 if (!MainExecutablePath.isEmpty()) {
1034 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1035 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001036
1037 // Get foo/lib/clang/1.0/include
1038 //
1039 // FIXME: Don't embed version here.
1040 MainExecutablePath.appendComponent("lib");
1041 MainExecutablePath.appendComponent("clang");
1042 MainExecutablePath.appendComponent("1.0");
1043 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001044
1045 // We pass true to ignore sysroot so that we *always* look for clang headers
1046 // relative to our executable, never relative to -isysroot.
1047 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1048 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001049 }
1050
Nico Weber770e3882008-08-22 09:25:22 +00001051 if (!nostdinc)
1052 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001053
1054 // Now that we have collected all of the include paths, merge them all
1055 // together and tell the preprocessor about them.
1056
Nico Weber770e3882008-08-22 09:25:22 +00001057 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001058}
1059
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001060//===----------------------------------------------------------------------===//
1061// Driver PreprocessorFactory - For lazily generating preprocessors ...
1062//===----------------------------------------------------------------------===//
1063
1064namespace {
1065class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001066 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001067 Diagnostic &Diags;
1068 const LangOptions &LangInfo;
1069 TargetInfo &Target;
1070 SourceManager &SourceMgr;
1071 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001072 bool InitializeSourceMgr;
1073
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001074public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001075 DriverPreprocessorFactory(const std::string &infile,
1076 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001077 TargetInfo &target, SourceManager &SM,
1078 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001079 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1080 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1081
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001082
1083 virtual ~DriverPreprocessorFactory() {}
1084
1085 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001086 llvm::OwningPtr<PTHManager> PTHMgr;
1087
1088 // Use PTH?
1089 if (!TokenCache.empty())
Ted Kremenek3d145552009-01-28 20:49:33 +00001090 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001091
1092 // Create the Preprocessor.
1093 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1094 SourceMgr, HeaderInfo,
1095 PTHMgr.get()));
1096
1097 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1098 // That argument is used as the IdentifierInfoLookup argument to
1099 // IdentifierTable's ctor.
1100 if (PTHMgr) {
1101 PTHMgr->setPreprocessor(PP.get());
1102 PP->setPTHManager(PTHMgr.take());
1103 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001104
Chris Lattner9d818a22008-04-19 23:25:44 +00001105 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001106 return NULL;
1107 }
1108
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001109 /// FIXME: PP can only handle one callback
1110 if (ProgAction != PrintPreprocessedInput) {
1111 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001112 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001113 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001114 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001115 return NULL;
1116 }
1117 }
1118
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001119 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001120 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001121 }
1122};
1123}
Chris Lattner4b009652007-07-25 00:24:17 +00001124
Chris Lattner4b009652007-07-25 00:24:17 +00001125//===----------------------------------------------------------------------===//
1126// Basic Parser driver
1127//===----------------------------------------------------------------------===//
1128
Chris Lattner9d818a22008-04-19 23:25:44 +00001129static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001130 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001131 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001132
1133 // Parsing the specified input file.
1134 P.ParseTranslationUnit();
1135 delete PA;
1136}
1137
1138//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001139// Code generation options
1140//===----------------------------------------------------------------------===//
1141
1142static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001143GenerateDebugInfo("g",
1144 llvm::cl::desc("Generate source level debug information"));
1145
1146static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001147OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001148
1149// It might be nice to add bounds to the CommandLine library directly.
1150struct OptLevelParser : public llvm::cl::parser<unsigned> {
1151 bool parse(llvm::cl::Option &O, const char *ArgName,
1152 const std::string &Arg, unsigned &Val) {
1153 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1154 return true;
1155 // FIXME: Support -O4.
1156 if (Val > 3)
1157 return O.error(": '" + Arg + "' invalid optimization level!");
1158 return false;
1159 }
1160};
1161static llvm::cl::opt<unsigned, false, OptLevelParser>
1162OptLevel("O", llvm::cl::Prefix,
1163 llvm::cl::desc("Optimization level"),
1164 llvm::cl::init(0));
1165
Daniel Dunbar9101a632009-02-17 19:47:34 +00001166static llvm::cl::opt<std::string>
1167TargetCPU("mcpu",
1168 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1169
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001170static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001171 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001172 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001173 if (OptSize) {
1174 // -Os implies -O2
1175 // FIXME: Diagnose conflicting options.
1176 Opts.OptimizationLevel = 2;
1177 } else {
1178 Opts.OptimizationLevel = OptLevel;
1179 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001180
1181 // FIXME: There are llvm-gcc options to control these selectively.
1182 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1183 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Daniel Dunbar6670e332009-02-15 20:00:15 +00001184 Opts.SimplifyLibCalls = !Freestanding;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001185
1186#ifdef NDEBUG
1187 Opts.VerifyModule = 0;
1188#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001189
1190 Opts.CPU = TargetCPU;
1191 Opts.Features.insert(Opts.Features.end(),
1192 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001193
1194 // Handle -ftime-report.
1195 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001196}
1197
1198//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001199// Main driver
1200//===----------------------------------------------------------------------===//
1201
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001202/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001203/// action. These consumers can operate on both ASTs that are freshly
1204/// parsed from source files as well as those deserialized from Bitcode.
1205/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001206static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001207 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001208 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001209 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001210 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001211 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001212 default:
1213 return NULL;
1214
1215 case ASTPrint:
1216 return CreateASTPrinter();
1217
1218 case ASTDump:
1219 return CreateASTDumper();
1220
1221 case ASTView:
1222 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001223
Chris Lattner7f902922009-02-18 01:20:05 +00001224 case PrintDeclContext:
1225 return CreateDeclContextPrinter();
1226
1227 case EmitHTML:
1228 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001229
Chris Lattner7f902922009-02-18 01:20:05 +00001230 case InheritanceView:
1231 return CreateInheritanceViewer(InheritanceViewCls);
1232
1233 case TestSerialization:
1234 return CreateSerializationTest(Diag, FileMgr);
1235
1236 case EmitAssembly:
1237 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001238 case EmitBC:
1239 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001240 BackendAction Act;
1241 if (ProgAction == EmitAssembly)
1242 Act = Backend_EmitAssembly;
1243 else if (ProgAction == EmitLLVM)
1244 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001245 else if (ProgAction == EmitLLVMOnly)
1246 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001247 else
1248 Act = Backend_EmitBC;
1249
1250 CompileOptions Opts;
1251 InitializeCompileOptions(Opts);
1252 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001253 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001254 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001255
Chris Lattner7f902922009-02-18 01:20:05 +00001256 case SerializeAST:
1257 // FIXME: Allow user to tailor where the file is written.
1258 return CreateASTSerializer(InFile, OutputFile, Diag);
1259
1260 case RewriteObjC:
1261 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001262
Chris Lattner7f902922009-02-18 01:20:05 +00001263 case RewriteBlocks:
1264 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1265
1266 case RunAnalysis:
1267 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001268 }
1269}
1270
Chris Lattner4b009652007-07-25 00:24:17 +00001271/// ProcessInputFile - Process a single input file with the specified state.
1272///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001273static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001274 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001275 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001276 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001277
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001278 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001279 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001280 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1281 PP.getFileManager(), PP.getLangOptions(),
1282 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001283
1284 if (!Consumer) {
1285 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001286 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001287 return;
1288 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001289
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001290 break;
1291
Chris Lattneraf669fb2008-10-12 05:03:36 +00001292 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001293 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001294 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001295 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001296 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001297 RawLex.SetKeepWhitespaceMode(true);
1298
1299 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001300 RawLex.LexFromRawLexer(RawTok);
1301 while (RawTok.isNot(tok::eof)) {
1302 PP.DumpToken(RawTok, true);
1303 fprintf(stderr, "\n");
1304 RawLex.LexFromRawLexer(RawTok);
1305 }
1306 ClearSourceMgr = true;
1307 break;
1308 }
Chris Lattner4b009652007-07-25 00:24:17 +00001309 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001310 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001311 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001312 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001313 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001314 do {
1315 PP.Lex(Tok);
1316 PP.DumpToken(Tok, true);
1317 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001318 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001319 ClearSourceMgr = true;
1320 break;
1321 }
1322 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001323 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001324 Token Tok;
1325 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001326 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001327 do {
1328 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001329 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001330 ClearSourceMgr = true;
1331 break;
1332 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001333
1334 case GeneratePCH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001335 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001336 CacheTokens(PP, OutputFile);
1337 ClearSourceMgr = true;
1338 break;
1339 }
Chris Lattner4b009652007-07-25 00:24:17 +00001340
Chris Lattnerefe33382009-02-18 01:51:21 +00001341 case PrintPreprocessedInput: { // -E mode.
1342 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001343 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001344 ClearSourceMgr = true;
1345 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001346 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001347
Chris Lattnerefe33382009-02-18 01:51:21 +00001348 case ParseNoop: { // -parse-noop
1349 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001350 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001351 ClearSourceMgr = true;
1352 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001353 }
Chris Lattner4b009652007-07-25 00:24:17 +00001354
Chris Lattnerefe33382009-02-18 01:51:21 +00001355 case ParsePrintCallbacks: {
1356 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001357 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001358 ClearSourceMgr = true;
1359 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001360 }
1361
1362 case ParseSyntaxOnly: { // -fsyntax-only
1363 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001364 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001365 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001366 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001367
1368 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001369 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001370 ClearSourceMgr = true;
1371 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001372
Chris Lattnerefe33382009-02-18 01:51:21 +00001373 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001374 DoRewriteTest(PP, InFile, OutputFile);
1375 ClearSourceMgr = true;
1376 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001377 }
Chris Lattnerefe33382009-02-18 01:51:21 +00001378 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001379
1380 if (Consumer) {
1381 TranslationUnit *TU = 0;
1382 if (DisableFree) {
1383 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1384 PP.getSourceManager(),
1385 PP.getTargetInfo(),
1386 PP.getIdentifierTable(),
1387 PP.getSelectorTable(),
1388 /* FreeMemory = */ false);
1389 TU = new TranslationUnit(*Context);
1390 }
1391 ParseAST(PP, Consumer.get(), TU, Stats);
1392 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001393
1394 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001395 if (CheckDiagnostics(PP))
1396 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001397
Chris Lattner4b009652007-07-25 00:24:17 +00001398 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001399 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001400 PP.PrintStats();
1401 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001402 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001403 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001404 fprintf(stderr, "\n");
1405 }
1406
1407 // For a multi-file compilation, some things are ok with nuking the source
1408 // manager tables, other require stable fileid/macroid's across multiple
1409 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001410 if (ClearSourceMgr)
1411 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001412
1413 if (DisableFree)
1414 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001415}
1416
Ted Kremenek80d53372007-12-12 23:41:08 +00001417static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1418 FileManager& FileMgr) {
1419
1420 if (VerifyDiagnostics) {
1421 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1422 exit (1);
1423 }
1424
1425 llvm::sys::Path Filename(InFile);
1426
1427 if (!Filename.isValid()) {
1428 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1429 exit (1);
1430 }
1431
Ted Kremenek863b01f2008-04-23 16:25:39 +00001432 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001433
1434 if (!TU) {
1435 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1436 InFile.c_str());
1437 exit (1);
1438 }
1439
Ted Kremenekab749372007-12-19 19:27:38 +00001440 // Observe that we use the source file name stored in the deserialized
1441 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001442 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001443 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001444 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001445
Ted Kremenek80d53372007-12-12 23:41:08 +00001446 if (!Consumer) {
1447 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1448 exit (1);
1449 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001450
Ted Kremenek863b01f2008-04-23 16:25:39 +00001451 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001452
Chris Lattner8d72ee02008-02-06 01:42:25 +00001453 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001454 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1455 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001456}
1457
1458
Chris Lattner4b009652007-07-25 00:24:17 +00001459static llvm::cl::list<std::string>
1460InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1461
Ted Kremenek80d53372007-12-12 23:41:08 +00001462static bool isSerializedFile(const std::string& InFile) {
1463 if (InFile.size() < 4)
1464 return false;
1465
1466 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00001467 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00001468}
1469
Chris Lattner4b009652007-07-25 00:24:17 +00001470
1471int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001472 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001473 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001474 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001475 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001476
Chris Lattnerefe33382009-02-18 01:51:21 +00001477 if (TimeReport)
1478 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1479
Chris Lattner4b009652007-07-25 00:24:17 +00001480 // If no input was specified, read from stdin.
1481 if (InputFilenames.empty())
1482 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001483
Chris Lattner4b009652007-07-25 00:24:17 +00001484 // Create a file manager object to provide access to and cache the filesystem.
1485 FileManager FileMgr;
1486
Ted Kremenekb240e822007-12-11 23:28:38 +00001487 // Create the diagnostic client for reporting errors or for
1488 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001489 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001490
Ted Kremenek5c341732008-08-07 17:49:57 +00001491 if (!VerifyDiagnostics) {
1492 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001493 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1494 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001495 !NoCaretDiagnostics,
1496 !NoShowLocation);
Ted Kremenek5c341732008-08-07 17:49:57 +00001497 } else {
1498 // When checking diagnostics, just buffer them up.
1499 TextDiagClient = new TextDiagnosticBuffer();
1500
1501 if (InputFilenames.size() != 1) {
1502 fprintf(stderr,
1503 "-verify only works on single input files for now.\n");
1504 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001505 }
1506 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001507
Chris Lattner4b009652007-07-25 00:24:17 +00001508 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001509 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1510 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001511 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001512 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001513
Chris Lattner45a56e02007-12-05 23:24:17 +00001514 // -I- is a deprecated GCC feature, scan for it and reject it.
1515 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1516 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001517 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001518 I_dirs.erase(I_dirs.begin()+i);
1519 --i;
1520 }
1521 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001522
1523 // Get information about the target being compiled for.
1524 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001525 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1526
Chris Lattner2c77d852008-03-14 06:12:05 +00001527 if (Target == 0) {
1528 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1529 Triple.c_str());
1530 fprintf(stderr, "Please use -triple or -arch.\n");
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001531 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001532 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001533
Daniel Dunbar9c321102009-01-20 23:17:32 +00001534 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001535 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001536
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001537 llvm::OwningPtr<SourceManager> SourceMgr;
1538
Chris Lattner4b009652007-07-25 00:24:17 +00001539 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001540 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001541
Ted Kremenek5c341732008-08-07 17:49:57 +00001542 if (isSerializedFile(InFile)) {
1543 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001544 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00001545 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001546 }
Chris Lattner2b989562009-03-04 21:40:56 +00001547
1548 /// Create a SourceManager object. This tracks and owns all the file
1549 /// buffers allocated to a translation unit.
1550 if (!SourceMgr)
1551 SourceMgr.reset(new SourceManager());
1552 else
1553 SourceMgr->clearIDTables();
1554
1555 // Initialize language options, inferring file types from input filenames.
1556 LangOptions LangInfo;
1557 InitializeBaseLanguage();
1558 LangKind LK = GetLanguage(InFile);
1559 bool PCH = InitializeLangOptions(LangInfo, LK);
1560 InitializeGCMode(LangInfo);
1561 InitializeLanguageStandard(LangInfo, LK, Target.get());
1562
1563 // Process the -I options and set them in the HeaderInfo.
1564 HeaderSearch HeaderInfo(FileMgr);
1565
1566 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1567
1568 // Set up the preprocessor with these options.
1569 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1570 *SourceMgr.get(), HeaderInfo);
1571
1572 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1573
1574 if (!PP)
1575 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001576
Chris Lattner2b989562009-03-04 21:40:56 +00001577 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1578 // always reset to using TextDiagClient.
1579 llvm::OwningPtr<DiagnosticClient> TmpClient;
1580
1581 if (!HTMLDiag.empty()) {
1582 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1583 &PPFactory));
1584 Diags.setClient(TmpClient.get());
Ted Kremenek80d53372007-12-12 23:41:08 +00001585 }
Chris Lattner2b989562009-03-04 21:40:56 +00001586 else
1587 Diags.setClient(TextDiagClient);
1588
1589 // Process the source file.
1590 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1591
1592 HeaderInfo.ClearFileInfo();
Chris Lattner4b009652007-07-25 00:24:17 +00001593 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001594
Mike Stump91d01352009-01-28 02:43:35 +00001595 if (Verbose)
1596 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1597 " hosted on " LLVM_HOSTTRIPLE "\n");
1598
Ted Kremenekec6c5252008-08-07 18:13:12 +00001599 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001600 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1601 (NumDiagnostics == 1 ? "" : "s"));
1602
1603 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001604 FileMgr.PrintStats();
1605 fprintf(stderr, "\n");
1606 }
1607
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001608 // If verifying diagnostics and we reached here, all is well.
1609 if (VerifyDiagnostics)
1610 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001611
1612 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001613
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001614 // Managed static deconstruction. Useful for making things like
1615 // -time-passes usable.
1616 llvm::llvm_shutdown();
1617
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001618 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001619}