blob: 6fdd18af6bd62cbd186d97abd1fe2b7de4755157 [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"
Chris Lattnerefe33382009-02-18 01:51:21 +000053#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000054#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000055#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000056#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000057using namespace clang;
58
59//===----------------------------------------------------------------------===//
60// Global options.
61//===----------------------------------------------------------------------===//
62
Chris Lattnerefe33382009-02-18 01:51:21 +000063/// ClangFrontendTimer - The front-end activities should charge time to it with
64/// TimeRegion. The -ftime-report option controls whether this will do
65/// anything.
66llvm::Timer *ClangFrontendTimer = 0;
67
Daniel Dunbar4efedde2008-10-16 16:54:18 +000068static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000069
Chris Lattner4b009652007-07-25 00:24:17 +000070static llvm::cl::opt<bool>
71Verbose("v", llvm::cl::desc("Enable verbose output"));
72static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000073Stats("print-stats",
74 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000075static llvm::cl::opt<bool>
76DisableFree("disable-free",
77 llvm::cl::desc("Disable freeing of memory on exit"),
78 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000079
80enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000081 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000082 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000083 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000084 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000085 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000086 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000087 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000088 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +000089 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek397de012007-12-13 00:37:31 +000090 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000091 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000092 ASTPrint, // Parse ASTs and print them.
93 ASTDump, // Parse ASTs and dump them.
94 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000095 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000096 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000097 ParsePrintCallbacks, // Parse and print each callback.
98 ParseSyntaxOnly, // Parse and perform semantic analysis.
99 ParseNoop, // Parse with noop callbacks.
100 RunPreprocessorOnly, // Just lex, no output.
101 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000102 DumpTokens, // Dump out preprocessed tokens.
103 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000104 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000105 GeneratePCH, // Generate precompiled header.
106 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000107};
108
109static llvm::cl::opt<ProgActions>
110ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
111 llvm::cl::init(ParseSyntaxOnly),
112 llvm::cl::values(
113 clEnumValN(RunPreprocessorOnly, "Eonly",
114 "Just run preprocessor, no output (for timings)"),
115 clEnumValN(PrintPreprocessedInput, "E",
116 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000117 clEnumValN(DumpRawTokens, "dump-raw-tokens",
118 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000119 clEnumValN(RunAnalysis, "analyze",
120 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000121 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000122 "Run preprocessor, dump internal rep of tokens"),
123 clEnumValN(ParseNoop, "parse-noop",
124 "Run parser with noop callbacks (for timings)"),
125 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
126 "Run parser and perform semantic analysis"),
127 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
128 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000129 clEnumValN(EmitHTML, "emit-html",
130 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000131 clEnumValN(ASTPrint, "ast-print",
132 "Build ASTs and then pretty-print them"),
133 clEnumValN(ASTDump, "ast-dump",
134 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000135 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000136 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000137 clEnumValN(PrintDeclContext, "print-decl-contexts",
138 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000139 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000140 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000141 clEnumValN(EmitAssembly, "S",
142 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000143 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000144 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000145 clEnumValN(EmitBC, "emit-llvm-bc",
146 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000147 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
148 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000149 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000150 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000151 clEnumValN(RewriteTest, "rewrite-test",
152 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000153 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000154 "Rewrite ObjC into C (code rewriter example)"),
155 clEnumValN(RewriteMacros, "rewrite-macros",
156 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000157 clEnumValN(RewriteBlocks, "rewrite-blocks",
158 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000159 clEnumValEnd));
160
Ted Kremenekd01eae62007-12-19 19:47:59 +0000161
162static llvm::cl::opt<std::string>
163OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000164 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000165 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000166
167//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000168// Code Generator Options
169//===----------------------------------------------------------------------===//
170static llvm::cl::opt<bool>
171GenerateDebugInfo("g",
172 llvm::cl::desc("Generate source level debug information"));
173
Ted Kremenek57f25b22008-12-02 19:57:31 +0000174
175//===----------------------------------------------------------------------===//
176// PTH.
177//===----------------------------------------------------------------------===//
178
179static llvm::cl::opt<std::string>
180TokenCache("token-cache", llvm::cl::value_desc("path"),
181 llvm::cl::desc("Use specified token cache file"));
182
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000183//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000184// Diagnostic Options
185//===----------------------------------------------------------------------===//
186
Ted Kremenek10389cf2007-09-26 19:42:19 +0000187static llvm::cl::opt<bool>
188VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000189 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000190
Ted Kremenekfd75e312008-03-27 06:17:42 +0000191static llvm::cl::opt<std::string>
192HTMLDiag("html-diags",
193 llvm::cl::desc("Generate HTML to report diagnostics"),
194 llvm::cl::value_desc("HTML directory"));
195
Nico Weber0e13eaa2008-08-05 23:33:20 +0000196static llvm::cl::opt<bool>
197NoShowColumn("fno-show-column",
198 llvm::cl::desc("Do not include column number on diagnostics"));
199
200static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000201NoShowLocation("fno-show-source-location",
202 llvm::cl::desc("Do not include source location information with"
203 " diagnostics"));
204
205static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000206NoCaretDiagnostics("fno-caret-diagnostics",
207 llvm::cl::desc("Do not include source line and caret with"
208 " diagnostics"));
209
210
Chris Lattner4b009652007-07-25 00:24:17 +0000211//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000212// C++ Visualization.
213//===----------------------------------------------------------------------===//
214
215static llvm::cl::opt<std::string>
216InheritanceViewCls("cxx-inheritance-view",
217 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000218 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000219
220//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000221// Builtin Options
222//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000223
224static llvm::cl::opt<bool>
225TimeReport("ftime-report",
226 llvm::cl::desc("Print the amount of time each "
227 "phase of compilation takes"));
228
Douglas Gregor23d23262009-02-14 20:49:29 +0000229static llvm::cl::opt<bool>
230Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000231 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000232 "freestanding environment"));
233
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000234static llvm::cl::opt<bool>
235MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000236 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000237 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000238
Douglas Gregor23d23262009-02-14 20:49:29 +0000239//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000240// Language Options
241//===----------------------------------------------------------------------===//
242
243enum LangKind {
244 langkind_unspecified,
245 langkind_c,
246 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000247 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000248 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000249 langkind_cxx,
250 langkind_cxx_cpp,
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000251 langkind_cxx_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000252 langkind_objc,
253 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000254 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000255 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000256 langkind_objcxx_cpp,
257 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000258};
259
Chris Lattner4b009652007-07-25 00:24:17 +0000260static llvm::cl::opt<LangKind>
261BaseLang("x", llvm::cl::desc("Base language to compile"),
262 llvm::cl::init(langkind_unspecified),
263 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
264 clEnumValN(langkind_cxx, "c++", "C++"),
265 clEnumValN(langkind_objc, "objective-c", "Objective C"),
266 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000267 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000268 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000269 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
270 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000271 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000272 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000273 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
274 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000275 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000276 "Preprocessed Objective C++"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000277 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000278 "Precompiled C header"),
279 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000280 "Precompiled Objective-C header"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000281 clEnumValN(langkind_cxx_pch, "c++-header",
282 "Precompiled C++ header"),
Ted Kremenekceacc812009-01-09 00:38:08 +0000283 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
284 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000285 clEnumValEnd));
286
287static llvm::cl::opt<bool>
288LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
289 llvm::cl::Hidden);
290static llvm::cl::opt<bool>
291LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
292 llvm::cl::Hidden);
293
Ted Kremenek11ad8952007-12-05 23:49:08 +0000294/// InitializeBaseLanguage - Handle the -x foo options.
295static void InitializeBaseLanguage() {
296 if (LangObjC)
297 BaseLang = langkind_objc;
298 else if (LangObjCXX)
299 BaseLang = langkind_objcxx;
300}
301
302static LangKind GetLanguage(const std::string &Filename) {
303 if (BaseLang != langkind_unspecified)
304 return BaseLang;
305
306 std::string::size_type DotPos = Filename.rfind('.');
307
308 if (DotPos == std::string::npos) {
309 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000310 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000311 }
312
Ted Kremenek11ad8952007-12-05 23:49:08 +0000313 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
314 // C header: .h
315 // C++ header: .hh or .H;
316 // assembler no preprocessing: .s
317 // assembler: .S
318 if (Ext == "c")
319 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000320 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000321 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000322 else if (Ext == "i")
323 return langkind_c_cpp;
324 else if (Ext == "ii")
325 return langkind_cxx_cpp;
326 else if (Ext == "m")
327 return langkind_objc;
328 else if (Ext == "mi")
329 return langkind_objc_cpp;
330 else if (Ext == "mm" || Ext == "M")
331 return langkind_objcxx;
332 else if (Ext == "mii")
333 return langkind_objcxx_cpp;
334 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
335 Ext == "c++" || Ext == "cp" || Ext == "cxx")
336 return langkind_cxx;
337 else
338 return langkind_c;
339}
340
341
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000342static void InitializeCOptions(LangOptions &Options) {
343 // Do nothing.
344}
345
346static void InitializeObjCOptions(LangOptions &Options) {
347 Options.ObjC1 = Options.ObjC2 = 1;
348}
349
350
351static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000352 // FIXME: implement -fpreprocessed mode.
353 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000354 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000355
356 // Test for 'PCH'.
357 switch (LK) {
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000358 default:
359 break;
360 case langkind_c_pch:
361 LK = langkind_c;
362 PCH = true;
363 break;
364 case langkind_objc_pch:
365 LK = langkind_objc;
366 PCH = true;
367 break;
368 case langkind_cxx_pch:
369 LK = langkind_cxx;
370 PCH = true;
371 break;
372 case langkind_objcxx_pch:
373 LK = langkind_objcxx;
374 PCH = true;
375 break;
Ted Kremenekceacc812009-01-09 00:38:08 +0000376 }
Chris Lattner4b009652007-07-25 00:24:17 +0000377
Ted Kremenek11ad8952007-12-05 23:49:08 +0000378 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000379 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000380 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000381 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000382 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000383 case langkind_c_cpp:
384 NoPreprocess = true;
385 // FALLTHROUGH
386 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000387 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000388 break;
389 case langkind_cxx_cpp:
390 NoPreprocess = true;
391 // FALLTHROUGH
392 case langkind_cxx:
393 Options.CPlusPlus = 1;
394 break;
395 case langkind_objc_cpp:
396 NoPreprocess = true;
397 // FALLTHROUGH
398 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000399 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000400 break;
401 case langkind_objcxx_cpp:
402 NoPreprocess = true;
403 // FALLTHROUGH
404 case langkind_objcxx:
405 Options.ObjC1 = Options.ObjC2 = 1;
406 Options.CPlusPlus = 1;
407 break;
408 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000409
410 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000411}
412
413/// LangStds - Language standards we support.
414enum LangStds {
415 lang_unspecified,
416 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000417 lang_gnu_START,
418 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000419 lang_cxx98, lang_gnucxx98,
420 lang_cxx0x, lang_gnucxx0x
421};
422
423static llvm::cl::opt<LangStds>
424LangStd("std", llvm::cl::desc("Language standard to compile for"),
425 llvm::cl::init(lang_unspecified),
426 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
427 clEnumValN(lang_c89, "c90", "ISO C 1990"),
428 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
429 clEnumValN(lang_c94, "iso9899:199409",
430 "ISO C 1990 with amendment 1"),
431 clEnumValN(lang_c99, "c99", "ISO C 1999"),
432// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
433 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
434// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
435 clEnumValN(lang_gnu89, "gnu89",
436 "ISO C 1990 with GNU extensions (default for C)"),
437 clEnumValN(lang_gnu99, "gnu99",
438 "ISO C 1999 with GNU extensions"),
439 clEnumValN(lang_gnu99, "gnu9x",
440 "ISO C 1999 with GNU extensions"),
441 clEnumValN(lang_cxx98, "c++98",
442 "ISO C++ 1998 with amendments"),
443 clEnumValN(lang_gnucxx98, "gnu++98",
444 "ISO C++ 1998 with amendments and GNU "
445 "extensions (default for C++)"),
446 clEnumValN(lang_cxx0x, "c++0x",
447 "Upcoming ISO C++ 200x with amendments"),
448 clEnumValN(lang_gnucxx0x, "gnu++0x",
449 "Upcoming ISO C++ 200x with amendments and GNU "
450 "extensions (default for C++)"),
451 clEnumValEnd));
452
453static llvm::cl::opt<bool>
454NoOperatorNames("fno-operator-names",
455 llvm::cl::desc("Do not treat C++ operator name keywords as "
456 "synonyms for operators"));
457
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000458static llvm::cl::opt<bool>
459PascalStrings("fpascal-strings",
460 llvm::cl::desc("Recognize and construct Pascal-style "
461 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000462
463static llvm::cl::opt<bool>
464MSExtensions("fms-extensions",
465 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000466 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000467
468static llvm::cl::opt<bool>
469WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000470 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000471
472static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000473NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000474 llvm::cl::desc("Disallow implicit conversions between "
475 "vectors with a different number of "
476 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000477
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000478static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000479EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
480 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
481 llvm::cl::ZeroOrMore);
482
483static llvm::cl::opt<bool>
484ObjCNonFragileABI("fobjc-nonfragile-abi",
485 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000486
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000487static llvm::cl::opt<bool>
488EmitAllDecls("femit-all-decls",
489 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000490
Daniel Dunbar91692d92008-08-11 17:36:14 +0000491// FIXME: This (and all GCC -f options) really come in -f... and
492// -fno-... forms, and additionally support automagic behavior when
493// they are not defined. For example, -fexceptions defaults to on or
494// off depending on the language. We should support this behavior in
495// some form (perhaps just add a facility for distinguishing when an
496// has its default value from when it has been set to its default
497// value).
498static llvm::cl::opt<bool>
499Exceptions("fexceptions",
500 llvm::cl::desc("Enable support for exception handling."));
501
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000502static llvm::cl::opt<bool>
503GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000504 llvm::cl::desc("Generate output compatible with the standard GNU "
505 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000506
507static llvm::cl::opt<bool>
508NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000509 llvm::cl::desc("Generate output compatible with the NeXT "
510 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000511
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000512
513
514static llvm::cl::opt<bool>
515Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
516
517static llvm::cl::opt<bool>
518Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
519
Chris Lattner4b009652007-07-25 00:24:17 +0000520// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000521// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000522static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
523 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000524 // Allow the target to set the default the langauge options as it sees fit.
525 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000526
527 if (Ansi) // "The -ansi option is equivalent to -std=c89."
528 LangStd = lang_c89;
529
Chris Lattner4b009652007-07-25 00:24:17 +0000530 if (LangStd == lang_unspecified) {
531 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000532 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000533 default: assert(0 && "Unknown base language");
534 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000535 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000536 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000537 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000538 case langkind_objc:
539 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000540 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000541 LangStd = lang_gnu99;
542 break;
543 case langkind_cxx:
544 case langkind_cxx_cpp:
545 case langkind_objcxx:
546 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000547 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000548 LangStd = lang_gnucxx98;
549 break;
550 }
551 }
552
553 switch (LangStd) {
554 default: assert(0 && "Unknown language standard!");
555
556 // Fall through from newer standards to older ones. This isn't really right.
557 // FIXME: Enable specifically the right features based on the language stds.
558 case lang_gnucxx0x:
559 case lang_cxx0x:
560 Options.CPlusPlus0x = 1;
561 // FALL THROUGH
562 case lang_gnucxx98:
563 case lang_cxx98:
564 Options.CPlusPlus = 1;
565 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000566 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000567 // FALL THROUGH.
568 case lang_gnu99:
569 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000570 Options.C99 = 1;
571 Options.HexFloats = 1;
572 // FALL THROUGH.
573 case lang_gnu89:
574 Options.BCPLComment = 1; // Only for C99/C++.
575 // FALL THROUGH.
576 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000577 Options.Digraphs = 1; // C94, C99, C++.
578 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000579 case lang_c89:
580 break;
581 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000582
583 if (Options.CPlusPlus) {
584 Options.C99 = 0;
585 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
586 }
Chris Lattner4b009652007-07-25 00:24:17 +0000587
Chris Lattner6ab935b2008-04-05 06:32:51 +0000588 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
589 Options.ImplicitInt = 1;
590 else
591 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000592
593 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
594 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000595 Options.Trigraphs = LangStd < lang_gnu_START;
596 if (Trigraphs.getPosition())
597 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000598
Chris Lattner58d5ba52008-12-05 00:10:44 +0000599 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
600 // even if they are normally on for the target. In GNU modes (e.g.
601 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000602 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
603 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000604 Options.Blocks = 0;
605
Chris Lattner4b009652007-07-25 00:24:17 +0000606 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000607 if (PascalStrings.getPosition())
608 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000609 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000610 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000611 if (NoLaxVectorConversions.getPosition())
612 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000613 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000614 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000615 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000616
Douglas Gregor23d23262009-02-14 20:49:29 +0000617 if (Freestanding)
618 Options.Freestanding = 1;
619
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000620 Options.MathErrno = MathErrno;
621
Chris Lattnerddae7102008-12-04 22:54:33 +0000622 // Override the default runtime if the user requested it.
623 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000624 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000625 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000626 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000627
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000628 if (ObjCNonFragileABI)
629 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000630
631 if (EmitAllDecls)
632 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000633}
634
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000635static llvm::cl::opt<bool>
636ObjCExclusiveGC("fobjc-gc-only",
637 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000638 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000639
640static llvm::cl::opt<bool>
641ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000642 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000643
644void InitializeGCMode(LangOptions &Options) {
645 if (ObjCExclusiveGC)
646 Options.setGCMode(LangOptions::GCOnly);
647 else if (ObjCEnableGC)
648 Options.setGCMode(LangOptions::HybridGC);
649}
650
Chris Lattner4b009652007-07-25 00:24:17 +0000651//===----------------------------------------------------------------------===//
652// Our DiagnosticClient implementation
653//===----------------------------------------------------------------------===//
654
655// FIXME: Werror should take a list of things, -Werror=foo,bar
656static llvm::cl::opt<bool>
657WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
658
659static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000660SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
661
662static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000663WarnOnExtensions("pedantic", llvm::cl::init(false),
664 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
665
666static llvm::cl::opt<bool>
667ErrorOnExtensions("pedantic-errors",
668 llvm::cl::desc("Issue an error on uses of GCC extensions"));
669
670static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000671SuppressSystemWarnings("suppress-system-warnings",
Chris Lattner71af6d62009-02-06 04:16:41 +0000672 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000673 llvm::cl::init(true));
674
675static llvm::cl::opt<bool>
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000676WarnUnusedMacros("Wunused-macros",
Chris Lattner4b009652007-07-25 00:24:17 +0000677 llvm::cl::desc("Warn for unused macros in the main translation unit"));
678
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000679static llvm::cl::opt<bool>
680WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000681 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000682
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000683static llvm::cl::opt<bool>
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000684WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
685 llvm::cl::desc("Warn about readonly properties with writable attributes"));
686
687static llvm::cl::opt<bool>
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000688WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000689 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000690
Chris Lattnera616ee32008-01-23 17:19:46 +0000691static llvm::cl::opt<bool>
692WarnUndefMacros("Wundef",
693 llvm::cl::desc("Warn on use of undefined macros in #if's"));
694
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000695static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000696WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
697 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000698
Steve Naroffb91afca2008-10-21 10:37:50 +0000699static llvm::cl::opt<bool>
700WarnNoStrictSelectorMatch("Wno-strict-selector-match",
Chris Lattner71af6d62009-02-06 04:16:41 +0000701 llvm::cl::desc("Do not warn about duplicate methods that have the same size"
702 " and alignment"),
Steve Naroffb91afca2008-10-21 10:37:50 +0000703 llvm::cl::init(true));
704
Chris Lattner4b009652007-07-25 00:24:17 +0000705/// InitializeDiagnostics - Initialize the diagnostic object, based on the
706/// current command line option settings.
707static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000708 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000709 Diags.setWarningsAsErrors(WarningsAsErrors);
710 Diags.setWarnOnExtensions(WarnOnExtensions);
711 Diags.setErrorOnExtensions(ErrorOnExtensions);
712
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000713 // Suppress warnings in system headers unless requested not to.
714 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
715
Chris Lattner4b009652007-07-25 00:24:17 +0000716 // Silence the "macro is not used" warning unless requested.
717 if (!WarnUnusedMacros)
718 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000719
720 // Silence "floating point comparison" warnings unless requested.
721 if (!WarnFloatEqual)
722 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000723
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000724 if (!WarnPropertyReadonlyAttrs)
725 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
726 diag::MAP_IGNORE);
727
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000728 // Silence "format string is not a string literal" warnings if requested
729 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000730 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
731 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000732 if (!WarnUndefMacros)
733 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000734
Chris Lattner86a24842009-01-29 06:55:46 +0000735 if (WarnImplicitFunctionDeclaration)
736 Diags.setDiagnosticMapping(diag::ext_implicit_function_decl,
737 diag::MAP_WARNING);
738 else
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000739 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
740 diag::MAP_IGNORE);
Chris Lattner71af6d62009-02-06 04:16:41 +0000741
742
743 Diags.setDiagnosticMapping(diag::err_pp_file_not_found, diag::MAP_FATAL);
Chris Lattner4b009652007-07-25 00:24:17 +0000744}
745
746//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000747// Target Triple Processing.
748//===----------------------------------------------------------------------===//
749
750static llvm::cl::opt<std::string>
751TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000752 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000753
Chris Lattnerfc457002008-03-05 01:18:20 +0000754static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000755Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000756
Chris Lattner2b168e02008-09-30 01:13:12 +0000757static llvm::cl::opt<std::string>
758MacOSVersionMin("mmacosx-version-min",
759 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
760
Chris Lattner01de9c82008-09-30 20:16:56 +0000761// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
762// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
763static void HandleMacOSVersionMin(std::string &Triple) {
764 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
765 if (DarwinDashIdx == std::string::npos) {
766 fprintf(stderr,
767 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
768 exit(1);
769 }
770 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
771
Chris Lattner01de9c82008-09-30 20:16:56 +0000772 // Remove the number.
773 Triple.resize(DarwinNumIdx);
774
775 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
776 bool MacOSVersionMinIsInvalid = false;
777 int VersionNum = 0;
778 if (MacOSVersionMin.size() < 4 ||
779 MacOSVersionMin.substr(0, 3) != "10." ||
780 !isdigit(MacOSVersionMin[3])) {
781 MacOSVersionMinIsInvalid = true;
782 } else {
783 const char *Start = MacOSVersionMin.c_str()+3;
784 char *End = 0;
785 VersionNum = (int)strtol(Start, &End, 10);
786
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000787 // The version number must be in the range 0-9.
788 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
789
Chris Lattner01de9c82008-09-30 20:16:56 +0000790 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
791 Triple += llvm::itostr(VersionNum+4);
792
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000793 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
794 // Add the period piece (.7) to the end of the triple. This gives us
795 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000796 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000797 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
798 MacOSVersionMinIsInvalid = true;
799 }
800 }
801
802 if (MacOSVersionMinIsInvalid) {
803 fprintf(stderr,
804 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
805 MacOSVersionMin.c_str());
806 exit(1);
807 }
808}
809
810/// CreateTargetTriple - Process the various options that affect the target
811/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000812static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000813 // Initialize base triple. If a -triple option has been specified, use
814 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000815 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000816 if (Triple.empty()) {
817 Triple = LLVM_HOSTTRIPLE;
818
Daniel Dunbar81caece2008-12-12 18:34:35 +0000819 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
820 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
821 Triple[2] == '8' && Triple[3] == '6')
822 Triple[1] = '3';
823
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000824 // On darwin, we want to update the version to match that of the
825 // host.
826 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
827 if (DarwinDashIdx != std::string::npos) {
828 Triple.resize(DarwinDashIdx + strlen("-darwin"));
829
Daniel Dunbar81caece2008-12-12 18:34:35 +0000830 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000831 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000832 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000833 }
834 }
Ted Kremenek40499482007-12-03 22:06:55 +0000835
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000836 // If -arch foo was specified, remove the architecture from the triple we have
837 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000838 if (!Arch.empty()) {
839 // Decompose the base triple into "arch" and suffix.
840 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000841
Chris Lattner2b168e02008-09-30 01:13:12 +0000842 if (FirstDashIdx == std::string::npos) {
843 fprintf(stderr,
844 "Malformed target triple: \"%s\" ('-' could not be found).\n",
845 Triple.c_str());
846 exit(1);
847 }
Ted Kremenek40499482007-12-03 22:06:55 +0000848
Chris Lattner2b168e02008-09-30 01:13:12 +0000849 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
850 }
851
852 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
853 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000854 if (!MacOSVersionMin.empty())
855 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000856
Chris Lattner2b168e02008-09-30 01:13:12 +0000857 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000858}
859
860//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000861// Preprocessor Initialization
862//===----------------------------------------------------------------------===//
863
864// FIXME: Preprocessor builtins to support.
865// -A... - Play with #assertions
866// -undef - Undefine all predefined macros
867
868static llvm::cl::list<std::string>
869D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
870 llvm::cl::desc("Predefine the specified macro"));
871static llvm::cl::list<std::string>
872U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
873 llvm::cl::desc("Undefine the specified macro"));
874
Chris Lattner008da782008-01-10 01:53:41 +0000875static llvm::cl::list<std::string>
876ImplicitIncludes("include", llvm::cl::value_desc("file"),
877 llvm::cl::desc("Include file before parsing"));
878
879
Chris Lattner4b009652007-07-25 00:24:17 +0000880// Append a #define line to Buf for Macro. Macro should be of the form XXX,
881// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
882// "#define XXX Y z W". To get a #define with no value, use "XXX=".
883static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
884 const char *Command = "#define ") {
885 Buf.insert(Buf.end(), Command, Command+strlen(Command));
886 if (const char *Equal = strchr(Macro, '=')) {
887 // Turn the = into ' '.
888 Buf.insert(Buf.end(), Macro, Equal);
889 Buf.push_back(' ');
890 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
891 } else {
892 // Push "macroname 1".
893 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
894 Buf.push_back(' ');
895 Buf.push_back('1');
896 }
897 Buf.push_back('\n');
898}
899
Chris Lattner008da782008-01-10 01:53:41 +0000900/// AddImplicitInclude - Add an implicit #include of the specified file to the
901/// predefines buffer.
902static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
903 const char *Inc = "#include \"";
904 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
905 Buf.insert(Buf.end(), File.begin(), File.end());
906 Buf.push_back('"');
907 Buf.push_back('\n');
908}
909
Chris Lattner4b009652007-07-25 00:24:17 +0000910
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000911/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000912/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000913///
Chris Lattner9d818a22008-04-19 23:25:44 +0000914static bool InitializePreprocessor(Preprocessor &PP,
915 bool InitializeSourceMgr,
916 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000917 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000918
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000919 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000920 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000921
922 if (InitializeSourceMgr) {
923 if (InFile != "-") {
924 const FileEntry *File = FileMgr.getFile(InFile);
925 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000926 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000927 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000928 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000929 }
930 } else {
931 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
932 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000933 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000934 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000935 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000936 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000937 }
Chris Lattner4b009652007-07-25 00:24:17 +0000938 }
Sam Bishop61a20782008-04-14 14:41:57 +0000939
Chris Lattner47b6a162008-04-19 23:09:31 +0000940 std::vector<char> PredefineBuffer;
941
Chris Lattner4b009652007-07-25 00:24:17 +0000942 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000943 unsigned d = 0, D = D_macros.size();
944 unsigned u = 0, U = U_macros.size();
945 while (d < D || u < U) {
946 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
947 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
948 else
949 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
950 }
951
Chris Lattner008da782008-01-10 01:53:41 +0000952 // FIXME: Read any files specified by -imacros.
953
954 // Add implicit #includes from -include.
955 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
956 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000957
Chris Lattner47b6a162008-04-19 23:09:31 +0000958 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000959 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000960 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000961
962 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000963 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000964}
965
966//===----------------------------------------------------------------------===//
967// Preprocessor include path information.
968//===----------------------------------------------------------------------===//
969
970// This tool exports a large number of command line options to control how the
971// preprocessor searches for header files. At root, however, the Preprocessor
972// object takes a very simple interface: a list of directories to search for
973//
974// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000975// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000976//
Chris Lattner008da782008-01-10 01:53:41 +0000977// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000978
979static llvm::cl::opt<bool>
980nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
981
982// Various command line options. These four add directories to each chain.
983static llvm::cl::list<std::string>
984F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
985 llvm::cl::desc("Add directory to framework include search path"));
986static llvm::cl::list<std::string>
987I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
988 llvm::cl::desc("Add directory to include search path"));
989static llvm::cl::list<std::string>
990idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
991 llvm::cl::desc("Add directory to AFTER include search path"));
992static llvm::cl::list<std::string>
993iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
994 llvm::cl::desc("Add directory to QUOTE include search path"));
995static llvm::cl::list<std::string>
996isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
997 llvm::cl::desc("Add directory to SYSTEM include search path"));
998
999// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1000static llvm::cl::list<std::string>
1001iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1002 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1003static llvm::cl::list<std::string>
1004iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1005 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1006static llvm::cl::list<std::string>
1007iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1008 llvm::cl::Prefix,
1009 llvm::cl::desc("Set directory to include search path with prefix"));
1010
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001011static llvm::cl::opt<std::string>
1012isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1013 llvm::cl::desc("Set the system root directory (usually /)"));
1014
Chris Lattner4b009652007-07-25 00:24:17 +00001015// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001016
Chris Lattner4b009652007-07-25 00:24:17 +00001017/// InitializeIncludePaths - Process the -I options and set them in the
1018/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001019void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1020 FileManager &FM, const LangOptions &Lang) {
1021 InitHeaderSearch Init(Headers, Verbose, isysroot);
1022
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001023 // Handle -I... and -F... options, walking the lists in parallel.
1024 unsigned Iidx = 0, Fidx = 0;
1025 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1026 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001027 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001028 ++Iidx;
1029 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001030 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001031 ++Fidx;
1032 }
1033 }
Chris Lattner4b009652007-07-25 00:24:17 +00001034
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001035 // Consume what's left from whatever list was longer.
1036 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001037 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001038 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001039 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001040
1041 // Handle -idirafter... options.
1042 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001043 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1044 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001045
1046 // Handle -iquote... options.
1047 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001048 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001049
1050 // Handle -isystem... options.
1051 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001052 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001053
1054 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1055 // parallel, processing the values in order of occurance to get the right
1056 // prefixes.
1057 {
1058 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1059 unsigned iprefix_idx = 0;
1060 unsigned iwithprefix_idx = 0;
1061 unsigned iwithprefixbefore_idx = 0;
1062 bool iprefix_done = iprefix_vals.empty();
1063 bool iwithprefix_done = iwithprefix_vals.empty();
1064 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1065 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1066 if (!iprefix_done &&
1067 (iwithprefix_done ||
1068 iprefix_vals.getPosition(iprefix_idx) <
1069 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1070 (iwithprefixbefore_done ||
1071 iprefix_vals.getPosition(iprefix_idx) <
1072 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1073 Prefix = iprefix_vals[iprefix_idx];
1074 ++iprefix_idx;
1075 iprefix_done = iprefix_idx == iprefix_vals.size();
1076 } else if (!iwithprefix_done &&
1077 (iwithprefixbefore_done ||
1078 iwithprefix_vals.getPosition(iwithprefix_idx) <
1079 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001080 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1081 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001082 ++iwithprefix_idx;
1083 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1084 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001085 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1086 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001087 ++iwithprefixbefore_idx;
1088 iwithprefixbefore_done =
1089 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1090 }
1091 }
1092 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001093
Nico Weber770e3882008-08-22 09:25:22 +00001094 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001095
Daniel Dunbar4e604292009-02-21 20:52:41 +00001096 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001097 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001098 llvm::sys::Path::GetMainExecutable(Argv0,
1099 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001100 if (!MainExecutablePath.isEmpty()) {
1101 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1102 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001103
1104 // Get foo/lib/clang/1.0/include
1105 //
1106 // FIXME: Don't embed version here.
1107 MainExecutablePath.appendComponent("lib");
1108 MainExecutablePath.appendComponent("clang");
1109 MainExecutablePath.appendComponent("1.0");
1110 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001111
1112 // We pass true to ignore sysroot so that we *always* look for clang headers
1113 // relative to our executable, never relative to -isysroot.
1114 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1115 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001116 }
1117
Nico Weber770e3882008-08-22 09:25:22 +00001118 if (!nostdinc)
1119 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001120
1121 // Now that we have collected all of the include paths, merge them all
1122 // together and tell the preprocessor about them.
1123
Nico Weber770e3882008-08-22 09:25:22 +00001124 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001125}
1126
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001127//===----------------------------------------------------------------------===//
1128// Driver PreprocessorFactory - For lazily generating preprocessors ...
1129//===----------------------------------------------------------------------===//
1130
1131namespace {
1132class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001133 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001134 Diagnostic &Diags;
1135 const LangOptions &LangInfo;
1136 TargetInfo &Target;
1137 SourceManager &SourceMgr;
1138 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001139 bool InitializeSourceMgr;
1140
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001141public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001142 DriverPreprocessorFactory(const std::string &infile,
1143 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001144 TargetInfo &target, SourceManager &SM,
1145 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001146 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1147 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1148
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001149
1150 virtual ~DriverPreprocessorFactory() {}
1151
1152 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001153 llvm::OwningPtr<PTHManager> PTHMgr;
1154
1155 // Use PTH?
1156 if (!TokenCache.empty())
Ted Kremenek3d145552009-01-28 20:49:33 +00001157 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001158
1159 // Create the Preprocessor.
1160 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1161 SourceMgr, HeaderInfo,
1162 PTHMgr.get()));
1163
1164 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1165 // That argument is used as the IdentifierInfoLookup argument to
1166 // IdentifierTable's ctor.
1167 if (PTHMgr) {
1168 PTHMgr->setPreprocessor(PP.get());
1169 PP->setPTHManager(PTHMgr.take());
1170 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001171
Chris Lattner9d818a22008-04-19 23:25:44 +00001172 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001173 return NULL;
1174 }
1175
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001176 /// FIXME: PP can only handle one callback
1177 if (ProgAction != PrintPreprocessedInput) {
1178 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001179 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001180 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001181 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001182 return NULL;
1183 }
1184 }
1185
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001186 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001187 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001188 }
1189};
1190}
Chris Lattner4b009652007-07-25 00:24:17 +00001191
Chris Lattner4b009652007-07-25 00:24:17 +00001192//===----------------------------------------------------------------------===//
1193// Basic Parser driver
1194//===----------------------------------------------------------------------===//
1195
Chris Lattner9d818a22008-04-19 23:25:44 +00001196static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001197 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001198 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001199
1200 // Parsing the specified input file.
1201 P.ParseTranslationUnit();
1202 delete PA;
1203}
1204
1205//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001206// Code generation options
1207//===----------------------------------------------------------------------===//
1208
1209static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001210OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001211
1212// It might be nice to add bounds to the CommandLine library directly.
1213struct OptLevelParser : public llvm::cl::parser<unsigned> {
1214 bool parse(llvm::cl::Option &O, const char *ArgName,
1215 const std::string &Arg, unsigned &Val) {
1216 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1217 return true;
1218 // FIXME: Support -O4.
1219 if (Val > 3)
1220 return O.error(": '" + Arg + "' invalid optimization level!");
1221 return false;
1222 }
1223};
1224static llvm::cl::opt<unsigned, false, OptLevelParser>
1225OptLevel("O", llvm::cl::Prefix,
1226 llvm::cl::desc("Optimization level"),
1227 llvm::cl::init(0));
1228
Daniel Dunbar9101a632009-02-17 19:47:34 +00001229static llvm::cl::opt<std::string>
1230TargetCPU("mcpu",
1231 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1232
1233static llvm::cl::list<std::string>
1234TargetFeatures("mattr",
1235 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
1236
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001237static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001238 Opts.OptimizeSize = OptSize;
Daniel Dunbard725b162008-10-29 07:56:11 +00001239 if (OptSize) {
1240 // -Os implies -O2
1241 // FIXME: Diagnose conflicting options.
1242 Opts.OptimizationLevel = 2;
1243 } else {
1244 Opts.OptimizationLevel = OptLevel;
1245 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001246
1247 // FIXME: There are llvm-gcc options to control these selectively.
1248 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1249 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Daniel Dunbar6670e332009-02-15 20:00:15 +00001250 Opts.SimplifyLibCalls = !Freestanding;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001251
1252#ifdef NDEBUG
1253 Opts.VerifyModule = 0;
1254#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001255
1256 Opts.CPU = TargetCPU;
1257 Opts.Features.insert(Opts.Features.end(),
1258 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001259
1260 // Handle -ftime-report.
1261 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001262}
1263
1264//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001265// Main driver
1266//===----------------------------------------------------------------------===//
1267
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001268/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1269/// action. These consumers can operate on both ASTs that are freshly
1270/// parsed from source files as well as those deserialized from Bitcode.
Chris Lattner7f902922009-02-18 01:20:05 +00001271static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001272 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001273 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001274 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001275 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001276 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001277 default:
1278 return NULL;
1279
1280 case ASTPrint:
1281 return CreateASTPrinter();
1282
1283 case ASTDump:
1284 return CreateASTDumper();
1285
1286 case ASTView:
1287 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001288
Chris Lattner7f902922009-02-18 01:20:05 +00001289 case PrintDeclContext:
1290 return CreateDeclContextPrinter();
1291
1292 case EmitHTML:
1293 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001294
Chris Lattner7f902922009-02-18 01:20:05 +00001295 case InheritanceView:
1296 return CreateInheritanceViewer(InheritanceViewCls);
1297
1298 case TestSerialization:
1299 return CreateSerializationTest(Diag, FileMgr);
1300
1301 case EmitAssembly:
1302 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001303 case EmitBC:
1304 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001305 BackendAction Act;
1306 if (ProgAction == EmitAssembly)
1307 Act = Backend_EmitAssembly;
1308 else if (ProgAction == EmitLLVM)
1309 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001310 else if (ProgAction == EmitLLVMOnly)
1311 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001312 else
1313 Act = Backend_EmitBC;
1314
1315 CompileOptions Opts;
1316 InitializeCompileOptions(Opts);
1317 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
1318 InFile, OutputFile, GenerateDebugInfo);
1319 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001320
Chris Lattner7f902922009-02-18 01:20:05 +00001321 case SerializeAST:
1322 // FIXME: Allow user to tailor where the file is written.
1323 return CreateASTSerializer(InFile, OutputFile, Diag);
1324
1325 case RewriteObjC:
1326 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001327
Chris Lattner7f902922009-02-18 01:20:05 +00001328 case RewriteBlocks:
1329 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1330
1331 case RunAnalysis:
1332 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001333 }
1334}
1335
Chris Lattner4b009652007-07-25 00:24:17 +00001336/// ProcessInputFile - Process a single input file with the specified state.
1337///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001338static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001339 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001340 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001341 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001342
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001343 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001344 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001345 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1346 PP.getFileManager(), PP.getLangOptions(),
1347 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001348
1349 if (!Consumer) {
1350 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001351 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001352 return;
1353 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001354
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001355 break;
1356
Chris Lattneraf669fb2008-10-12 05:03:36 +00001357 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001358 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001359 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001360 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001361 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001362 RawLex.SetKeepWhitespaceMode(true);
1363
1364 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001365 RawLex.LexFromRawLexer(RawTok);
1366 while (RawTok.isNot(tok::eof)) {
1367 PP.DumpToken(RawTok, true);
1368 fprintf(stderr, "\n");
1369 RawLex.LexFromRawLexer(RawTok);
1370 }
1371 ClearSourceMgr = true;
1372 break;
1373 }
Chris Lattner4b009652007-07-25 00:24:17 +00001374 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001375 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001376 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001377 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001378 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001379 do {
1380 PP.Lex(Tok);
1381 PP.DumpToken(Tok, true);
1382 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001383 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001384 ClearSourceMgr = true;
1385 break;
1386 }
1387 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001388 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001389 Token Tok;
1390 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001391 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001392 do {
1393 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001394 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001395 ClearSourceMgr = true;
1396 break;
1397 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001398
1399 case GeneratePCH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001400 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001401 CacheTokens(PP, OutputFile);
1402 ClearSourceMgr = true;
1403 break;
1404 }
Chris Lattner4b009652007-07-25 00:24:17 +00001405
Chris Lattnerefe33382009-02-18 01:51:21 +00001406 case PrintPreprocessedInput: { // -E mode.
1407 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001408 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001409 ClearSourceMgr = true;
1410 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001411 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001412
Chris Lattnerefe33382009-02-18 01:51:21 +00001413 case ParseNoop: { // -parse-noop
1414 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001415 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001416 ClearSourceMgr = true;
1417 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001418 }
Chris Lattner4b009652007-07-25 00:24:17 +00001419
Chris Lattnerefe33382009-02-18 01:51:21 +00001420 case ParsePrintCallbacks: {
1421 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001422 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001423 ClearSourceMgr = true;
1424 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001425 }
1426
1427 case ParseSyntaxOnly: { // -fsyntax-only
1428 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001429 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001430 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001431 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001432
1433 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001434 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001435 ClearSourceMgr = true;
1436 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001437
Chris Lattnerefe33382009-02-18 01:51:21 +00001438 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001439 DoRewriteTest(PP, InFile, OutputFile);
1440 ClearSourceMgr = true;
1441 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001442 }
Chris Lattnerefe33382009-02-18 01:51:21 +00001443 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001444
1445 if (Consumer) {
1446 TranslationUnit *TU = 0;
1447 if (DisableFree) {
1448 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1449 PP.getSourceManager(),
1450 PP.getTargetInfo(),
1451 PP.getIdentifierTable(),
1452 PP.getSelectorTable(),
1453 /* FreeMemory = */ false);
1454 TU = new TranslationUnit(*Context);
1455 }
1456 ParseAST(PP, Consumer.get(), TU, Stats);
1457 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001458
1459 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001460 if (CheckDiagnostics(PP))
1461 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001462
Chris Lattner4b009652007-07-25 00:24:17 +00001463 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001464 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001465 PP.PrintStats();
1466 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001467 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001468 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001469 fprintf(stderr, "\n");
1470 }
1471
1472 // For a multi-file compilation, some things are ok with nuking the source
1473 // manager tables, other require stable fileid/macroid's across multiple
1474 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001475 if (ClearSourceMgr)
1476 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001477
1478 if (DisableFree)
1479 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001480}
1481
Ted Kremenek80d53372007-12-12 23:41:08 +00001482static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1483 FileManager& FileMgr) {
1484
1485 if (VerifyDiagnostics) {
1486 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1487 exit (1);
1488 }
1489
1490 llvm::sys::Path Filename(InFile);
1491
1492 if (!Filename.isValid()) {
1493 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1494 exit (1);
1495 }
1496
Ted Kremenek863b01f2008-04-23 16:25:39 +00001497 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001498
1499 if (!TU) {
1500 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1501 InFile.c_str());
1502 exit (1);
1503 }
1504
Ted Kremenekab749372007-12-19 19:27:38 +00001505 // Observe that we use the source file name stored in the deserialized
1506 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001507 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001508 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001509 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001510
Ted Kremenek80d53372007-12-12 23:41:08 +00001511 if (!Consumer) {
1512 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1513 exit (1);
1514 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001515
Ted Kremenek863b01f2008-04-23 16:25:39 +00001516 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001517
Chris Lattner8d72ee02008-02-06 01:42:25 +00001518 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001519 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1520 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001521}
1522
1523
Chris Lattner4b009652007-07-25 00:24:17 +00001524static llvm::cl::list<std::string>
1525InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1526
Ted Kremenek80d53372007-12-12 23:41:08 +00001527static bool isSerializedFile(const std::string& InFile) {
1528 if (InFile.size() < 4)
1529 return false;
1530
1531 const char* s = InFile.c_str()+InFile.size()-4;
1532
1533 return s[0] == '.' &&
1534 s[1] == 'a' &&
1535 s[2] == 's' &&
1536 s[3] == 't';
1537}
1538
Chris Lattner4b009652007-07-25 00:24:17 +00001539
1540int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001541 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001542 llvm::sys::PrintStackTraceOnErrorSignal();
1543
Chris Lattnerefe33382009-02-18 01:51:21 +00001544 if (TimeReport)
1545 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1546
1547
Chris Lattner4b009652007-07-25 00:24:17 +00001548 // If no input was specified, read from stdin.
1549 if (InputFilenames.empty())
1550 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001551
Chris Lattner4b009652007-07-25 00:24:17 +00001552 // Create a file manager object to provide access to and cache the filesystem.
1553 FileManager FileMgr;
1554
Ted Kremenekb240e822007-12-11 23:28:38 +00001555 // Create the diagnostic client for reporting errors or for
1556 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001557 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001558
Ted Kremenek5c341732008-08-07 17:49:57 +00001559 if (!VerifyDiagnostics) {
1560 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001561 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1562 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001563 !NoCaretDiagnostics,
1564 !NoShowLocation);
Ted Kremenek5c341732008-08-07 17:49:57 +00001565 } else {
1566 // When checking diagnostics, just buffer them up.
1567 TextDiagClient = new TextDiagnosticBuffer();
1568
1569 if (InputFilenames.size() != 1) {
1570 fprintf(stderr,
1571 "-verify only works on single input files for now.\n");
1572 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001573 }
1574 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001575
Chris Lattner4b009652007-07-25 00:24:17 +00001576 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001577 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1578 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001579 InitializeDiagnostics(Diags);
1580
Chris Lattner45a56e02007-12-05 23:24:17 +00001581 // -I- is a deprecated GCC feature, scan for it and reject it.
1582 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1583 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001584 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001585 I_dirs.erase(I_dirs.begin()+i);
1586 --i;
1587 }
1588 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001589
1590 // Get information about the target being compiled for.
1591 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001592 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1593
Chris Lattner2c77d852008-03-14 06:12:05 +00001594 if (Target == 0) {
1595 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1596 Triple.c_str());
1597 fprintf(stderr, "Please use -triple or -arch.\n");
1598 exit(1);
1599 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001600
Daniel Dunbar9c321102009-01-20 23:17:32 +00001601 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001602 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001603
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001604 llvm::OwningPtr<SourceManager> SourceMgr;
1605
Chris Lattner4b009652007-07-25 00:24:17 +00001606 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001607 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001608
Ted Kremenek5c341732008-08-07 17:49:57 +00001609 if (isSerializedFile(InFile)) {
1610 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001611 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001612 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001613 else {
1614 /// Create a SourceManager object. This tracks and owns all the file
1615 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001616 if (!SourceMgr)
1617 SourceMgr.reset(new SourceManager());
1618 else
1619 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001620
Ted Kremenek80d53372007-12-12 23:41:08 +00001621 // Initialize language options, inferring file types from input filenames.
1622 LangOptions LangInfo;
1623 InitializeBaseLanguage();
1624 LangKind LK = GetLanguage(InFile);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001625 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001626 InitializeGCMode(LangInfo);
Chris Lattnerddae7102008-12-04 22:54:33 +00001627 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001628
Ted Kremenek80d53372007-12-12 23:41:08 +00001629 // Process the -I options and set them in the HeaderInfo.
1630 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001631
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001632 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001633
Ted Kremenek80d53372007-12-12 23:41:08 +00001634 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001635 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001636 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001637
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001638 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1639
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001640 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001641 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001642
1643 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1644 // always reset to using TextDiagClient.
1645 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001646
Ted Kremenek5c341732008-08-07 17:49:57 +00001647 if (!HTMLDiag.empty()) {
1648 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1649 &PPFactory));
1650 Diags.setClient(TmpClient.get());
1651 }
1652 else
1653 Diags.setClient(TextDiagClient);
1654
1655 // Process the source file.
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001656 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1657
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001658 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001659 }
Chris Lattner4b009652007-07-25 00:24:17 +00001660 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001661
Mike Stump91d01352009-01-28 02:43:35 +00001662 if (Verbose)
1663 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1664 " hosted on " LLVM_HOSTTRIPLE "\n");
1665
Ted Kremenekec6c5252008-08-07 18:13:12 +00001666 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001667 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1668 (NumDiagnostics == 1 ? "" : "s"));
1669
1670 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001671 FileMgr.PrintStats();
1672 fprintf(stderr, "\n");
1673 }
1674
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001675 // If verifying diagnostics and we reached here, all is well.
1676 if (VerifyDiagnostics)
1677 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001678
1679 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001680
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001681 // Managed static deconstruction. Useful for making things like
1682 // -time-passes usable.
1683 llvm::llvm_shutdown();
1684
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001685 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001686}