blob: 160c252304972f9bf128dd2d2613fb6b2ff55e5d [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"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000029#include "clang/Frontend/InitHeaderSearch.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000030#include "clang/Frontend/PathDiagnosticClients.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000031#include "clang/Frontend/TextDiagnosticBuffer.h"
32#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000033#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000034#include "clang/AST/Decl.h"
Ted Kremenekac881932007-12-18 21:34:28 +000035#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000036#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000037#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000038#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000039#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000040#include "clang/Parse/Parser.h"
41#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000042#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000043#include "clang/Basic/FileManager.h"
44#include "clang/Basic/SourceManager.h"
45#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000046#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000047#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000048#include "llvm/ADT/StringExtras.h"
49#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000050#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000051#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000052#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000053#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000054#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000055#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000056#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000057#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000058#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000059using namespace clang;
60
61//===----------------------------------------------------------------------===//
62// Global options.
63//===----------------------------------------------------------------------===//
64
Chris Lattnerefe33382009-02-18 01:51:21 +000065/// ClangFrontendTimer - The front-end activities should charge time to it with
66/// TimeRegion. The -ftime-report option controls whether this will do
67/// anything.
68llvm::Timer *ClangFrontendTimer = 0;
69
Daniel Dunbar4efedde2008-10-16 16:54:18 +000070static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000071
Chris Lattner4b009652007-07-25 00:24:17 +000072static llvm::cl::opt<bool>
73Verbose("v", llvm::cl::desc("Enable verbose output"));
74static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000075Stats("print-stats",
76 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000077static llvm::cl::opt<bool>
78DisableFree("disable-free",
79 llvm::cl::desc("Disable freeing of memory on exit"),
80 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000081
82enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000083 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000084 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000085 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000086 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000087 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000088 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000089 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000090 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +000091 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek397de012007-12-13 00:37:31 +000092 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000093 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000094 ASTPrint, // Parse ASTs and print them.
95 ASTDump, // Parse ASTs and dump them.
96 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000097 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000098 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000099 ParsePrintCallbacks, // Parse and print each callback.
100 ParseSyntaxOnly, // Parse and perform semantic analysis.
101 ParseNoop, // Parse with noop callbacks.
102 RunPreprocessorOnly, // Just lex, no output.
103 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000104 DumpTokens, // Dump out preprocessed tokens.
105 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000106 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000107 GeneratePCH, // Generate precompiled header.
108 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000109};
110
111static llvm::cl::opt<ProgActions>
112ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
113 llvm::cl::init(ParseSyntaxOnly),
114 llvm::cl::values(
115 clEnumValN(RunPreprocessorOnly, "Eonly",
116 "Just run preprocessor, no output (for timings)"),
117 clEnumValN(PrintPreprocessedInput, "E",
118 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000119 clEnumValN(DumpRawTokens, "dump-raw-tokens",
120 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000121 clEnumValN(RunAnalysis, "analyze",
122 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000123 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000124 "Run preprocessor, dump internal rep of tokens"),
125 clEnumValN(ParseNoop, "parse-noop",
126 "Run parser with noop callbacks (for timings)"),
127 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
128 "Run parser and perform semantic analysis"),
129 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
130 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000131 clEnumValN(EmitHTML, "emit-html",
132 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000133 clEnumValN(ASTPrint, "ast-print",
134 "Build ASTs and then pretty-print them"),
135 clEnumValN(ASTDump, "ast-dump",
136 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000137 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000138 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000139 clEnumValN(PrintDeclContext, "print-decl-contexts",
140 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000141 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000142 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000143 clEnumValN(EmitAssembly, "S",
144 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000145 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000146 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000147 clEnumValN(EmitBC, "emit-llvm-bc",
148 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000149 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
150 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000151 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000152 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000153 clEnumValN(RewriteTest, "rewrite-test",
154 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000155 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000156 "Rewrite ObjC into C (code rewriter example)"),
157 clEnumValN(RewriteMacros, "rewrite-macros",
158 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000159 clEnumValN(RewriteBlocks, "rewrite-blocks",
160 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000161 clEnumValEnd));
162
Ted Kremenekd01eae62007-12-19 19:47:59 +0000163
164static llvm::cl::opt<std::string>
165OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000166 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000167 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000168
Ted Kremenek57f25b22008-12-02 19:57:31 +0000169
170//===----------------------------------------------------------------------===//
171// PTH.
172//===----------------------------------------------------------------------===//
173
174static llvm::cl::opt<std::string>
175TokenCache("token-cache", llvm::cl::value_desc("path"),
176 llvm::cl::desc("Use specified token cache file"));
177
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000178//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000179// Diagnostic Options
180//===----------------------------------------------------------------------===//
181
Ted Kremenek10389cf2007-09-26 19:42:19 +0000182static llvm::cl::opt<bool>
183VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000184 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000185
Ted Kremenekfd75e312008-03-27 06:17:42 +0000186static llvm::cl::opt<std::string>
187HTMLDiag("html-diags",
188 llvm::cl::desc("Generate HTML to report diagnostics"),
189 llvm::cl::value_desc("HTML directory"));
190
Nico Weber0e13eaa2008-08-05 23:33:20 +0000191static llvm::cl::opt<bool>
192NoShowColumn("fno-show-column",
193 llvm::cl::desc("Do not include column number on diagnostics"));
194
195static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000196NoShowLocation("fno-show-source-location",
197 llvm::cl::desc("Do not include source location information with"
198 " diagnostics"));
199
200static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000201NoCaretDiagnostics("fno-caret-diagnostics",
202 llvm::cl::desc("Do not include source line and caret with"
203 " diagnostics"));
204
Chris Lattner695a4f52009-03-13 01:08:23 +0000205static llvm::cl::opt<bool>
206PrintSourceRangeInfo("fprint-source-range-info",
207 llvm::cl::desc("Print source range spans in numeric form"));
208
Nico Weber0e13eaa2008-08-05 23:33:20 +0000209
Chris Lattner4b009652007-07-25 00:24:17 +0000210//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000211// C++ Visualization.
212//===----------------------------------------------------------------------===//
213
214static llvm::cl::opt<std::string>
215InheritanceViewCls("cxx-inheritance-view",
216 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000217 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000218
219//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000220// Builtin Options
221//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000222
223static llvm::cl::opt<bool>
224TimeReport("ftime-report",
225 llvm::cl::desc("Print the amount of time each "
226 "phase of compilation takes"));
227
Douglas Gregor23d23262009-02-14 20:49:29 +0000228static llvm::cl::opt<bool>
229Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000230 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000231 "freestanding environment"));
232
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000233static llvm::cl::opt<bool>
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000234AllowBuiltins("fbuiltin",
235 llvm::cl::desc("Disable implicit builtin knowledge of functions"),
236 llvm::cl::init(true), llvm::cl::AllowInverse);
Chris Lattner911b8672009-03-13 22:38:49 +0000237
238
239static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000240MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000241 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000242 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000243
Douglas Gregor23d23262009-02-14 20:49:29 +0000244//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000245// Language Options
246//===----------------------------------------------------------------------===//
247
248enum LangKind {
249 langkind_unspecified,
250 langkind_c,
251 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000252 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000253 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000254 langkind_cxx,
255 langkind_cxx_cpp,
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000256 langkind_cxx_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000257 langkind_objc,
258 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000259 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000260 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000261 langkind_objcxx_cpp,
262 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000263};
264
Chris Lattner4b009652007-07-25 00:24:17 +0000265static llvm::cl::opt<LangKind>
266BaseLang("x", llvm::cl::desc("Base language to compile"),
267 llvm::cl::init(langkind_unspecified),
268 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
269 clEnumValN(langkind_cxx, "c++", "C++"),
270 clEnumValN(langkind_objc, "objective-c", "Objective C"),
271 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000272 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000273 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000274 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
275 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000276 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000277 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000278 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
279 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000280 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000281 "Preprocessed Objective C++"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000282 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000283 "Precompiled C header"),
284 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000285 "Precompiled Objective-C header"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000286 clEnumValN(langkind_cxx_pch, "c++-header",
287 "Precompiled C++ header"),
Ted Kremenekceacc812009-01-09 00:38:08 +0000288 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
289 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000290 clEnumValEnd));
291
292static llvm::cl::opt<bool>
293LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
294 llvm::cl::Hidden);
295static llvm::cl::opt<bool>
296LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
297 llvm::cl::Hidden);
298
Ted Kremenek11ad8952007-12-05 23:49:08 +0000299/// InitializeBaseLanguage - Handle the -x foo options.
300static void InitializeBaseLanguage() {
301 if (LangObjC)
302 BaseLang = langkind_objc;
303 else if (LangObjCXX)
304 BaseLang = langkind_objcxx;
305}
306
307static LangKind GetLanguage(const std::string &Filename) {
308 if (BaseLang != langkind_unspecified)
309 return BaseLang;
310
311 std::string::size_type DotPos = Filename.rfind('.');
312
313 if (DotPos == std::string::npos) {
314 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000315 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000316 }
317
Ted Kremenek11ad8952007-12-05 23:49:08 +0000318 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
319 // C header: .h
320 // C++ header: .hh or .H;
321 // assembler no preprocessing: .s
322 // assembler: .S
323 if (Ext == "c")
324 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000325 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000326 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000327 else if (Ext == "i")
328 return langkind_c_cpp;
329 else if (Ext == "ii")
330 return langkind_cxx_cpp;
331 else if (Ext == "m")
332 return langkind_objc;
333 else if (Ext == "mi")
334 return langkind_objc_cpp;
335 else if (Ext == "mm" || Ext == "M")
336 return langkind_objcxx;
337 else if (Ext == "mii")
338 return langkind_objcxx_cpp;
339 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
340 Ext == "c++" || Ext == "cp" || Ext == "cxx")
341 return langkind_cxx;
342 else
343 return langkind_c;
344}
345
346
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000347static void InitializeCOptions(LangOptions &Options) {
348 // Do nothing.
349}
350
351static void InitializeObjCOptions(LangOptions &Options) {
352 Options.ObjC1 = Options.ObjC2 = 1;
353}
354
355
356static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000357 // FIXME: implement -fpreprocessed mode.
358 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000359 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000360
361 // Test for 'PCH'.
362 switch (LK) {
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000363 default:
364 break;
365 case langkind_c_pch:
366 LK = langkind_c;
367 PCH = true;
368 break;
369 case langkind_objc_pch:
370 LK = langkind_objc;
371 PCH = true;
372 break;
373 case langkind_cxx_pch:
374 LK = langkind_cxx;
375 PCH = true;
376 break;
377 case langkind_objcxx_pch:
378 LK = langkind_objcxx;
379 PCH = true;
380 break;
Ted Kremenekceacc812009-01-09 00:38:08 +0000381 }
Chris Lattner4b009652007-07-25 00:24:17 +0000382
Ted Kremenek11ad8952007-12-05 23:49:08 +0000383 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000384 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000385 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000386 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000387 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000388 case langkind_c_cpp:
389 NoPreprocess = true;
390 // FALLTHROUGH
391 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000392 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000393 break;
394 case langkind_cxx_cpp:
395 NoPreprocess = true;
396 // FALLTHROUGH
397 case langkind_cxx:
398 Options.CPlusPlus = 1;
399 break;
400 case langkind_objc_cpp:
401 NoPreprocess = true;
402 // FALLTHROUGH
403 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000404 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000405 break;
406 case langkind_objcxx_cpp:
407 NoPreprocess = true;
408 // FALLTHROUGH
409 case langkind_objcxx:
410 Options.ObjC1 = Options.ObjC2 = 1;
411 Options.CPlusPlus = 1;
412 break;
413 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000414
415 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000416}
417
418/// LangStds - Language standards we support.
419enum LangStds {
420 lang_unspecified,
421 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000422 lang_gnu_START,
423 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000424 lang_cxx98, lang_gnucxx98,
425 lang_cxx0x, lang_gnucxx0x
426};
427
428static llvm::cl::opt<LangStds>
429LangStd("std", llvm::cl::desc("Language standard to compile for"),
430 llvm::cl::init(lang_unspecified),
431 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
432 clEnumValN(lang_c89, "c90", "ISO C 1990"),
433 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
434 clEnumValN(lang_c94, "iso9899:199409",
435 "ISO C 1990 with amendment 1"),
436 clEnumValN(lang_c99, "c99", "ISO C 1999"),
437// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
438 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
439// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
440 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000441 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000442 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000443 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000444 clEnumValN(lang_gnu99, "gnu9x",
445 "ISO C 1999 with GNU extensions"),
446 clEnumValN(lang_cxx98, "c++98",
447 "ISO C++ 1998 with amendments"),
448 clEnumValN(lang_gnucxx98, "gnu++98",
449 "ISO C++ 1998 with amendments and GNU "
450 "extensions (default for C++)"),
451 clEnumValN(lang_cxx0x, "c++0x",
452 "Upcoming ISO C++ 200x with amendments"),
453 clEnumValN(lang_gnucxx0x, "gnu++0x",
454 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000455 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000456 clEnumValEnd));
457
458static llvm::cl::opt<bool>
459NoOperatorNames("fno-operator-names",
460 llvm::cl::desc("Do not treat C++ operator name keywords as "
461 "synonyms for operators"));
462
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000463static llvm::cl::opt<bool>
464PascalStrings("fpascal-strings",
465 llvm::cl::desc("Recognize and construct Pascal-style "
466 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000467
468static llvm::cl::opt<bool>
469MSExtensions("fms-extensions",
470 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000471 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000472
473static llvm::cl::opt<bool>
474WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000475 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000476
477static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000478NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000479 llvm::cl::desc("Disallow implicit conversions between "
480 "vectors with a different number of "
481 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000482
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000483static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000484EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
485 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
486 llvm::cl::ZeroOrMore);
487
488static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000489EnableHeinousExtensions("fheinous-gnu-extensions",
490 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
491 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
492
493static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000494ObjCNonFragileABI("fobjc-nonfragile-abi",
495 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000496
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000497static llvm::cl::opt<bool>
498EmitAllDecls("femit-all-decls",
499 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000500
Daniel Dunbar91692d92008-08-11 17:36:14 +0000501// FIXME: This (and all GCC -f options) really come in -f... and
502// -fno-... forms, and additionally support automagic behavior when
503// they are not defined. For example, -fexceptions defaults to on or
504// off depending on the language. We should support this behavior in
505// some form (perhaps just add a facility for distinguishing when an
506// has its default value from when it has been set to its default
507// value).
508static llvm::cl::opt<bool>
509Exceptions("fexceptions",
510 llvm::cl::desc("Enable support for exception handling."));
511
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000512static llvm::cl::opt<bool>
513GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000514 llvm::cl::desc("Generate output compatible with the standard GNU "
515 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000516
517static llvm::cl::opt<bool>
518NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000519 llvm::cl::desc("Generate output compatible with the NeXT "
520 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000521
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000522
523
524static llvm::cl::opt<bool>
525Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
526
527static llvm::cl::opt<bool>
528Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
529
Chris Lattner738d3f62009-03-02 22:11:07 +0000530static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000531TargetFeatures("mattr", llvm::cl::CommaSeparated,
532 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
533
Douglas Gregor375733c2009-03-10 00:06:19 +0000534static llvm::cl::opt<unsigned>
535TemplateDepth("ftemplate-depth", llvm::cl::init(99),
536 llvm::cl::desc("Maximum depth of recursive template "
537 "instantiation"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000538
Chris Lattner4b009652007-07-25 00:24:17 +0000539// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000540// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000541static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
542 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000543 // Allow the target to set the default the langauge options as it sees fit.
544 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000545
Chris Lattnerf6790a82009-03-03 19:56:18 +0000546 // If there are any -mattr options, pass them to the target for validation and
547 // processing. The driver should have already consolidated all the
548 // target-feature settings and passed them to us in the -mattr list. The
549 // -mattr list is treated by the code generator as a diff against the -mcpu
550 // setting, but the driver should pass all enabled options as "+" settings.
551 // This means that the target should only look at + settings.
552 if (!TargetFeatures.empty()
553 // FIXME: The driver is not quite yet ready for this.
554 && 0) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000555 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000556 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
557 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000558 if (Opt != -1) {
559 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000560 fprintf(stderr, "invalid feature '%s'\n",
561 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000562 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000563 fprintf(stderr, "feature '%s': %s\n",
564 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000565 exit(1);
566 }
567 }
568
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000569 if (Ansi) // "The -ansi option is equivalent to -std=c89."
570 LangStd = lang_c89;
571
Chris Lattner4b009652007-07-25 00:24:17 +0000572 if (LangStd == lang_unspecified) {
573 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000574 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000575 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000576 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000577 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000578 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000579 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000580 case langkind_objc:
581 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000582 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000583 LangStd = lang_gnu99;
584 break;
585 case langkind_cxx:
586 case langkind_cxx_cpp:
Ted Kremenek6be44de2009-03-19 18:21:42 +0000587 case langkind_cxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000588 case langkind_objcxx:
589 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000590 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000591 LangStd = lang_gnucxx98;
592 break;
593 }
594 }
595
596 switch (LangStd) {
597 default: assert(0 && "Unknown language standard!");
598
599 // Fall through from newer standards to older ones. This isn't really right.
600 // FIXME: Enable specifically the right features based on the language stds.
601 case lang_gnucxx0x:
602 case lang_cxx0x:
603 Options.CPlusPlus0x = 1;
604 // FALL THROUGH
605 case lang_gnucxx98:
606 case lang_cxx98:
607 Options.CPlusPlus = 1;
608 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000609 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000610 // FALL THROUGH.
611 case lang_gnu99:
612 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000613 Options.C99 = 1;
614 Options.HexFloats = 1;
615 // FALL THROUGH.
616 case lang_gnu89:
617 Options.BCPLComment = 1; // Only for C99/C++.
618 // FALL THROUGH.
619 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000620 Options.Digraphs = 1; // C94, C99, C++.
621 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000622 case lang_c89:
623 break;
624 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000625
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000626 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
627 Options.GNUMode = LangStd >= lang_gnu_START;
628
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000629 if (Options.CPlusPlus) {
630 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000631 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000632 }
Chris Lattner4b009652007-07-25 00:24:17 +0000633
Chris Lattner6ab935b2008-04-05 06:32:51 +0000634 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
635 Options.ImplicitInt = 1;
636 else
637 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000638
639 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
640 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000641 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000642 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000643 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000644
Chris Lattner58d5ba52008-12-05 00:10:44 +0000645 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
646 // even if they are normally on for the target. In GNU modes (e.g.
647 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000648 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000649 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000650 Options.Blocks = 0;
651
Daniel Dunbar551236b2009-03-15 00:11:28 +0000652 // Never accept '$' in identifiers when preprocessing assembler.
653 if (LK != langkind_asm_cpp)
654 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000655 if (PascalStrings.getPosition())
656 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000657 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000658 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000659 if (NoLaxVectorConversions.getPosition())
660 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000661 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000662 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000663 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000664
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000665 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000666 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000667 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000668 Options.Freestanding = Options.NoBuiltin = 1;
669
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000670 if (EnableHeinousExtensions)
671 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000672
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000673 Options.MathErrno = MathErrno;
674
Douglas Gregor375733c2009-03-10 00:06:19 +0000675 Options.InstantiationDepth = TemplateDepth;
676
Chris Lattnerddae7102008-12-04 22:54:33 +0000677 // Override the default runtime if the user requested it.
678 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000679 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000680 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000681 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000682
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000683 if (ObjCNonFragileABI)
684 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000685
686 if (EmitAllDecls)
687 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000688}
689
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000690static llvm::cl::opt<bool>
691ObjCExclusiveGC("fobjc-gc-only",
692 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000693 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000694
695static llvm::cl::opt<bool>
696ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000697 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000698
699void InitializeGCMode(LangOptions &Options) {
700 if (ObjCExclusiveGC)
701 Options.setGCMode(LangOptions::GCOnly);
702 else if (ObjCEnableGC)
703 Options.setGCMode(LangOptions::HybridGC);
704}
705
Chris Lattner4b009652007-07-25 00:24:17 +0000706//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000707// Target Triple Processing.
708//===----------------------------------------------------------------------===//
709
710static llvm::cl::opt<std::string>
711TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000712 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000713
Chris Lattnerfc457002008-03-05 01:18:20 +0000714static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000715Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000716
Chris Lattner2b168e02008-09-30 01:13:12 +0000717static llvm::cl::opt<std::string>
718MacOSVersionMin("mmacosx-version-min",
719 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
720
Chris Lattner01de9c82008-09-30 20:16:56 +0000721// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
722// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
723static void HandleMacOSVersionMin(std::string &Triple) {
724 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
725 if (DarwinDashIdx == std::string::npos) {
726 fprintf(stderr,
727 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
728 exit(1);
729 }
730 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
731
Chris Lattner01de9c82008-09-30 20:16:56 +0000732 // Remove the number.
733 Triple.resize(DarwinNumIdx);
734
735 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
736 bool MacOSVersionMinIsInvalid = false;
737 int VersionNum = 0;
738 if (MacOSVersionMin.size() < 4 ||
739 MacOSVersionMin.substr(0, 3) != "10." ||
740 !isdigit(MacOSVersionMin[3])) {
741 MacOSVersionMinIsInvalid = true;
742 } else {
743 const char *Start = MacOSVersionMin.c_str()+3;
744 char *End = 0;
745 VersionNum = (int)strtol(Start, &End, 10);
746
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000747 // The version number must be in the range 0-9.
748 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
749
Chris Lattner01de9c82008-09-30 20:16:56 +0000750 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
751 Triple += llvm::itostr(VersionNum+4);
752
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000753 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
754 // Add the period piece (.7) to the end of the triple. This gives us
755 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000756 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000757 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
758 MacOSVersionMinIsInvalid = true;
759 }
760 }
761
762 if (MacOSVersionMinIsInvalid) {
763 fprintf(stderr,
764 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
765 MacOSVersionMin.c_str());
766 exit(1);
767 }
768}
769
770/// CreateTargetTriple - Process the various options that affect the target
771/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000772static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000773 // Initialize base triple. If a -triple option has been specified, use
774 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000775 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000776 if (Triple.empty()) {
777 Triple = LLVM_HOSTTRIPLE;
778
Daniel Dunbar81caece2008-12-12 18:34:35 +0000779 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
780 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
781 Triple[2] == '8' && Triple[3] == '6')
782 Triple[1] = '3';
783
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000784 // On darwin, we want to update the version to match that of the
785 // host.
786 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
787 if (DarwinDashIdx != std::string::npos) {
788 Triple.resize(DarwinDashIdx + strlen("-darwin"));
789
Daniel Dunbar81caece2008-12-12 18:34:35 +0000790 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000791 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000792 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000793 }
794 }
Ted Kremenek40499482007-12-03 22:06:55 +0000795
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000796 // If -arch foo was specified, remove the architecture from the triple we have
797 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000798 if (!Arch.empty()) {
799 // Decompose the base triple into "arch" and suffix.
800 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000801
Chris Lattner2b168e02008-09-30 01:13:12 +0000802 if (FirstDashIdx == std::string::npos) {
803 fprintf(stderr,
804 "Malformed target triple: \"%s\" ('-' could not be found).\n",
805 Triple.c_str());
806 exit(1);
807 }
Ted Kremenek40499482007-12-03 22:06:55 +0000808
Chris Lattner2b168e02008-09-30 01:13:12 +0000809 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
810 }
811
812 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
813 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000814 if (!MacOSVersionMin.empty())
815 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000816
Chris Lattner2b168e02008-09-30 01:13:12 +0000817 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000818}
819
820//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000821// Preprocessor Initialization
822//===----------------------------------------------------------------------===//
823
824// FIXME: Preprocessor builtins to support.
825// -A... - Play with #assertions
826// -undef - Undefine all predefined macros
827
Chris Lattner695a4f52009-03-13 01:08:23 +0000828// FIXME: -imacros
829
Chris Lattner4b009652007-07-25 00:24:17 +0000830static llvm::cl::list<std::string>
831D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
832 llvm::cl::desc("Predefine the specified macro"));
833static llvm::cl::list<std::string>
834U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
835 llvm::cl::desc("Undefine the specified macro"));
836
Chris Lattner008da782008-01-10 01:53:41 +0000837static llvm::cl::list<std::string>
838ImplicitIncludes("include", llvm::cl::value_desc("file"),
839 llvm::cl::desc("Include file before parsing"));
840
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000841static llvm::cl::opt<std::string>
842ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
843 llvm::cl::desc("Include file before parsing"));
844
Chris Lattner4b009652007-07-25 00:24:17 +0000845// Append a #define line to Buf for Macro. Macro should be of the form XXX,
846// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
847// "#define XXX Y z W". To get a #define with no value, use "XXX=".
848static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
849 const char *Command = "#define ") {
850 Buf.insert(Buf.end(), Command, Command+strlen(Command));
851 if (const char *Equal = strchr(Macro, '=')) {
852 // Turn the = into ' '.
853 Buf.insert(Buf.end(), Macro, Equal);
854 Buf.push_back(' ');
855 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
856 } else {
857 // Push "macroname 1".
858 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
859 Buf.push_back(' ');
860 Buf.push_back('1');
861 }
862 Buf.push_back('\n');
863}
864
Chris Lattner008da782008-01-10 01:53:41 +0000865/// AddImplicitInclude - Add an implicit #include of the specified file to the
866/// predefines buffer.
867static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
868 const char *Inc = "#include \"";
869 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
870 Buf.insert(Buf.end(), File.begin(), File.end());
871 Buf.push_back('"');
872 Buf.push_back('\n');
873}
874
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000875/// AddImplicitIncludePTH - Add an implicit #include using the original file
876/// used to generate a PTH cache.
877static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
878 PTHManager *P = PP.getPTHManager();
879 assert(P && "No PTHManager.");
880 const char *OriginalFile = P->getOriginalSourceFile();
881
882 if (!OriginalFile) {
883 assert(!ImplicitIncludePTH.empty());
884 fprintf(stderr, "error: PTH file '%s' does not designate an original "
885 "source header file for -include-pth\n",
886 ImplicitIncludePTH.c_str());
887 exit (1);
888 }
889
890 AddImplicitInclude(Buf, OriginalFile);
891}
Chris Lattner4b009652007-07-25 00:24:17 +0000892
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000893/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000894/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000895///
Chris Lattner9d818a22008-04-19 23:25:44 +0000896static bool InitializePreprocessor(Preprocessor &PP,
897 bool InitializeSourceMgr,
898 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000899 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000900
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000901 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000902 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000903
904 if (InitializeSourceMgr) {
905 if (InFile != "-") {
906 const FileEntry *File = FileMgr.getFile(InFile);
907 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000908 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +0000909 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
910 << InFile.c_str();
Chris Lattner9d818a22008-04-19 23:25:44 +0000911 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000912 }
913 } else {
914 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar99617162009-03-21 17:56:30 +0000915
916 // If stdin was empty, SB is null. Cons up an empty memory
917 // buffer now.
918 if (!SB) {
919 const char *EmptyStr = "";
920 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
921 }
922
923 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000924 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +0000925 PP.getDiagnostics().Report(FullSourceLoc(),
926 diag::err_fe_error_reading_stdin);
Chris Lattner9d818a22008-04-19 23:25:44 +0000927 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000928 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000929 }
Chris Lattner4b009652007-07-25 00:24:17 +0000930 }
Sam Bishop61a20782008-04-14 14:41:57 +0000931
Chris Lattner47b6a162008-04-19 23:09:31 +0000932 std::vector<char> PredefineBuffer;
933
Chris Lattner4b009652007-07-25 00:24:17 +0000934 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000935 unsigned d = 0, D = D_macros.size();
936 unsigned u = 0, U = U_macros.size();
937 while (d < D || u < U) {
938 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
939 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
940 else
941 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
942 }
943
Chris Lattner008da782008-01-10 01:53:41 +0000944 // FIXME: Read any files specified by -imacros.
945
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000946 // Add implicit #includes from -include and -include-pth.
947 bool handledPTH = ImplicitIncludePTH.empty();
948 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc4ecf322009-03-20 00:40:03 +0000949 if (!handledPTH &&
950 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000951 AddImplicitIncludePTH(PredefineBuffer, PP);
952 handledPTH = true;
953 }
954
Chris Lattner008da782008-01-10 01:53:41 +0000955 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000956 }
957 if (!handledPTH && !ImplicitIncludePTH.empty())
958 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000959
Chris Lattner47b6a162008-04-19 23:09:31 +0000960 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000961 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000962 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000963
964 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000965 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000966}
967
968//===----------------------------------------------------------------------===//
969// Preprocessor include path information.
970//===----------------------------------------------------------------------===//
971
972// This tool exports a large number of command line options to control how the
973// preprocessor searches for header files. At root, however, the Preprocessor
974// object takes a very simple interface: a list of directories to search for
975//
976// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000977// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000978//
Chris Lattner4b009652007-07-25 00:24:17 +0000979
980static llvm::cl::opt<bool>
981nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
982
983// Various command line options. These four add directories to each chain.
984static llvm::cl::list<std::string>
985F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
986 llvm::cl::desc("Add directory to framework include search path"));
987static llvm::cl::list<std::string>
988I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
989 llvm::cl::desc("Add directory to include search path"));
990static llvm::cl::list<std::string>
991idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
992 llvm::cl::desc("Add directory to AFTER include search path"));
993static llvm::cl::list<std::string>
994iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
995 llvm::cl::desc("Add directory to QUOTE include search path"));
996static llvm::cl::list<std::string>
997isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
998 llvm::cl::desc("Add directory to SYSTEM include search path"));
999
1000// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1001static llvm::cl::list<std::string>
1002iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1003 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1004static llvm::cl::list<std::string>
1005iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1006 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1007static llvm::cl::list<std::string>
1008iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1009 llvm::cl::Prefix,
1010 llvm::cl::desc("Set directory to include search path with prefix"));
1011
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001012static llvm::cl::opt<std::string>
1013isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1014 llvm::cl::desc("Set the system root directory (usually /)"));
1015
Chris Lattner4b009652007-07-25 00:24:17 +00001016// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001017
Chris Lattner4b009652007-07-25 00:24:17 +00001018/// InitializeIncludePaths - Process the -I options and set them in the
1019/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001020void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1021 FileManager &FM, const LangOptions &Lang) {
1022 InitHeaderSearch Init(Headers, Verbose, isysroot);
1023
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001024 // Handle -I... and -F... options, walking the lists in parallel.
1025 unsigned Iidx = 0, Fidx = 0;
1026 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1027 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001028 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001029 ++Iidx;
1030 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001031 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001032 ++Fidx;
1033 }
1034 }
Chris Lattner4b009652007-07-25 00:24:17 +00001035
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001036 // Consume what's left from whatever list was longer.
1037 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001038 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001039 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001040 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001041
1042 // Handle -idirafter... options.
1043 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001044 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1045 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001046
1047 // Handle -iquote... options.
1048 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001049 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001050
1051 // Handle -isystem... options.
1052 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001053 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001054
1055 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1056 // parallel, processing the values in order of occurance to get the right
1057 // prefixes.
1058 {
1059 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1060 unsigned iprefix_idx = 0;
1061 unsigned iwithprefix_idx = 0;
1062 unsigned iwithprefixbefore_idx = 0;
1063 bool iprefix_done = iprefix_vals.empty();
1064 bool iwithprefix_done = iwithprefix_vals.empty();
1065 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1066 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1067 if (!iprefix_done &&
1068 (iwithprefix_done ||
1069 iprefix_vals.getPosition(iprefix_idx) <
1070 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1071 (iwithprefixbefore_done ||
1072 iprefix_vals.getPosition(iprefix_idx) <
1073 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1074 Prefix = iprefix_vals[iprefix_idx];
1075 ++iprefix_idx;
1076 iprefix_done = iprefix_idx == iprefix_vals.size();
1077 } else if (!iwithprefix_done &&
1078 (iwithprefixbefore_done ||
1079 iwithprefix_vals.getPosition(iwithprefix_idx) <
1080 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001081 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1082 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001083 ++iwithprefix_idx;
1084 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1085 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001086 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1087 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001088 ++iwithprefixbefore_idx;
1089 iwithprefixbefore_done =
1090 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1091 }
1092 }
1093 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001094
Nico Weber770e3882008-08-22 09:25:22 +00001095 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001096
Daniel Dunbar4e604292009-02-21 20:52:41 +00001097 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001098 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001099 llvm::sys::Path::GetMainExecutable(Argv0,
1100 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001101 if (!MainExecutablePath.isEmpty()) {
1102 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1103 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001104
1105 // Get foo/lib/clang/1.0/include
1106 //
1107 // FIXME: Don't embed version here.
1108 MainExecutablePath.appendComponent("lib");
1109 MainExecutablePath.appendComponent("clang");
1110 MainExecutablePath.appendComponent("1.0");
1111 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001112
1113 // We pass true to ignore sysroot so that we *always* look for clang headers
1114 // relative to our executable, never relative to -isysroot.
1115 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1116 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001117 }
1118
Nico Weber770e3882008-08-22 09:25:22 +00001119 if (!nostdinc)
1120 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001121
1122 // Now that we have collected all of the include paths, merge them all
1123 // together and tell the preprocessor about them.
1124
Nico Weber770e3882008-08-22 09:25:22 +00001125 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001126}
1127
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001128//===----------------------------------------------------------------------===//
1129// Driver PreprocessorFactory - For lazily generating preprocessors ...
1130//===----------------------------------------------------------------------===//
1131
1132namespace {
1133class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001134 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001135 Diagnostic &Diags;
1136 const LangOptions &LangInfo;
1137 TargetInfo &Target;
1138 SourceManager &SourceMgr;
1139 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001140 bool InitializeSourceMgr;
1141
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001142public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001143 DriverPreprocessorFactory(const std::string &infile,
1144 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001145 TargetInfo &target, SourceManager &SM,
1146 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001147 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1148 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1149
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001150
1151 virtual ~DriverPreprocessorFactory() {}
1152
1153 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001154 llvm::OwningPtr<PTHManager> PTHMgr;
1155
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001156 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1157 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1158 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001159 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001160 }
1161
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001162 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001163 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1164 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001165 PTHMgr.reset(PTHManager::Create(x, &Diags,
1166 TokenCache.empty() ? Diagnostic::Error
1167 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001168 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001169
Ted Kremenek6348cc62009-03-22 06:42:39 +00001170 if (Diags.hasErrorOccurred())
1171 exit(1);
1172
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001173 // Create the Preprocessor.
1174 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1175 SourceMgr, HeaderInfo,
1176 PTHMgr.get()));
1177
1178 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1179 // That argument is used as the IdentifierInfoLookup argument to
1180 // IdentifierTable's ctor.
1181 if (PTHMgr) {
1182 PTHMgr->setPreprocessor(PP.get());
1183 PP->setPTHManager(PTHMgr.take());
1184 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001185
Chris Lattner9d818a22008-04-19 23:25:44 +00001186 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001187 return NULL;
1188 }
1189
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001190 /// FIXME: PP can only handle one callback
1191 if (ProgAction != PrintPreprocessedInput) {
1192 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001193 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001194 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001195 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001196 return NULL;
1197 }
1198 }
1199
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001200 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001201 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001202 }
1203};
1204}
Chris Lattner4b009652007-07-25 00:24:17 +00001205
Chris Lattner4b009652007-07-25 00:24:17 +00001206//===----------------------------------------------------------------------===//
1207// Basic Parser driver
1208//===----------------------------------------------------------------------===//
1209
Chris Lattner9d818a22008-04-19 23:25:44 +00001210static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001211 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001212 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001213
1214 // Parsing the specified input file.
1215 P.ParseTranslationUnit();
1216 delete PA;
1217}
1218
1219//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001220// Code generation options
1221//===----------------------------------------------------------------------===//
1222
1223static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001224GenerateDebugInfo("g",
1225 llvm::cl::desc("Generate source level debug information"));
1226
1227static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001228OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001229
1230// It might be nice to add bounds to the CommandLine library directly.
1231struct OptLevelParser : public llvm::cl::parser<unsigned> {
1232 bool parse(llvm::cl::Option &O, const char *ArgName,
1233 const std::string &Arg, unsigned &Val) {
1234 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1235 return true;
1236 // FIXME: Support -O4.
1237 if (Val > 3)
1238 return O.error(": '" + Arg + "' invalid optimization level!");
1239 return false;
1240 }
1241};
1242static llvm::cl::opt<unsigned, false, OptLevelParser>
1243OptLevel("O", llvm::cl::Prefix,
1244 llvm::cl::desc("Optimization level"),
1245 llvm::cl::init(0));
1246
Daniel Dunbar9101a632009-02-17 19:47:34 +00001247static llvm::cl::opt<std::string>
1248TargetCPU("mcpu",
1249 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1250
Chris Lattner8a9615c2009-03-16 18:41:18 +00001251static void InitializeCompileOptions(CompileOptions &Opts,
1252 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001253 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001254 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001255 if (OptSize) {
1256 // -Os implies -O2
1257 // FIXME: Diagnose conflicting options.
1258 Opts.OptimizationLevel = 2;
1259 } else {
1260 Opts.OptimizationLevel = OptLevel;
1261 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001262
1263 // FIXME: There are llvm-gcc options to control these selectively.
1264 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1265 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001266 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001267
1268#ifdef NDEBUG
1269 Opts.VerifyModule = 0;
1270#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001271
1272 Opts.CPU = TargetCPU;
1273 Opts.Features.insert(Opts.Features.end(),
1274 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001275
1276 // Handle -ftime-report.
1277 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001278}
1279
1280//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001281// Main driver
1282//===----------------------------------------------------------------------===//
1283
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001284/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001285/// action. These consumers can operate on both ASTs that are freshly
1286/// parsed from source files as well as those deserialized from Bitcode.
1287/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001288static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001289 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001290 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001291 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001292 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001293 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001294 default:
1295 return NULL;
1296
1297 case ASTPrint:
1298 return CreateASTPrinter();
1299
1300 case ASTDump:
1301 return CreateASTDumper();
1302
1303 case ASTView:
1304 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001305
Chris Lattner7f902922009-02-18 01:20:05 +00001306 case PrintDeclContext:
1307 return CreateDeclContextPrinter();
1308
1309 case EmitHTML:
1310 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001311
Chris Lattner7f902922009-02-18 01:20:05 +00001312 case InheritanceView:
1313 return CreateInheritanceViewer(InheritanceViewCls);
1314
1315 case TestSerialization:
1316 return CreateSerializationTest(Diag, FileMgr);
1317
1318 case EmitAssembly:
1319 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001320 case EmitBC:
1321 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001322 BackendAction Act;
1323 if (ProgAction == EmitAssembly)
1324 Act = Backend_EmitAssembly;
1325 else if (ProgAction == EmitLLVM)
1326 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001327 else if (ProgAction == EmitLLVMOnly)
1328 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001329 else
1330 Act = Backend_EmitBC;
1331
1332 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001333 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001334 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001335 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001336 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001337
Chris Lattner7f902922009-02-18 01:20:05 +00001338 case SerializeAST:
1339 // FIXME: Allow user to tailor where the file is written.
1340 return CreateASTSerializer(InFile, OutputFile, Diag);
1341
1342 case RewriteObjC:
1343 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001344
Chris Lattner7f902922009-02-18 01:20:05 +00001345 case RewriteBlocks:
1346 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1347
1348 case RunAnalysis:
1349 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001350 }
1351}
1352
Chris Lattner4b009652007-07-25 00:24:17 +00001353/// ProcessInputFile - Process a single input file with the specified state.
1354///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001355static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001356 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001357 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001358 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001359
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001360 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001361 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001362 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1363 PP.getFileManager(), PP.getLangOptions(),
1364 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001365
1366 if (!Consumer) {
1367 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001368 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001369 return;
1370 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001371
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001372 break;
1373
Chris Lattneraf669fb2008-10-12 05:03:36 +00001374 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001375 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001376 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001377 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001378 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001379 RawLex.SetKeepWhitespaceMode(true);
1380
1381 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001382 RawLex.LexFromRawLexer(RawTok);
1383 while (RawTok.isNot(tok::eof)) {
1384 PP.DumpToken(RawTok, true);
1385 fprintf(stderr, "\n");
1386 RawLex.LexFromRawLexer(RawTok);
1387 }
1388 ClearSourceMgr = true;
1389 break;
1390 }
Chris Lattner4b009652007-07-25 00:24:17 +00001391 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001392 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001393 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001394 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001395 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001396 do {
1397 PP.Lex(Tok);
1398 PP.DumpToken(Tok, true);
1399 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001400 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001401 ClearSourceMgr = true;
1402 break;
1403 }
1404 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001405 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001406 Token Tok;
1407 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001408 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001409 do {
1410 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001411 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001412 ClearSourceMgr = true;
1413 break;
1414 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001415
1416 case GeneratePCH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001417 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001418 CacheTokens(PP, OutputFile);
1419 ClearSourceMgr = true;
1420 break;
1421 }
Chris Lattner4b009652007-07-25 00:24:17 +00001422
Chris Lattnerefe33382009-02-18 01:51:21 +00001423 case PrintPreprocessedInput: { // -E mode.
1424 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001425 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001426 ClearSourceMgr = true;
1427 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001428 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001429
Chris Lattnerefe33382009-02-18 01:51:21 +00001430 case ParseNoop: { // -parse-noop
1431 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001432 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001433 ClearSourceMgr = true;
1434 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001435 }
Chris Lattner4b009652007-07-25 00:24:17 +00001436
Chris Lattnerefe33382009-02-18 01:51:21 +00001437 case ParsePrintCallbacks: {
1438 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001439 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001440 ClearSourceMgr = true;
1441 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001442 }
1443
1444 case ParseSyntaxOnly: { // -fsyntax-only
1445 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001446 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001447 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001448 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001449
1450 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001451 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001452 ClearSourceMgr = true;
1453 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001454
Chris Lattnerefe33382009-02-18 01:51:21 +00001455 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001456 DoRewriteTest(PP, InFile, OutputFile);
1457 ClearSourceMgr = true;
1458 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001459 }
Chris Lattnerefe33382009-02-18 01:51:21 +00001460 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001461
1462 if (Consumer) {
1463 TranslationUnit *TU = 0;
1464 if (DisableFree) {
1465 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1466 PP.getSourceManager(),
1467 PP.getTargetInfo(),
1468 PP.getIdentifierTable(),
1469 PP.getSelectorTable(),
1470 /* FreeMemory = */ false);
1471 TU = new TranslationUnit(*Context);
1472 }
1473 ParseAST(PP, Consumer.get(), TU, Stats);
1474 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001475
1476 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001477 if (CheckDiagnostics(PP))
1478 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001479
Chris Lattner4b009652007-07-25 00:24:17 +00001480 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001481 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001482 PP.PrintStats();
1483 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001484 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001485 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001486 fprintf(stderr, "\n");
1487 }
1488
1489 // For a multi-file compilation, some things are ok with nuking the source
1490 // manager tables, other require stable fileid/macroid's across multiple
1491 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001492 if (ClearSourceMgr)
1493 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001494
1495 if (DisableFree)
1496 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001497}
1498
Ted Kremenek80d53372007-12-12 23:41:08 +00001499static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1500 FileManager& FileMgr) {
1501
1502 if (VerifyDiagnostics) {
1503 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1504 exit (1);
1505 }
1506
1507 llvm::sys::Path Filename(InFile);
1508
1509 if (!Filename.isValid()) {
1510 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1511 exit (1);
1512 }
1513
Ted Kremenek863b01f2008-04-23 16:25:39 +00001514 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001515
1516 if (!TU) {
1517 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1518 InFile.c_str());
1519 exit (1);
1520 }
1521
Ted Kremenekab749372007-12-19 19:27:38 +00001522 // Observe that we use the source file name stored in the deserialized
1523 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001524 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001525 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001526 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001527
Ted Kremenek80d53372007-12-12 23:41:08 +00001528 if (!Consumer) {
1529 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1530 exit (1);
1531 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001532
Ted Kremenek863b01f2008-04-23 16:25:39 +00001533 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001534
Chris Lattner8d72ee02008-02-06 01:42:25 +00001535 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001536 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1537 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001538}
1539
1540
Chris Lattner4b009652007-07-25 00:24:17 +00001541static llvm::cl::list<std::string>
1542InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1543
Ted Kremenek80d53372007-12-12 23:41:08 +00001544static bool isSerializedFile(const std::string& InFile) {
1545 if (InFile.size() < 4)
1546 return false;
1547
1548 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00001549 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00001550}
1551
Chris Lattner4b009652007-07-25 00:24:17 +00001552
1553int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001554 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001555 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001556 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001557 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001558
Chris Lattnerefe33382009-02-18 01:51:21 +00001559 if (TimeReport)
1560 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1561
Chris Lattner4b009652007-07-25 00:24:17 +00001562 // If no input was specified, read from stdin.
1563 if (InputFilenames.empty())
1564 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001565
Chris Lattner4b009652007-07-25 00:24:17 +00001566 // Create a file manager object to provide access to and cache the filesystem.
1567 FileManager FileMgr;
1568
Ted Kremenekb240e822007-12-11 23:28:38 +00001569 // Create the diagnostic client for reporting errors or for
1570 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001571 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001572
Ted Kremenek5c341732008-08-07 17:49:57 +00001573 if (!VerifyDiagnostics) {
1574 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001575 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1576 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001577 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00001578 !NoShowLocation,
1579 PrintSourceRangeInfo);
Ted Kremenek5c341732008-08-07 17:49:57 +00001580 } else {
1581 // When checking diagnostics, just buffer them up.
1582 TextDiagClient = new TextDiagnosticBuffer();
1583
1584 if (InputFilenames.size() != 1) {
1585 fprintf(stderr,
1586 "-verify only works on single input files for now.\n");
1587 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001588 }
1589 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001590
Chris Lattner4b009652007-07-25 00:24:17 +00001591 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001592 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1593 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001594 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001595 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001596
Chris Lattner45a56e02007-12-05 23:24:17 +00001597 // -I- is a deprecated GCC feature, scan for it and reject it.
1598 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1599 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001600 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001601 I_dirs.erase(I_dirs.begin()+i);
1602 --i;
1603 }
1604 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001605
1606 // Get information about the target being compiled for.
1607 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001608 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1609
Chris Lattner2c77d852008-03-14 06:12:05 +00001610 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001611 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1612 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001613 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001614 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001615
Daniel Dunbar9c321102009-01-20 23:17:32 +00001616 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001617 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001618
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001619 llvm::OwningPtr<SourceManager> SourceMgr;
1620
Chris Lattner4b009652007-07-25 00:24:17 +00001621 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001622 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001623
Ted Kremenek5c341732008-08-07 17:49:57 +00001624 if (isSerializedFile(InFile)) {
1625 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001626 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00001627 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001628 }
Chris Lattner2b989562009-03-04 21:40:56 +00001629
1630 /// Create a SourceManager object. This tracks and owns all the file
1631 /// buffers allocated to a translation unit.
1632 if (!SourceMgr)
1633 SourceMgr.reset(new SourceManager());
1634 else
1635 SourceMgr->clearIDTables();
1636
1637 // Initialize language options, inferring file types from input filenames.
1638 LangOptions LangInfo;
1639 InitializeBaseLanguage();
1640 LangKind LK = GetLanguage(InFile);
1641 bool PCH = InitializeLangOptions(LangInfo, LK);
1642 InitializeGCMode(LangInfo);
1643 InitializeLanguageStandard(LangInfo, LK, Target.get());
1644
1645 // Process the -I options and set them in the HeaderInfo.
1646 HeaderSearch HeaderInfo(FileMgr);
1647
1648 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1649
1650 // Set up the preprocessor with these options.
1651 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1652 *SourceMgr.get(), HeaderInfo);
1653
1654 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1655
1656 if (!PP)
1657 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001658
Chris Lattner2b989562009-03-04 21:40:56 +00001659 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1660 // always reset to using TextDiagClient.
1661 llvm::OwningPtr<DiagnosticClient> TmpClient;
1662
1663 if (!HTMLDiag.empty()) {
1664 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1665 &PPFactory));
1666 Diags.setClient(TmpClient.get());
Ted Kremenek80d53372007-12-12 23:41:08 +00001667 }
Chris Lattner2b989562009-03-04 21:40:56 +00001668 else
1669 Diags.setClient(TextDiagClient);
1670
1671 // Process the source file.
1672 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1673
1674 HeaderInfo.ClearFileInfo();
Chris Lattner4b009652007-07-25 00:24:17 +00001675 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001676
Mike Stump91d01352009-01-28 02:43:35 +00001677 if (Verbose)
1678 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1679 " hosted on " LLVM_HOSTTRIPLE "\n");
1680
Ted Kremenekec6c5252008-08-07 18:13:12 +00001681 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001682 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1683 (NumDiagnostics == 1 ? "" : "s"));
1684
1685 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001686 FileMgr.PrintStats();
1687 fprintf(stderr, "\n");
1688 }
1689
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001690 // If verifying diagnostics and we reached here, all is well.
1691 if (VerifyDiagnostics)
1692 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001693
1694 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001695
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001696 // Managed static deconstruction. Useful for making things like
1697 // -time-passes usable.
1698 llvm::llvm_shutdown();
1699
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001700 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001701}