blob: c42d375882379ce0cd18525f6a7c7b87cc21c729 [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>
Chris Lattner911b8672009-03-13 22:38:49 +0000234NoBuiltin("fno-builtin",
235 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
236
237
238static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000239MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000240 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000241 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000242
Douglas Gregor23d23262009-02-14 20:49:29 +0000243//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000244// Language Options
245//===----------------------------------------------------------------------===//
246
247enum LangKind {
248 langkind_unspecified,
249 langkind_c,
250 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000251 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000252 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000253 langkind_cxx,
254 langkind_cxx_cpp,
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000255 langkind_cxx_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000256 langkind_objc,
257 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000258 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000259 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000260 langkind_objcxx_cpp,
261 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000262};
263
Chris Lattner4b009652007-07-25 00:24:17 +0000264static llvm::cl::opt<LangKind>
265BaseLang("x", llvm::cl::desc("Base language to compile"),
266 llvm::cl::init(langkind_unspecified),
267 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
268 clEnumValN(langkind_cxx, "c++", "C++"),
269 clEnumValN(langkind_objc, "objective-c", "Objective C"),
270 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000271 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000272 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000273 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
274 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000275 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000276 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000277 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
278 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000279 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000280 "Preprocessed Objective C++"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000281 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000282 "Precompiled C header"),
283 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000284 "Precompiled Objective-C header"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000285 clEnumValN(langkind_cxx_pch, "c++-header",
286 "Precompiled C++ header"),
Ted Kremenekceacc812009-01-09 00:38:08 +0000287 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
288 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000289 clEnumValEnd));
290
291static llvm::cl::opt<bool>
292LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
293 llvm::cl::Hidden);
294static llvm::cl::opt<bool>
295LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
296 llvm::cl::Hidden);
297
Ted Kremenek11ad8952007-12-05 23:49:08 +0000298/// InitializeBaseLanguage - Handle the -x foo options.
299static void InitializeBaseLanguage() {
300 if (LangObjC)
301 BaseLang = langkind_objc;
302 else if (LangObjCXX)
303 BaseLang = langkind_objcxx;
304}
305
306static LangKind GetLanguage(const std::string &Filename) {
307 if (BaseLang != langkind_unspecified)
308 return BaseLang;
309
310 std::string::size_type DotPos = Filename.rfind('.');
311
312 if (DotPos == std::string::npos) {
313 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000314 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000315 }
316
Ted Kremenek11ad8952007-12-05 23:49:08 +0000317 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
318 // C header: .h
319 // C++ header: .hh or .H;
320 // assembler no preprocessing: .s
321 // assembler: .S
322 if (Ext == "c")
323 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000324 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000325 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000326 else if (Ext == "i")
327 return langkind_c_cpp;
328 else if (Ext == "ii")
329 return langkind_cxx_cpp;
330 else if (Ext == "m")
331 return langkind_objc;
332 else if (Ext == "mi")
333 return langkind_objc_cpp;
334 else if (Ext == "mm" || Ext == "M")
335 return langkind_objcxx;
336 else if (Ext == "mii")
337 return langkind_objcxx_cpp;
338 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
339 Ext == "c++" || Ext == "cp" || Ext == "cxx")
340 return langkind_cxx;
341 else
342 return langkind_c;
343}
344
345
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000346static void InitializeCOptions(LangOptions &Options) {
347 // Do nothing.
348}
349
350static void InitializeObjCOptions(LangOptions &Options) {
351 Options.ObjC1 = Options.ObjC2 = 1;
352}
353
354
355static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000356 // FIXME: implement -fpreprocessed mode.
357 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000358 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000359
360 // Test for 'PCH'.
361 switch (LK) {
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000362 default:
363 break;
364 case langkind_c_pch:
365 LK = langkind_c;
366 PCH = true;
367 break;
368 case langkind_objc_pch:
369 LK = langkind_objc;
370 PCH = true;
371 break;
372 case langkind_cxx_pch:
373 LK = langkind_cxx;
374 PCH = true;
375 break;
376 case langkind_objcxx_pch:
377 LK = langkind_objcxx;
378 PCH = true;
379 break;
Ted Kremenekceacc812009-01-09 00:38:08 +0000380 }
Chris Lattner4b009652007-07-25 00:24:17 +0000381
Ted Kremenek11ad8952007-12-05 23:49:08 +0000382 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000383 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000384 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000385 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000386 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000387 case langkind_c_cpp:
388 NoPreprocess = true;
389 // FALLTHROUGH
390 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000391 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000392 break;
393 case langkind_cxx_cpp:
394 NoPreprocess = true;
395 // FALLTHROUGH
396 case langkind_cxx:
397 Options.CPlusPlus = 1;
398 break;
399 case langkind_objc_cpp:
400 NoPreprocess = true;
401 // FALLTHROUGH
402 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000403 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000404 break;
405 case langkind_objcxx_cpp:
406 NoPreprocess = true;
407 // FALLTHROUGH
408 case langkind_objcxx:
409 Options.ObjC1 = Options.ObjC2 = 1;
410 Options.CPlusPlus = 1;
411 break;
412 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000413
414 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000415}
416
417/// LangStds - Language standards we support.
418enum LangStds {
419 lang_unspecified,
420 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000421 lang_gnu_START,
422 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000423 lang_cxx98, lang_gnucxx98,
424 lang_cxx0x, lang_gnucxx0x
425};
426
427static llvm::cl::opt<LangStds>
428LangStd("std", llvm::cl::desc("Language standard to compile for"),
429 llvm::cl::init(lang_unspecified),
430 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
431 clEnumValN(lang_c89, "c90", "ISO C 1990"),
432 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
433 clEnumValN(lang_c94, "iso9899:199409",
434 "ISO C 1990 with amendment 1"),
435 clEnumValN(lang_c99, "c99", "ISO C 1999"),
436// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
437 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
438// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
439 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000440 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000441 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000442 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000443 clEnumValN(lang_gnu99, "gnu9x",
444 "ISO C 1999 with GNU extensions"),
445 clEnumValN(lang_cxx98, "c++98",
446 "ISO C++ 1998 with amendments"),
447 clEnumValN(lang_gnucxx98, "gnu++98",
448 "ISO C++ 1998 with amendments and GNU "
449 "extensions (default for C++)"),
450 clEnumValN(lang_cxx0x, "c++0x",
451 "Upcoming ISO C++ 200x with amendments"),
452 clEnumValN(lang_gnucxx0x, "gnu++0x",
453 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000454 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000455 clEnumValEnd));
456
457static llvm::cl::opt<bool>
458NoOperatorNames("fno-operator-names",
459 llvm::cl::desc("Do not treat C++ operator name keywords as "
460 "synonyms for operators"));
461
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000462static llvm::cl::opt<bool>
463PascalStrings("fpascal-strings",
464 llvm::cl::desc("Recognize and construct Pascal-style "
465 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000466
467static llvm::cl::opt<bool>
468MSExtensions("fms-extensions",
469 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000470 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000471
472static llvm::cl::opt<bool>
473WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000474 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000475
476static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000477NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000478 llvm::cl::desc("Disallow implicit conversions between "
479 "vectors with a different number of "
480 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000481
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000482static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000483EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
484 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
485 llvm::cl::ZeroOrMore);
486
487static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000488EnableHeinousExtensions("fheinous-gnu-extensions",
489 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
490 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
491
492static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000493ObjCNonFragileABI("fobjc-nonfragile-abi",
494 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000495
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000496static llvm::cl::opt<bool>
497EmitAllDecls("femit-all-decls",
498 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000499
Daniel Dunbar91692d92008-08-11 17:36:14 +0000500// FIXME: This (and all GCC -f options) really come in -f... and
501// -fno-... forms, and additionally support automagic behavior when
502// they are not defined. For example, -fexceptions defaults to on or
503// off depending on the language. We should support this behavior in
504// some form (perhaps just add a facility for distinguishing when an
505// has its default value from when it has been set to its default
506// value).
507static llvm::cl::opt<bool>
508Exceptions("fexceptions",
509 llvm::cl::desc("Enable support for exception handling."));
510
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000511static llvm::cl::opt<bool>
512GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000513 llvm::cl::desc("Generate output compatible with the standard GNU "
514 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000515
516static llvm::cl::opt<bool>
517NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000518 llvm::cl::desc("Generate output compatible with the NeXT "
519 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000520
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000521
522
523static llvm::cl::opt<bool>
524Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
525
526static llvm::cl::opt<bool>
527Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
528
Chris Lattner738d3f62009-03-02 22:11:07 +0000529static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000530TargetFeatures("mattr", llvm::cl::CommaSeparated,
531 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
532
Douglas Gregor375733c2009-03-10 00:06:19 +0000533static llvm::cl::opt<unsigned>
534TemplateDepth("ftemplate-depth", llvm::cl::init(99),
535 llvm::cl::desc("Maximum depth of recursive template "
536 "instantiation"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000537
Chris Lattner4b009652007-07-25 00:24:17 +0000538// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000539// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000540static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
541 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000542 // Allow the target to set the default the langauge options as it sees fit.
543 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000544
Chris Lattnerf6790a82009-03-03 19:56:18 +0000545 // If there are any -mattr options, pass them to the target for validation and
546 // processing. The driver should have already consolidated all the
547 // target-feature settings and passed them to us in the -mattr list. The
548 // -mattr list is treated by the code generator as a diff against the -mcpu
549 // setting, but the driver should pass all enabled options as "+" settings.
550 // This means that the target should only look at + settings.
551 if (!TargetFeatures.empty()
552 // FIXME: The driver is not quite yet ready for this.
553 && 0) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000554 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000555 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
556 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000557 if (Opt != -1) {
558 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000559 fprintf(stderr, "invalid feature '%s'\n",
560 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000561 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000562 fprintf(stderr, "feature '%s': %s\n",
563 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000564 exit(1);
565 }
566 }
567
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000568 if (Ansi) // "The -ansi option is equivalent to -std=c89."
569 LangStd = lang_c89;
570
Chris Lattner4b009652007-07-25 00:24:17 +0000571 if (LangStd == lang_unspecified) {
572 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000573 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000574 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000575 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000576 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000577 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000578 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000579 case langkind_objc:
580 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000581 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000582 LangStd = lang_gnu99;
583 break;
584 case langkind_cxx:
585 case langkind_cxx_cpp:
Ted Kremenek6be44de2009-03-19 18:21:42 +0000586 case langkind_cxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000587 case langkind_objcxx:
588 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000589 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000590 LangStd = lang_gnucxx98;
591 break;
592 }
593 }
594
595 switch (LangStd) {
596 default: assert(0 && "Unknown language standard!");
597
598 // Fall through from newer standards to older ones. This isn't really right.
599 // FIXME: Enable specifically the right features based on the language stds.
600 case lang_gnucxx0x:
601 case lang_cxx0x:
602 Options.CPlusPlus0x = 1;
603 // FALL THROUGH
604 case lang_gnucxx98:
605 case lang_cxx98:
606 Options.CPlusPlus = 1;
607 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000608 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000609 // FALL THROUGH.
610 case lang_gnu99:
611 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000612 Options.C99 = 1;
613 Options.HexFloats = 1;
614 // FALL THROUGH.
615 case lang_gnu89:
616 Options.BCPLComment = 1; // Only for C99/C++.
617 // FALL THROUGH.
618 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000619 Options.Digraphs = 1; // C94, C99, C++.
620 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000621 case lang_c89:
622 break;
623 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000624
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000625 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
626 Options.GNUMode = LangStd >= lang_gnu_START;
627
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000628 if (Options.CPlusPlus) {
629 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000630 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000631 }
Chris Lattner4b009652007-07-25 00:24:17 +0000632
Chris Lattner6ab935b2008-04-05 06:32:51 +0000633 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
634 Options.ImplicitInt = 1;
635 else
636 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000637
638 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
639 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000640 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000641 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000642 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000643
Chris Lattner58d5ba52008-12-05 00:10:44 +0000644 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
645 // even if they are normally on for the target. In GNU modes (e.g.
646 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000647 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000648 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000649 Options.Blocks = 0;
650
Daniel Dunbar551236b2009-03-15 00:11:28 +0000651 // Never accept '$' in identifiers when preprocessing assembler.
652 if (LK != langkind_asm_cpp)
653 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000654 if (PascalStrings.getPosition())
655 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000656 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000657 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000658 if (NoLaxVectorConversions.getPosition())
659 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000660 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000661 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000662 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000663
Chris Lattner911b8672009-03-13 22:38:49 +0000664 if (NoBuiltin)
665 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000666 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000667 Options.Freestanding = Options.NoBuiltin = 1;
668
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000669 if (EnableHeinousExtensions)
670 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000671
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000672 Options.MathErrno = MathErrno;
673
Douglas Gregor375733c2009-03-10 00:06:19 +0000674 Options.InstantiationDepth = TemplateDepth;
675
Chris Lattnerddae7102008-12-04 22:54:33 +0000676 // Override the default runtime if the user requested it.
677 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000678 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000679 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000680 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000681
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000682 if (ObjCNonFragileABI)
683 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000684
685 if (EmitAllDecls)
686 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000687}
688
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000689static llvm::cl::opt<bool>
690ObjCExclusiveGC("fobjc-gc-only",
691 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000692 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000693
694static llvm::cl::opt<bool>
695ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000696 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000697
698void InitializeGCMode(LangOptions &Options) {
699 if (ObjCExclusiveGC)
700 Options.setGCMode(LangOptions::GCOnly);
701 else if (ObjCEnableGC)
702 Options.setGCMode(LangOptions::HybridGC);
703}
704
Chris Lattner4b009652007-07-25 00:24:17 +0000705//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000706// Target Triple Processing.
707//===----------------------------------------------------------------------===//
708
709static llvm::cl::opt<std::string>
710TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000711 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000712
Chris Lattnerfc457002008-03-05 01:18:20 +0000713static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000714Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000715
Chris Lattner2b168e02008-09-30 01:13:12 +0000716static llvm::cl::opt<std::string>
717MacOSVersionMin("mmacosx-version-min",
718 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
719
Chris Lattner01de9c82008-09-30 20:16:56 +0000720// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
721// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
722static void HandleMacOSVersionMin(std::string &Triple) {
723 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
724 if (DarwinDashIdx == std::string::npos) {
725 fprintf(stderr,
726 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
727 exit(1);
728 }
729 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
730
Chris Lattner01de9c82008-09-30 20:16:56 +0000731 // Remove the number.
732 Triple.resize(DarwinNumIdx);
733
734 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
735 bool MacOSVersionMinIsInvalid = false;
736 int VersionNum = 0;
737 if (MacOSVersionMin.size() < 4 ||
738 MacOSVersionMin.substr(0, 3) != "10." ||
739 !isdigit(MacOSVersionMin[3])) {
740 MacOSVersionMinIsInvalid = true;
741 } else {
742 const char *Start = MacOSVersionMin.c_str()+3;
743 char *End = 0;
744 VersionNum = (int)strtol(Start, &End, 10);
745
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000746 // The version number must be in the range 0-9.
747 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
748
Chris Lattner01de9c82008-09-30 20:16:56 +0000749 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
750 Triple += llvm::itostr(VersionNum+4);
751
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000752 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
753 // Add the period piece (.7) to the end of the triple. This gives us
754 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000755 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000756 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
757 MacOSVersionMinIsInvalid = true;
758 }
759 }
760
761 if (MacOSVersionMinIsInvalid) {
762 fprintf(stderr,
763 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
764 MacOSVersionMin.c_str());
765 exit(1);
766 }
767}
768
769/// CreateTargetTriple - Process the various options that affect the target
770/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000771static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000772 // Initialize base triple. If a -triple option has been specified, use
773 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000774 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000775 if (Triple.empty()) {
776 Triple = LLVM_HOSTTRIPLE;
777
Daniel Dunbar81caece2008-12-12 18:34:35 +0000778 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
779 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
780 Triple[2] == '8' && Triple[3] == '6')
781 Triple[1] = '3';
782
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000783 // On darwin, we want to update the version to match that of the
784 // host.
785 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
786 if (DarwinDashIdx != std::string::npos) {
787 Triple.resize(DarwinDashIdx + strlen("-darwin"));
788
Daniel Dunbar81caece2008-12-12 18:34:35 +0000789 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000790 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000791 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000792 }
793 }
Ted Kremenek40499482007-12-03 22:06:55 +0000794
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000795 // If -arch foo was specified, remove the architecture from the triple we have
796 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000797 if (!Arch.empty()) {
798 // Decompose the base triple into "arch" and suffix.
799 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000800
Chris Lattner2b168e02008-09-30 01:13:12 +0000801 if (FirstDashIdx == std::string::npos) {
802 fprintf(stderr,
803 "Malformed target triple: \"%s\" ('-' could not be found).\n",
804 Triple.c_str());
805 exit(1);
806 }
Ted Kremenek40499482007-12-03 22:06:55 +0000807
Chris Lattner2b168e02008-09-30 01:13:12 +0000808 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
809 }
810
811 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
812 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000813 if (!MacOSVersionMin.empty())
814 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000815
Chris Lattner2b168e02008-09-30 01:13:12 +0000816 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000817}
818
819//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000820// Preprocessor Initialization
821//===----------------------------------------------------------------------===//
822
823// FIXME: Preprocessor builtins to support.
824// -A... - Play with #assertions
825// -undef - Undefine all predefined macros
826
Chris Lattner695a4f52009-03-13 01:08:23 +0000827// FIXME: -imacros
828
Chris Lattner4b009652007-07-25 00:24:17 +0000829static llvm::cl::list<std::string>
830D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
831 llvm::cl::desc("Predefine the specified macro"));
832static llvm::cl::list<std::string>
833U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
834 llvm::cl::desc("Undefine the specified macro"));
835
Chris Lattner008da782008-01-10 01:53:41 +0000836static llvm::cl::list<std::string>
837ImplicitIncludes("include", llvm::cl::value_desc("file"),
838 llvm::cl::desc("Include file before parsing"));
839
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000840static llvm::cl::opt<std::string>
841ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
842 llvm::cl::desc("Include file before parsing"));
843
Chris Lattner4b009652007-07-25 00:24:17 +0000844// Append a #define line to Buf for Macro. Macro should be of the form XXX,
845// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
846// "#define XXX Y z W". To get a #define with no value, use "XXX=".
847static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
848 const char *Command = "#define ") {
849 Buf.insert(Buf.end(), Command, Command+strlen(Command));
850 if (const char *Equal = strchr(Macro, '=')) {
851 // Turn the = into ' '.
852 Buf.insert(Buf.end(), Macro, Equal);
853 Buf.push_back(' ');
854 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
855 } else {
856 // Push "macroname 1".
857 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
858 Buf.push_back(' ');
859 Buf.push_back('1');
860 }
861 Buf.push_back('\n');
862}
863
Chris Lattner008da782008-01-10 01:53:41 +0000864/// AddImplicitInclude - Add an implicit #include of the specified file to the
865/// predefines buffer.
866static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
867 const char *Inc = "#include \"";
868 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
869 Buf.insert(Buf.end(), File.begin(), File.end());
870 Buf.push_back('"');
871 Buf.push_back('\n');
872}
873
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000874/// AddImplicitIncludePTH - Add an implicit #include using the original file
875/// used to generate a PTH cache.
876static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
877 PTHManager *P = PP.getPTHManager();
878 assert(P && "No PTHManager.");
879 const char *OriginalFile = P->getOriginalSourceFile();
880
881 if (!OriginalFile) {
882 assert(!ImplicitIncludePTH.empty());
883 fprintf(stderr, "error: PTH file '%s' does not designate an original "
884 "source header file for -include-pth\n",
885 ImplicitIncludePTH.c_str());
886 exit (1);
887 }
888
889 AddImplicitInclude(Buf, OriginalFile);
890}
Chris Lattner4b009652007-07-25 00:24:17 +0000891
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000892/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000893/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000894///
Chris Lattner9d818a22008-04-19 23:25:44 +0000895static bool InitializePreprocessor(Preprocessor &PP,
896 bool InitializeSourceMgr,
897 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000898 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000899
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000900 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000901 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000902
903 if (InitializeSourceMgr) {
904 if (InFile != "-") {
905 const FileEntry *File = FileMgr.getFile(InFile);
906 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000907 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +0000908 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
909 << InFile.c_str();
Chris Lattner9d818a22008-04-19 23:25:44 +0000910 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000911 }
912 } else {
913 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
914 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000915 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +0000916 PP.getDiagnostics().Report(FullSourceLoc(),
917 diag::err_fe_error_reading_stdin);
Chris Lattner9d818a22008-04-19 23:25:44 +0000918 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000919 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000920 }
Chris Lattner4b009652007-07-25 00:24:17 +0000921 }
Sam Bishop61a20782008-04-14 14:41:57 +0000922
Chris Lattner47b6a162008-04-19 23:09:31 +0000923 std::vector<char> PredefineBuffer;
924
Chris Lattner4b009652007-07-25 00:24:17 +0000925 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000926 unsigned d = 0, D = D_macros.size();
927 unsigned u = 0, U = U_macros.size();
928 while (d < D || u < U) {
929 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
930 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
931 else
932 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
933 }
934
Chris Lattner008da782008-01-10 01:53:41 +0000935 // FIXME: Read any files specified by -imacros.
936
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000937 // Add implicit #includes from -include and -include-pth.
938 bool handledPTH = ImplicitIncludePTH.empty();
939 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc4ecf322009-03-20 00:40:03 +0000940 if (!handledPTH &&
941 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000942 AddImplicitIncludePTH(PredefineBuffer, PP);
943 handledPTH = true;
944 }
945
Chris Lattner008da782008-01-10 01:53:41 +0000946 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000947 }
948 if (!handledPTH && !ImplicitIncludePTH.empty())
949 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000950
Chris Lattner47b6a162008-04-19 23:09:31 +0000951 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000952 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000953 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000954
955 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000956 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000957}
958
959//===----------------------------------------------------------------------===//
960// Preprocessor include path information.
961//===----------------------------------------------------------------------===//
962
963// This tool exports a large number of command line options to control how the
964// preprocessor searches for header files. At root, however, the Preprocessor
965// object takes a very simple interface: a list of directories to search for
966//
967// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000968// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000969//
Chris Lattner4b009652007-07-25 00:24:17 +0000970
971static llvm::cl::opt<bool>
972nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
973
974// Various command line options. These four add directories to each chain.
975static llvm::cl::list<std::string>
976F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
977 llvm::cl::desc("Add directory to framework include search path"));
978static llvm::cl::list<std::string>
979I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
980 llvm::cl::desc("Add directory to include search path"));
981static llvm::cl::list<std::string>
982idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
983 llvm::cl::desc("Add directory to AFTER include search path"));
984static llvm::cl::list<std::string>
985iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
986 llvm::cl::desc("Add directory to QUOTE include search path"));
987static llvm::cl::list<std::string>
988isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
989 llvm::cl::desc("Add directory to SYSTEM include search path"));
990
991// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
992static llvm::cl::list<std::string>
993iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
994 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
995static llvm::cl::list<std::string>
996iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
997 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
998static llvm::cl::list<std::string>
999iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1000 llvm::cl::Prefix,
1001 llvm::cl::desc("Set directory to include search path with prefix"));
1002
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001003static llvm::cl::opt<std::string>
1004isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1005 llvm::cl::desc("Set the system root directory (usually /)"));
1006
Chris Lattner4b009652007-07-25 00:24:17 +00001007// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001008
Chris Lattner4b009652007-07-25 00:24:17 +00001009/// InitializeIncludePaths - Process the -I options and set them in the
1010/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001011void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1012 FileManager &FM, const LangOptions &Lang) {
1013 InitHeaderSearch Init(Headers, Verbose, isysroot);
1014
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001015 // Handle -I... and -F... options, walking the lists in parallel.
1016 unsigned Iidx = 0, Fidx = 0;
1017 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1018 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001019 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001020 ++Iidx;
1021 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001022 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001023 ++Fidx;
1024 }
1025 }
Chris Lattner4b009652007-07-25 00:24:17 +00001026
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001027 // Consume what's left from whatever list was longer.
1028 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001029 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001030 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001031 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001032
1033 // Handle -idirafter... options.
1034 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001035 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1036 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001037
1038 // Handle -iquote... options.
1039 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001040 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001041
1042 // Handle -isystem... options.
1043 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001044 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001045
1046 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1047 // parallel, processing the values in order of occurance to get the right
1048 // prefixes.
1049 {
1050 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1051 unsigned iprefix_idx = 0;
1052 unsigned iwithprefix_idx = 0;
1053 unsigned iwithprefixbefore_idx = 0;
1054 bool iprefix_done = iprefix_vals.empty();
1055 bool iwithprefix_done = iwithprefix_vals.empty();
1056 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1057 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1058 if (!iprefix_done &&
1059 (iwithprefix_done ||
1060 iprefix_vals.getPosition(iprefix_idx) <
1061 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1062 (iwithprefixbefore_done ||
1063 iprefix_vals.getPosition(iprefix_idx) <
1064 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1065 Prefix = iprefix_vals[iprefix_idx];
1066 ++iprefix_idx;
1067 iprefix_done = iprefix_idx == iprefix_vals.size();
1068 } else if (!iwithprefix_done &&
1069 (iwithprefixbefore_done ||
1070 iwithprefix_vals.getPosition(iwithprefix_idx) <
1071 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001072 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1073 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001074 ++iwithprefix_idx;
1075 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1076 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001077 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1078 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001079 ++iwithprefixbefore_idx;
1080 iwithprefixbefore_done =
1081 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1082 }
1083 }
1084 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001085
Nico Weber770e3882008-08-22 09:25:22 +00001086 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001087
Daniel Dunbar4e604292009-02-21 20:52:41 +00001088 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001089 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001090 llvm::sys::Path::GetMainExecutable(Argv0,
1091 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001092 if (!MainExecutablePath.isEmpty()) {
1093 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1094 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001095
1096 // Get foo/lib/clang/1.0/include
1097 //
1098 // FIXME: Don't embed version here.
1099 MainExecutablePath.appendComponent("lib");
1100 MainExecutablePath.appendComponent("clang");
1101 MainExecutablePath.appendComponent("1.0");
1102 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001103
1104 // We pass true to ignore sysroot so that we *always* look for clang headers
1105 // relative to our executable, never relative to -isysroot.
1106 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1107 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001108 }
1109
Nico Weber770e3882008-08-22 09:25:22 +00001110 if (!nostdinc)
1111 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001112
1113 // Now that we have collected all of the include paths, merge them all
1114 // together and tell the preprocessor about them.
1115
Nico Weber770e3882008-08-22 09:25:22 +00001116 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001117}
1118
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001119//===----------------------------------------------------------------------===//
1120// Driver PreprocessorFactory - For lazily generating preprocessors ...
1121//===----------------------------------------------------------------------===//
1122
1123namespace {
1124class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001125 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001126 Diagnostic &Diags;
1127 const LangOptions &LangInfo;
1128 TargetInfo &Target;
1129 SourceManager &SourceMgr;
1130 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001131 bool InitializeSourceMgr;
1132
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001133public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001134 DriverPreprocessorFactory(const std::string &infile,
1135 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001136 TargetInfo &target, SourceManager &SM,
1137 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001138 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1139 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1140
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001141
1142 virtual ~DriverPreprocessorFactory() {}
1143
1144 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001145 llvm::OwningPtr<PTHManager> PTHMgr;
1146
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001147 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1148 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1149 "options\n");
1150 exit (1);
1151 }
1152
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001153 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001154 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1155 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
1156 PTHMgr.reset(PTHManager::Create(x, &Diags));
1157 }
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>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001210GenerateDebugInfo("g",
1211 llvm::cl::desc("Generate source level debug information"));
1212
1213static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001214OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001215
1216// It might be nice to add bounds to the CommandLine library directly.
1217struct OptLevelParser : public llvm::cl::parser<unsigned> {
1218 bool parse(llvm::cl::Option &O, const char *ArgName,
1219 const std::string &Arg, unsigned &Val) {
1220 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1221 return true;
1222 // FIXME: Support -O4.
1223 if (Val > 3)
1224 return O.error(": '" + Arg + "' invalid optimization level!");
1225 return false;
1226 }
1227};
1228static llvm::cl::opt<unsigned, false, OptLevelParser>
1229OptLevel("O", llvm::cl::Prefix,
1230 llvm::cl::desc("Optimization level"),
1231 llvm::cl::init(0));
1232
Daniel Dunbar9101a632009-02-17 19:47:34 +00001233static llvm::cl::opt<std::string>
1234TargetCPU("mcpu",
1235 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1236
Chris Lattner8a9615c2009-03-16 18:41:18 +00001237static void InitializeCompileOptions(CompileOptions &Opts,
1238 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001239 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001240 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001241 if (OptSize) {
1242 // -Os implies -O2
1243 // FIXME: Diagnose conflicting options.
1244 Opts.OptimizationLevel = 2;
1245 } else {
1246 Opts.OptimizationLevel = OptLevel;
1247 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001248
1249 // FIXME: There are llvm-gcc options to control these selectively.
1250 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1251 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001252 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001253
1254#ifdef NDEBUG
1255 Opts.VerifyModule = 0;
1256#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001257
1258 Opts.CPU = TargetCPU;
1259 Opts.Features.insert(Opts.Features.end(),
1260 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001261
1262 // Handle -ftime-report.
1263 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001264}
1265
1266//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001267// Main driver
1268//===----------------------------------------------------------------------===//
1269
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001270/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001271/// action. These consumers can operate on both ASTs that are freshly
1272/// parsed from source files as well as those deserialized from Bitcode.
1273/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001274static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001275 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001276 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001277 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001278 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001279 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001280 default:
1281 return NULL;
1282
1283 case ASTPrint:
1284 return CreateASTPrinter();
1285
1286 case ASTDump:
1287 return CreateASTDumper();
1288
1289 case ASTView:
1290 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001291
Chris Lattner7f902922009-02-18 01:20:05 +00001292 case PrintDeclContext:
1293 return CreateDeclContextPrinter();
1294
1295 case EmitHTML:
1296 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001297
Chris Lattner7f902922009-02-18 01:20:05 +00001298 case InheritanceView:
1299 return CreateInheritanceViewer(InheritanceViewCls);
1300
1301 case TestSerialization:
1302 return CreateSerializationTest(Diag, FileMgr);
1303
1304 case EmitAssembly:
1305 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001306 case EmitBC:
1307 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001308 BackendAction Act;
1309 if (ProgAction == EmitAssembly)
1310 Act = Backend_EmitAssembly;
1311 else if (ProgAction == EmitLLVM)
1312 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001313 else if (ProgAction == EmitLLVMOnly)
1314 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001315 else
1316 Act = Backend_EmitBC;
1317
1318 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001319 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001320 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001321 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001322 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001323
Chris Lattner7f902922009-02-18 01:20:05 +00001324 case SerializeAST:
1325 // FIXME: Allow user to tailor where the file is written.
1326 return CreateASTSerializer(InFile, OutputFile, Diag);
1327
1328 case RewriteObjC:
1329 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001330
Chris Lattner7f902922009-02-18 01:20:05 +00001331 case RewriteBlocks:
1332 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1333
1334 case RunAnalysis:
1335 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001336 }
1337}
1338
Chris Lattner4b009652007-07-25 00:24:17 +00001339/// ProcessInputFile - Process a single input file with the specified state.
1340///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001341static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001342 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001343 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001344 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001345
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001346 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001347 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001348 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1349 PP.getFileManager(), PP.getLangOptions(),
1350 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001351
1352 if (!Consumer) {
1353 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001354 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001355 return;
1356 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001357
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001358 break;
1359
Chris Lattneraf669fb2008-10-12 05:03:36 +00001360 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001361 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001362 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001363 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001364 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001365 RawLex.SetKeepWhitespaceMode(true);
1366
1367 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001368 RawLex.LexFromRawLexer(RawTok);
1369 while (RawTok.isNot(tok::eof)) {
1370 PP.DumpToken(RawTok, true);
1371 fprintf(stderr, "\n");
1372 RawLex.LexFromRawLexer(RawTok);
1373 }
1374 ClearSourceMgr = true;
1375 break;
1376 }
Chris Lattner4b009652007-07-25 00:24:17 +00001377 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001378 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001379 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001380 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001381 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001382 do {
1383 PP.Lex(Tok);
1384 PP.DumpToken(Tok, true);
1385 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001386 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001387 ClearSourceMgr = true;
1388 break;
1389 }
1390 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001391 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001392 Token Tok;
1393 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001394 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001395 do {
1396 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001397 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001398 ClearSourceMgr = true;
1399 break;
1400 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001401
1402 case GeneratePCH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001403 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001404 CacheTokens(PP, OutputFile);
1405 ClearSourceMgr = true;
1406 break;
1407 }
Chris Lattner4b009652007-07-25 00:24:17 +00001408
Chris Lattnerefe33382009-02-18 01:51:21 +00001409 case PrintPreprocessedInput: { // -E mode.
1410 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001411 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001412 ClearSourceMgr = true;
1413 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001414 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001415
Chris Lattnerefe33382009-02-18 01:51:21 +00001416 case ParseNoop: { // -parse-noop
1417 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001418 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001419 ClearSourceMgr = true;
1420 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001421 }
Chris Lattner4b009652007-07-25 00:24:17 +00001422
Chris Lattnerefe33382009-02-18 01:51:21 +00001423 case ParsePrintCallbacks: {
1424 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001425 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001426 ClearSourceMgr = true;
1427 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001428 }
1429
1430 case ParseSyntaxOnly: { // -fsyntax-only
1431 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001432 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001433 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001434 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001435
1436 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001437 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001438 ClearSourceMgr = true;
1439 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001440
Chris Lattnerefe33382009-02-18 01:51:21 +00001441 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001442 DoRewriteTest(PP, InFile, OutputFile);
1443 ClearSourceMgr = true;
1444 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001445 }
Chris Lattnerefe33382009-02-18 01:51:21 +00001446 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001447
1448 if (Consumer) {
1449 TranslationUnit *TU = 0;
1450 if (DisableFree) {
1451 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1452 PP.getSourceManager(),
1453 PP.getTargetInfo(),
1454 PP.getIdentifierTable(),
1455 PP.getSelectorTable(),
1456 /* FreeMemory = */ false);
1457 TU = new TranslationUnit(*Context);
1458 }
1459 ParseAST(PP, Consumer.get(), TU, Stats);
1460 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001461
1462 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001463 if (CheckDiagnostics(PP))
1464 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001465
Chris Lattner4b009652007-07-25 00:24:17 +00001466 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001467 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001468 PP.PrintStats();
1469 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001470 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001471 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001472 fprintf(stderr, "\n");
1473 }
1474
1475 // For a multi-file compilation, some things are ok with nuking the source
1476 // manager tables, other require stable fileid/macroid's across multiple
1477 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001478 if (ClearSourceMgr)
1479 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001480
1481 if (DisableFree)
1482 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001483}
1484
Ted Kremenek80d53372007-12-12 23:41:08 +00001485static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1486 FileManager& FileMgr) {
1487
1488 if (VerifyDiagnostics) {
1489 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1490 exit (1);
1491 }
1492
1493 llvm::sys::Path Filename(InFile);
1494
1495 if (!Filename.isValid()) {
1496 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1497 exit (1);
1498 }
1499
Ted Kremenek863b01f2008-04-23 16:25:39 +00001500 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001501
1502 if (!TU) {
1503 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1504 InFile.c_str());
1505 exit (1);
1506 }
1507
Ted Kremenekab749372007-12-19 19:27:38 +00001508 // Observe that we use the source file name stored in the deserialized
1509 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001510 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001511 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001512 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001513
Ted Kremenek80d53372007-12-12 23:41:08 +00001514 if (!Consumer) {
1515 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1516 exit (1);
1517 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001518
Ted Kremenek863b01f2008-04-23 16:25:39 +00001519 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001520
Chris Lattner8d72ee02008-02-06 01:42:25 +00001521 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001522 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1523 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001524}
1525
1526
Chris Lattner4b009652007-07-25 00:24:17 +00001527static llvm::cl::list<std::string>
1528InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1529
Ted Kremenek80d53372007-12-12 23:41:08 +00001530static bool isSerializedFile(const std::string& InFile) {
1531 if (InFile.size() < 4)
1532 return false;
1533
1534 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00001535 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00001536}
1537
Chris Lattner4b009652007-07-25 00:24:17 +00001538
1539int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001540 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001541 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001542 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001543 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001544
Chris Lattnerefe33382009-02-18 01:51:21 +00001545 if (TimeReport)
1546 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
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,
Chris Lattner695a4f52009-03-13 01:08:23 +00001564 !NoShowLocation,
1565 PrintSourceRangeInfo);
Ted Kremenek5c341732008-08-07 17:49:57 +00001566 } else {
1567 // When checking diagnostics, just buffer them up.
1568 TextDiagClient = new TextDiagnosticBuffer();
1569
1570 if (InputFilenames.size() != 1) {
1571 fprintf(stderr,
1572 "-verify only works on single input files for now.\n");
1573 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001574 }
1575 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001576
Chris Lattner4b009652007-07-25 00:24:17 +00001577 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001578 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1579 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001580 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001581 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001582
Chris Lattner45a56e02007-12-05 23:24:17 +00001583 // -I- is a deprecated GCC feature, scan for it and reject it.
1584 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1585 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001586 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001587 I_dirs.erase(I_dirs.begin()+i);
1588 --i;
1589 }
1590 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001591
1592 // Get information about the target being compiled for.
1593 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001594 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1595
Chris Lattner2c77d852008-03-14 06:12:05 +00001596 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001597 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1598 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001599 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001600 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001601
Daniel Dunbar9c321102009-01-20 23:17:32 +00001602 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001603 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001604
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001605 llvm::OwningPtr<SourceManager> SourceMgr;
1606
Chris Lattner4b009652007-07-25 00:24:17 +00001607 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001608 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001609
Ted Kremenek5c341732008-08-07 17:49:57 +00001610 if (isSerializedFile(InFile)) {
1611 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001612 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00001613 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001614 }
Chris Lattner2b989562009-03-04 21:40:56 +00001615
1616 /// Create a SourceManager object. This tracks and owns all the file
1617 /// buffers allocated to a translation unit.
1618 if (!SourceMgr)
1619 SourceMgr.reset(new SourceManager());
1620 else
1621 SourceMgr->clearIDTables();
1622
1623 // Initialize language options, inferring file types from input filenames.
1624 LangOptions LangInfo;
1625 InitializeBaseLanguage();
1626 LangKind LK = GetLanguage(InFile);
1627 bool PCH = InitializeLangOptions(LangInfo, LK);
1628 InitializeGCMode(LangInfo);
1629 InitializeLanguageStandard(LangInfo, LK, Target.get());
1630
1631 // Process the -I options and set them in the HeaderInfo.
1632 HeaderSearch HeaderInfo(FileMgr);
1633
1634 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1635
1636 // Set up the preprocessor with these options.
1637 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1638 *SourceMgr.get(), HeaderInfo);
1639
1640 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1641
1642 if (!PP)
1643 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001644
Chris Lattner2b989562009-03-04 21:40:56 +00001645 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1646 // always reset to using TextDiagClient.
1647 llvm::OwningPtr<DiagnosticClient> TmpClient;
1648
1649 if (!HTMLDiag.empty()) {
1650 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1651 &PPFactory));
1652 Diags.setClient(TmpClient.get());
Ted Kremenek80d53372007-12-12 23:41:08 +00001653 }
Chris Lattner2b989562009-03-04 21:40:56 +00001654 else
1655 Diags.setClient(TextDiagClient);
1656
1657 // Process the source file.
1658 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1659
1660 HeaderInfo.ClearFileInfo();
Chris Lattner4b009652007-07-25 00:24:17 +00001661 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001662
Mike Stump91d01352009-01-28 02:43:35 +00001663 if (Verbose)
1664 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1665 " hosted on " LLVM_HOSTTRIPLE "\n");
1666
Ted Kremenekec6c5252008-08-07 18:13:12 +00001667 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001668 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1669 (NumDiagnostics == 1 ? "" : "s"));
1670
1671 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001672 FileMgr.PrintStats();
1673 fprintf(stderr, "\n");
1674 }
1675
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001676 // If verifying diagnostics and we reached here, all is well.
1677 if (VerifyDiagnostics)
1678 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001679
1680 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001681
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001682 // Managed static deconstruction. Useful for making things like
1683 // -time-passes usable.
1684 llvm::llvm_shutdown();
1685
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001686 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001687}