blob: a2ec08a1546e5d4e4cafbdc76da8fab9937e9d64 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000029#include "clang/Frontend/InitHeaderSearch.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000030#include "clang/Frontend/PathDiagnosticClients.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000031#include "clang/Frontend/TextDiagnosticBuffer.h"
32#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000033#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000034#include "clang/AST/Decl.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000035#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000036#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000037#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000038#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000039#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040#include "clang/Parse/Parser.h"
41#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000042#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000043#include "clang/Basic/FileManager.h"
44#include "clang/Basic/SourceManager.h"
45#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000046#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000047#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000048#include "llvm/ADT/StringExtras.h"
49#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000050#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000051#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000052#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000053#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000054#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000055#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000056#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000057#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000058#include "llvm/System/Signals.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000059using namespace clang;
60
61//===----------------------------------------------------------------------===//
62// Global options.
63//===----------------------------------------------------------------------===//
64
Chris Lattner47099742009-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 Dunbard3db4012008-10-16 16:54:18 +000070static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +000071
Reid Spencer5f016e22007-07-11 17:01:13 +000072static llvm::cl::opt<bool>
73Verbose("v", llvm::cl::desc("Enable verbose output"));
74static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000075Stats("print-stats",
76 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-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));
Reid Spencer5f016e22007-07-11 17:01:13 +000081
82enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000083 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000084 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000085 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000086 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +000087 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000088 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000089 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000090 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +000091 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000092 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000093 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-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 Xu2d75d6f2009-01-13 01:29:24 +000097 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000098 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerc106c102008-10-12 05:03:36 +0000104 DumpTokens, // Dump out preprocessed tokens.
105 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000106 RunAnalysis, // Run one or more source code analyses.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000107 GeneratePCH, // Generate precompiled header.
108 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerc106c102008-10-12 05:03:36 +0000119 clEnumValN(DumpRawTokens, "dump-raw-tokens",
120 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000121 clEnumValN(RunAnalysis, "analyze",
122 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000123 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek6a340832008-03-18 21:19:49 +0000131 clEnumValN(EmitHTML, "emit-html",
132 "Output input source as HTML"),
Chris Lattner3b427b32007-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 Lattnerea254db2007-10-11 00:37:43 +0000137 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000138 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000139 clEnumValN(PrintDeclContext, "print-decl-contexts",
140 "Print DeclContexts and their Decls."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000141 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000142 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000143 clEnumValN(EmitAssembly, "S",
144 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000145 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000146 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000147 clEnumValN(EmitBC, "emit-llvm-bc",
148 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000149 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
150 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000151 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000152 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000153 clEnumValN(RewriteTest, "rewrite-test",
154 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000155 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-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 Naroff13188952008-09-18 14:10:13 +0000159 clEnumValN(RewriteBlocks, "rewrite-blocks",
160 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000161 clEnumValEnd));
162
Ted Kremenekccc76472007-12-19 19:47:59 +0000163
164static llvm::cl::opt<std::string>
165OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000166 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000167 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000168
Ted Kremenekc2e72992008-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 Guptae8b9f5b2008-05-08 08:54:20 +0000178//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000179// Diagnostic Options
180//===----------------------------------------------------------------------===//
181
Ted Kremenek41193e42007-09-26 19:42:19 +0000182static llvm::cl::opt<bool>
183VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000184 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000185
Ted Kremenek88f5cde2008-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 Weberfd54ebc2008-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 Lattner65f5e642009-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 Weberfd54ebc2008-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 Lattner1fbee5d2009-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 Weberfd54ebc2008-08-05 23:33:20 +0000209
Reid Spencer5f016e22007-07-11 17:01:13 +0000210//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-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 Dunbard77b2512009-01-14 18:56:36 +0000217 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000218
219//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000220// Builtin Options
221//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-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 Gregor3573c0c2009-02-14 20:49:29 +0000228static llvm::cl::opt<bool>
229Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000230 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000231 "freestanding environment"));
232
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000233static llvm::cl::opt<bool>
Chris Lattner7644f072009-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 Dunbaref2abfe2009-02-16 22:43:43 +0000239MathErrno("fmath-errno",
Chris Lattner5ea9d1b2009-02-17 00:30:31 +0000240 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner5bef8dd2009-02-17 00:35:09 +0000241 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000242
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000243//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000244// Language Options
245//===----------------------------------------------------------------------===//
246
247enum LangKind {
248 langkind_unspecified,
249 langkind_c,
250 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000251 langkind_asm_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000252 langkind_c_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 langkind_cxx,
254 langkind_cxx_cpp,
Chris Lattnerc76d8072009-02-06 06:19:20 +0000255 langkind_cxx_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 langkind_objc,
257 langkind_objc_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000258 langkind_objc_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 langkind_objcxx,
Ted Kremenekf8901912009-01-09 00:38:08 +0000260 langkind_objcxx_cpp,
261 langkind_objcxx_pch
Reid Spencer5f016e22007-07-11 17:01:13 +0000262};
263
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbard2ea3862009-01-29 23:50:47 +0000271 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000273 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
274 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000275 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000276 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
278 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000279 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 "Preprocessed Objective C++"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000281 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek85888962008-10-21 00:54:44 +0000282 "Precompiled C header"),
283 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekf8901912009-01-09 00:38:08 +0000284 "Precompiled Objective-C header"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000285 clEnumValN(langkind_cxx_pch, "c++-header",
286 "Precompiled C++ header"),
Ted Kremenekf8901912009-01-09 00:38:08 +0000287 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
288 "Precompiled Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek8904f152007-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 Lattner9b2f6c42008-01-04 19:12:28 +0000314 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 }
316
Ted Kremenek8904f152007-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 Lattner1b450b02008-10-28 20:33:42 +0000324 else if (Ext == "S")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000325 return langkind_asm_cpp;
Ted Kremenek8904f152007-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 Kremenek85888962008-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){
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 // FIXME: implement -fpreprocessed mode.
357 bool NoPreprocess = false;
Ted Kremenek85888962008-10-21 00:54:44 +0000358 bool PCH = false;
Ted Kremenekf8901912009-01-09 00:38:08 +0000359
360 // Test for 'PCH'.
361 switch (LK) {
Chris Lattnerc76d8072009-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 Kremenekf8901912009-01-09 00:38:08 +0000380 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000381
Ted Kremenek8904f152007-12-05 23:49:08 +0000382 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000384 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000385 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000386 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 case langkind_c_cpp:
388 NoPreprocess = true;
389 // FALLTHROUGH
390 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000391 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek85888962008-10-21 00:54:44 +0000403 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek85888962008-10-21 00:54:44 +0000413
414 return PCH;
Reid Spencer5f016e22007-07-11 17:01:13 +0000415}
416
417/// LangStds - Language standards we support.
418enum LangStds {
419 lang_unspecified,
420 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000421 lang_gnu_START,
422 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000423 lang_cxx98, lang_gnucxx98,
424 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000425};
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 Greif10b26142009-02-28 09:22:15 +0000440 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000441 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000442 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +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++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000450 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 Greif5f8d1db2009-03-11 23:07:18 +0000454 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +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 Carlssonee98ac52007-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 Naroffd62701b2008-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 Gupta56cf96b2008-05-08 08:28:14 +0000470 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000471
472static llvm::cl::opt<bool>
473WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000474 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000475
476static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000477NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-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 Lattnerae0ee032008-12-04 23:20:07 +0000481
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000482static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-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 Lattner810f6d52009-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 Stumpa0f02aa2009-02-02 22:57:57 +0000493ObjCNonFragileABI("fobjc-nonfragile-abi",
494 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000495
Daniel Dunbard604c402009-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 Kremenek01d9dbf2008-04-29 04:37:03 +0000499
Daniel Dunbar6379a7a2008-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 Dunbarf77ac862008-08-11 21:35:06 +0000511static llvm::cl::opt<bool>
512GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000513 llvm::cl::desc("Generate output compatible with the standard GNU "
514 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000515
516static llvm::cl::opt<bool>
517NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000518 llvm::cl::desc("Generate output compatible with the NeXT "
519 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000520
Ted Kremenekea644d82008-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 Lattner16167a62009-03-02 22:11:07 +0000529static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000530TargetFeatures("mattr", llvm::cl::CommaSeparated,
531 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
532
Douglas Gregor26dce442009-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 Lattner16167a62009-03-02 22:11:07 +0000537
Reid Spencer5f016e22007-07-11 17:01:13 +0000538// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000539// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000540static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
541 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-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 Kremenekea644d82008-09-03 21:22:16 +0000544
Chris Lattner6328cc32009-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 Lattner16167a62009-03-02 22:11:07 +0000554 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000555 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
556 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000557 if (Opt != -1) {
558 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000559 fprintf(stderr, "invalid feature '%s'\n",
560 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000561 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000562 fprintf(stderr, "feature '%s': %s\n",
563 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000564 exit(1);
565 }
566 }
567
Ted Kremenekea644d82008-09-03 21:22:16 +0000568 if (Ansi) // "The -ansi option is equivalent to -std=c89."
569 LangStd = lang_c89;
570
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 if (LangStd == lang_unspecified) {
572 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000573 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 default: assert(0 && "Unknown base language");
575 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000576 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 case langkind_c_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000578 case langkind_c_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 case langkind_objc:
580 case langkind_objc_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000581 case langkind_objc_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 LangStd = lang_gnu99;
583 break;
584 case langkind_cxx:
585 case langkind_cxx_cpp:
Ted Kremenekab56c5d2009-03-19 18:21:42 +0000586 case langkind_cxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 case langkind_objcxx:
588 case langkind_objcxx_cpp:
Ted Kremenekf8901912009-01-09 00:38:08 +0000589 case langkind_objcxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +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.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000600 case lang_gnucxx0x:
601 case lang_cxx0x:
602 Options.CPlusPlus0x = 1;
603 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 case lang_gnucxx98:
605 case lang_cxx98:
606 Options.CPlusPlus = 1;
607 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000608 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000609 // FALL THROUGH.
610 case lang_gnu99:
611 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner3426b9b2008-02-25 04:01:39 +0000619 Options.Digraphs = 1; // C94, C99, C++.
620 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000621 case lang_c89:
622 break;
623 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000624
625 if (Options.CPlusPlus) {
626 Options.C99 = 0;
627 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
628 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000629
Chris Lattnerd658b562008-04-05 06:32:51 +0000630 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
631 Options.ImplicitInt = 1;
632 else
633 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000634
635 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
636 // is specified, or -std is set to a conforming mode.
Chris Lattner802db9b2008-12-05 00:10:44 +0000637 Options.Trigraphs = LangStd < lang_gnu_START;
638 if (Trigraphs.getPosition())
639 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenekea644d82008-09-03 21:22:16 +0000640
Chris Lattner802db9b2008-12-05 00:10:44 +0000641 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
642 // even if they are normally on for the target. In GNU modes (e.g.
643 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000644 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
645 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner802db9b2008-12-05 00:10:44 +0000646 Options.Blocks = 0;
647
Daniel Dunbar85c49102009-03-15 00:11:28 +0000648 // Never accept '$' in identifiers when preprocessing assembler.
649 if (LK != langkind_asm_cpp)
650 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000651 if (PascalStrings.getPosition())
652 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000653 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000654 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000655 if (NoLaxVectorConversions.getPosition())
656 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000657 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000658 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000659 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000660
Chris Lattner7644f072009-03-13 22:38:49 +0000661 if (NoBuiltin)
662 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000663 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000664 Options.Freestanding = Options.NoBuiltin = 1;
665
Chris Lattner810f6d52009-03-13 17:38:01 +0000666 if (EnableHeinousExtensions)
667 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000668
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000669 Options.MathErrno = MathErrno;
670
Douglas Gregor26dce442009-03-10 00:06:19 +0000671 Options.InstantiationDepth = TemplateDepth;
672
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000673 // Override the default runtime if the user requested it.
674 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000675 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000676 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000677 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000678
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000679 if (ObjCNonFragileABI)
680 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000681
682 if (EmitAllDecls)
683 Options.EmitAllDecls = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000684}
685
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000686static llvm::cl::opt<bool>
687ObjCExclusiveGC("fobjc-gc-only",
688 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000689 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000690
691static llvm::cl::opt<bool>
692ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000693 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000694
695void InitializeGCMode(LangOptions &Options) {
696 if (ObjCExclusiveGC)
697 Options.setGCMode(LangOptions::GCOnly);
698 else if (ObjCEnableGC)
699 Options.setGCMode(LangOptions::HybridGC);
700}
701
Reid Spencer5f016e22007-07-11 17:01:13 +0000702//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000703// Target Triple Processing.
704//===----------------------------------------------------------------------===//
705
706static llvm::cl::opt<std::string>
707TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000708 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000709
Chris Lattner42e67372008-03-05 01:18:20 +0000710static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000711Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000712
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000713static llvm::cl::opt<std::string>
714MacOSVersionMin("mmacosx-version-min",
715 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
716
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000717// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
718// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
719static void HandleMacOSVersionMin(std::string &Triple) {
720 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
721 if (DarwinDashIdx == std::string::npos) {
722 fprintf(stderr,
723 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
724 exit(1);
725 }
726 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
727
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000728 // Remove the number.
729 Triple.resize(DarwinNumIdx);
730
731 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
732 bool MacOSVersionMinIsInvalid = false;
733 int VersionNum = 0;
734 if (MacOSVersionMin.size() < 4 ||
735 MacOSVersionMin.substr(0, 3) != "10." ||
736 !isdigit(MacOSVersionMin[3])) {
737 MacOSVersionMinIsInvalid = true;
738 } else {
739 const char *Start = MacOSVersionMin.c_str()+3;
740 char *End = 0;
741 VersionNum = (int)strtol(Start, &End, 10);
742
Chris Lattner079f2c462008-09-30 20:30:12 +0000743 // The version number must be in the range 0-9.
744 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
745
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000746 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
747 Triple += llvm::itostr(VersionNum+4);
748
Chris Lattner079f2c462008-09-30 20:30:12 +0000749 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
750 // Add the period piece (.7) to the end of the triple. This gives us
751 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000752 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000753 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
754 MacOSVersionMinIsInvalid = true;
755 }
756 }
757
758 if (MacOSVersionMinIsInvalid) {
759 fprintf(stderr,
760 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
761 MacOSVersionMin.c_str());
762 exit(1);
763 }
764}
765
766/// CreateTargetTriple - Process the various options that affect the target
767/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000768static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000769 // Initialize base triple. If a -triple option has been specified, use
770 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000771 std::string Triple = TargetTriple;
Daniel Dunbare553a722008-10-02 01:21:33 +0000772 if (Triple.empty()) {
773 Triple = LLVM_HOSTTRIPLE;
774
Daniel Dunbara6291902008-12-12 18:34:35 +0000775 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
776 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
777 Triple[2] == '8' && Triple[3] == '6')
778 Triple[1] = '3';
779
Daniel Dunbare553a722008-10-02 01:21:33 +0000780 // On darwin, we want to update the version to match that of the
781 // host.
782 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
783 if (DarwinDashIdx != std::string::npos) {
784 Triple.resize(DarwinDashIdx + strlen("-darwin"));
785
Daniel Dunbara6291902008-12-12 18:34:35 +0000786 // Only add the major part of the os version.
Chris Lattnera05ff452009-01-22 20:57:52 +0000787 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbara6291902008-12-12 18:34:35 +0000788 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbare553a722008-10-02 01:21:33 +0000789 }
790 }
Ted Kremenekae360762007-12-03 22:06:55 +0000791
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000792 // If -arch foo was specified, remove the architecture from the triple we have
793 // so far and replace it with the specified one.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000794 if (!Arch.empty()) {
795 // Decompose the base triple into "arch" and suffix.
796 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000797
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000798 if (FirstDashIdx == std::string::npos) {
799 fprintf(stderr,
800 "Malformed target triple: \"%s\" ('-' could not be found).\n",
801 Triple.c_str());
802 exit(1);
803 }
Ted Kremenekae360762007-12-03 22:06:55 +0000804
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000805 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
806 }
807
808 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
809 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000810 if (!MacOSVersionMin.empty())
811 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000812
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000813 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000814}
815
816//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000817// Preprocessor Initialization
818//===----------------------------------------------------------------------===//
819
820// FIXME: Preprocessor builtins to support.
821// -A... - Play with #assertions
822// -undef - Undefine all predefined macros
823
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000824// FIXME: -imacros
825
Reid Spencer5f016e22007-07-11 17:01:13 +0000826static llvm::cl::list<std::string>
827D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
828 llvm::cl::desc("Predefine the specified macro"));
829static llvm::cl::list<std::string>
830U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
831 llvm::cl::desc("Undefine the specified macro"));
832
Chris Lattner64299f82008-01-10 01:53:41 +0000833static llvm::cl::list<std::string>
834ImplicitIncludes("include", llvm::cl::value_desc("file"),
835 llvm::cl::desc("Include file before parsing"));
836
Reid Spencer5f016e22007-07-11 17:01:13 +0000837// Append a #define line to Buf for Macro. Macro should be of the form XXX,
838// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
839// "#define XXX Y z W". To get a #define with no value, use "XXX=".
840static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
841 const char *Command = "#define ") {
842 Buf.insert(Buf.end(), Command, Command+strlen(Command));
843 if (const char *Equal = strchr(Macro, '=')) {
844 // Turn the = into ' '.
845 Buf.insert(Buf.end(), Macro, Equal);
846 Buf.push_back(' ');
847 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
848 } else {
849 // Push "macroname 1".
850 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
851 Buf.push_back(' ');
852 Buf.push_back('1');
853 }
854 Buf.push_back('\n');
855}
856
Chris Lattner64299f82008-01-10 01:53:41 +0000857/// AddImplicitInclude - Add an implicit #include of the specified file to the
858/// predefines buffer.
859static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
860 const char *Inc = "#include \"";
861 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
862 Buf.insert(Buf.end(), File.begin(), File.end());
863 Buf.push_back('"');
864 Buf.push_back('\n');
865}
866
Reid Spencer5f016e22007-07-11 17:01:13 +0000867
Chris Lattner53b0dab2007-10-09 22:10:18 +0000868/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000869/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000870///
Chris Lattner51574ea2008-04-19 23:25:44 +0000871static bool InitializePreprocessor(Preprocessor &PP,
872 bool InitializeSourceMgr,
873 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000874 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000875
Chris Lattner53b0dab2007-10-09 22:10:18 +0000876 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000877 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000878
879 if (InitializeSourceMgr) {
880 if (InFile != "-") {
881 const FileEntry *File = FileMgr.getFile(InFile);
882 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +0000883 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000884 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
885 << InFile.c_str();
Chris Lattner51574ea2008-04-19 23:25:44 +0000886 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000887 }
888 } else {
889 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
890 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000891 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000892 PP.getDiagnostics().Report(FullSourceLoc(),
893 diag::err_fe_error_reading_stdin);
Chris Lattner51574ea2008-04-19 23:25:44 +0000894 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000895 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000896 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000898
Chris Lattneraa391972008-04-19 23:09:31 +0000899 std::vector<char> PredefineBuffer;
900
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000902 unsigned d = 0, D = D_macros.size();
903 unsigned u = 0, U = U_macros.size();
904 while (d < D || u < U) {
905 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
906 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
907 else
908 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
909 }
910
Chris Lattner64299f82008-01-10 01:53:41 +0000911 // FIXME: Read any files specified by -imacros.
912
913 // Add implicit #includes from -include.
914 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
915 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000916
Chris Lattneraa391972008-04-19 23:09:31 +0000917 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000918 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000919 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000920
921 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000922 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000923}
924
925//===----------------------------------------------------------------------===//
926// Preprocessor include path information.
927//===----------------------------------------------------------------------===//
928
929// This tool exports a large number of command line options to control how the
930// preprocessor searches for header files. At root, however, the Preprocessor
931// object takes a very simple interface: a list of directories to search for
932//
933// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000934// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000935//
Reid Spencer5f016e22007-07-11 17:01:13 +0000936
937static llvm::cl::opt<bool>
938nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
939
940// Various command line options. These four add directories to each chain.
941static llvm::cl::list<std::string>
942F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
943 llvm::cl::desc("Add directory to framework include search path"));
944static llvm::cl::list<std::string>
945I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
946 llvm::cl::desc("Add directory to include search path"));
947static llvm::cl::list<std::string>
948idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
949 llvm::cl::desc("Add directory to AFTER include search path"));
950static llvm::cl::list<std::string>
951iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
952 llvm::cl::desc("Add directory to QUOTE include search path"));
953static llvm::cl::list<std::string>
954isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
955 llvm::cl::desc("Add directory to SYSTEM include search path"));
956
957// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
958static llvm::cl::list<std::string>
959iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
960 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
961static llvm::cl::list<std::string>
962iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
963 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
964static llvm::cl::list<std::string>
965iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
966 llvm::cl::Prefix,
967 llvm::cl::desc("Set directory to include search path with prefix"));
968
Chris Lattner0c946412007-08-26 17:47:35 +0000969static llvm::cl::opt<std::string>
970isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
971 llvm::cl::desc("Set the system root directory (usually /)"));
972
Reid Spencer5f016e22007-07-11 17:01:13 +0000973// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +0000974
Reid Spencer5f016e22007-07-11 17:01:13 +0000975/// InitializeIncludePaths - Process the -I options and set them in the
976/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +0000977void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
978 FileManager &FM, const LangOptions &Lang) {
979 InitHeaderSearch Init(Headers, Verbose, isysroot);
980
Ted Kremenekf3721112008-05-31 00:27:00 +0000981 // Handle -I... and -F... options, walking the lists in parallel.
982 unsigned Iidx = 0, Fidx = 0;
983 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
984 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +0000985 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +0000986 ++Iidx;
987 } else {
Nico Weber0fca0222008-08-22 09:25:22 +0000988 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +0000989 ++Fidx;
990 }
991 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000992
Ted Kremenekf3721112008-05-31 00:27:00 +0000993 // Consume what's left from whatever list was longer.
994 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +0000995 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +0000996 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +0000997 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000998
999 // Handle -idirafter... options.
1000 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001001 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1002 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001003
1004 // Handle -iquote... options.
1005 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001006 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001007
1008 // Handle -isystem... options.
1009 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001010 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001011
1012 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1013 // parallel, processing the values in order of occurance to get the right
1014 // prefixes.
1015 {
1016 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1017 unsigned iprefix_idx = 0;
1018 unsigned iwithprefix_idx = 0;
1019 unsigned iwithprefixbefore_idx = 0;
1020 bool iprefix_done = iprefix_vals.empty();
1021 bool iwithprefix_done = iwithprefix_vals.empty();
1022 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1023 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1024 if (!iprefix_done &&
1025 (iwithprefix_done ||
1026 iprefix_vals.getPosition(iprefix_idx) <
1027 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1028 (iwithprefixbefore_done ||
1029 iprefix_vals.getPosition(iprefix_idx) <
1030 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1031 Prefix = iprefix_vals[iprefix_idx];
1032 ++iprefix_idx;
1033 iprefix_done = iprefix_idx == iprefix_vals.size();
1034 } else if (!iwithprefix_done &&
1035 (iwithprefixbefore_done ||
1036 iwithprefix_vals.getPosition(iwithprefix_idx) <
1037 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001038 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1039 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001040 ++iwithprefix_idx;
1041 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1042 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001043 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1044 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 ++iwithprefixbefore_idx;
1046 iwithprefixbefore_done =
1047 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1048 }
1049 }
1050 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001051
Nico Weber0fca0222008-08-22 09:25:22 +00001052 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001053
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001054 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001055 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001056 llvm::sys::Path::GetMainExecutable(Argv0,
1057 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001058 if (!MainExecutablePath.isEmpty()) {
1059 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1060 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001061
1062 // Get foo/lib/clang/1.0/include
1063 //
1064 // FIXME: Don't embed version here.
1065 MainExecutablePath.appendComponent("lib");
1066 MainExecutablePath.appendComponent("clang");
1067 MainExecutablePath.appendComponent("1.0");
1068 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001069
1070 // We pass true to ignore sysroot so that we *always* look for clang headers
1071 // relative to our executable, never relative to -isysroot.
1072 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1073 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001074 }
1075
Nico Weber0fca0222008-08-22 09:25:22 +00001076 if (!nostdinc)
1077 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001078
1079 // Now that we have collected all of the include paths, merge them all
1080 // together and tell the preprocessor about them.
1081
Nico Weber0fca0222008-08-22 09:25:22 +00001082 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001083}
1084
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001085//===----------------------------------------------------------------------===//
1086// Driver PreprocessorFactory - For lazily generating preprocessors ...
1087//===----------------------------------------------------------------------===//
1088
1089namespace {
1090class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001091 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001092 Diagnostic &Diags;
1093 const LangOptions &LangInfo;
1094 TargetInfo &Target;
1095 SourceManager &SourceMgr;
1096 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001097 bool InitializeSourceMgr;
1098
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001099public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001100 DriverPreprocessorFactory(const std::string &infile,
1101 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001102 TargetInfo &target, SourceManager &SM,
1103 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001104 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1105 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1106
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001107
1108 virtual ~DriverPreprocessorFactory() {}
1109
1110 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001111 llvm::OwningPtr<PTHManager> PTHMgr;
1112
1113 // Use PTH?
1114 if (!TokenCache.empty())
Ted Kremenek8a6aec62009-01-28 20:49:33 +00001115 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenek72b1b152009-01-15 18:47:46 +00001116
1117 // Create the Preprocessor.
1118 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1119 SourceMgr, HeaderInfo,
1120 PTHMgr.get()));
1121
1122 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1123 // That argument is used as the IdentifierInfoLookup argument to
1124 // IdentifierTable's ctor.
1125 if (PTHMgr) {
1126 PTHMgr->setPreprocessor(PP.get());
1127 PP->setPTHManager(PTHMgr.take());
1128 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001129
Chris Lattner51574ea2008-04-19 23:25:44 +00001130 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001131 return NULL;
1132 }
1133
Daniel Dunbar750c3582008-10-24 22:12:41 +00001134 /// FIXME: PP can only handle one callback
1135 if (ProgAction != PrintPreprocessedInput) {
1136 const char* ErrStr;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001137 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001138 if (!DFG && ErrStr) {
Ted Kremenek9a30c242008-10-25 20:19:34 +00001139 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001140 return NULL;
1141 }
1142 }
1143
Ted Kremenek339b9c22008-04-17 22:31:54 +00001144 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001145 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001146 }
1147};
1148}
Reid Spencer5f016e22007-07-11 17:01:13 +00001149
Reid Spencer5f016e22007-07-11 17:01:13 +00001150//===----------------------------------------------------------------------===//
1151// Basic Parser driver
1152//===----------------------------------------------------------------------===//
1153
Chris Lattner51574ea2008-04-19 23:25:44 +00001154static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001156 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001157
1158 // Parsing the specified input file.
1159 P.ParseTranslationUnit();
1160 delete PA;
1161}
1162
1163//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001164// Code generation options
1165//===----------------------------------------------------------------------===//
1166
1167static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001168GenerateDebugInfo("g",
1169 llvm::cl::desc("Generate source level debug information"));
1170
1171static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00001172OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbar70f92432008-10-23 05:50:47 +00001173
1174// It might be nice to add bounds to the CommandLine library directly.
1175struct OptLevelParser : public llvm::cl::parser<unsigned> {
1176 bool parse(llvm::cl::Option &O, const char *ArgName,
1177 const std::string &Arg, unsigned &Val) {
1178 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1179 return true;
1180 // FIXME: Support -O4.
1181 if (Val > 3)
1182 return O.error(": '" + Arg + "' invalid optimization level!");
1183 return false;
1184 }
1185};
1186static llvm::cl::opt<unsigned, false, OptLevelParser>
1187OptLevel("O", llvm::cl::Prefix,
1188 llvm::cl::desc("Optimization level"),
1189 llvm::cl::init(0));
1190
Daniel Dunbara034ba82009-02-17 19:47:34 +00001191static llvm::cl::opt<std::string>
1192TargetCPU("mcpu",
1193 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1194
Chris Lattner7afae712009-03-16 18:41:18 +00001195static void InitializeCompileOptions(CompileOptions &Opts,
1196 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001197 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001198 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001199 if (OptSize) {
1200 // -Os implies -O2
1201 // FIXME: Diagnose conflicting options.
1202 Opts.OptimizationLevel = 2;
1203 } else {
1204 Opts.OptimizationLevel = OptLevel;
1205 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001206
1207 // FIXME: There are llvm-gcc options to control these selectively.
1208 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1209 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001210 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001211
1212#ifdef NDEBUG
1213 Opts.VerifyModule = 0;
1214#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001215
1216 Opts.CPU = TargetCPU;
1217 Opts.Features.insert(Opts.Features.end(),
1218 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001219
1220 // Handle -ftime-report.
1221 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001222}
1223
1224//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001225// Main driver
1226//===----------------------------------------------------------------------===//
1227
Ted Kremenekdb094a22007-12-05 18:27:04 +00001228/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001229/// action. These consumers can operate on both ASTs that are freshly
1230/// parsed from source files as well as those deserialized from Bitcode.
1231/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001232static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001233 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001234 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001235 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001236 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001237 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001238 default:
1239 return NULL;
1240
1241 case ASTPrint:
1242 return CreateASTPrinter();
1243
1244 case ASTDump:
1245 return CreateASTDumper();
1246
1247 case ASTView:
1248 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001249
Chris Lattner8a5c8092009-02-18 01:20:05 +00001250 case PrintDeclContext:
1251 return CreateDeclContextPrinter();
1252
1253 case EmitHTML:
1254 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001255
Chris Lattner8a5c8092009-02-18 01:20:05 +00001256 case InheritanceView:
1257 return CreateInheritanceViewer(InheritanceViewCls);
1258
1259 case TestSerialization:
1260 return CreateSerializationTest(Diag, FileMgr);
1261
1262 case EmitAssembly:
1263 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001264 case EmitBC:
1265 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001266 BackendAction Act;
1267 if (ProgAction == EmitAssembly)
1268 Act = Backend_EmitAssembly;
1269 else if (ProgAction == EmitLLVM)
1270 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001271 else if (ProgAction == EmitLLVMOnly)
1272 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001273 else
1274 Act = Backend_EmitBC;
1275
1276 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001277 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001278 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001279 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001280 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001281
Chris Lattner8a5c8092009-02-18 01:20:05 +00001282 case SerializeAST:
1283 // FIXME: Allow user to tailor where the file is written.
1284 return CreateASTSerializer(InFile, OutputFile, Diag);
1285
1286 case RewriteObjC:
1287 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001288
Chris Lattner8a5c8092009-02-18 01:20:05 +00001289 case RewriteBlocks:
1290 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1291
1292 case RunAnalysis:
1293 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001294 }
1295}
1296
Reid Spencer5f016e22007-07-11 17:01:13 +00001297/// ProcessInputFile - Process a single input file with the specified state.
1298///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001299static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001300 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001301 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001302 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001303
Ted Kremenek85888962008-10-21 00:54:44 +00001304 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001305 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001306 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1307 PP.getFileManager(), PP.getLangOptions(),
1308 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001309
1310 if (!Consumer) {
1311 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001312 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001313 return;
1314 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001315
Ted Kremenekdb094a22007-12-05 18:27:04 +00001316 break;
1317
Chris Lattnerc106c102008-10-12 05:03:36 +00001318 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001319 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001320 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001321 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001322 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001323 RawLex.SetKeepWhitespaceMode(true);
1324
1325 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001326 RawLex.LexFromRawLexer(RawTok);
1327 while (RawTok.isNot(tok::eof)) {
1328 PP.DumpToken(RawTok, true);
1329 fprintf(stderr, "\n");
1330 RawLex.LexFromRawLexer(RawTok);
1331 }
1332 ClearSourceMgr = true;
1333 break;
1334 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001336 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001337 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001338 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001339 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 do {
1341 PP.Lex(Tok);
1342 PP.DumpToken(Tok, true);
1343 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001344 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001345 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 break;
1347 }
1348 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001349 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001350 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001352 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 do {
1354 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001355 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001356 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 break;
1358 }
Ted Kremenek85888962008-10-21 00:54:44 +00001359
1360 case GeneratePCH: {
Chris Lattner47099742009-02-18 01:51:21 +00001361 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001362 CacheTokens(PP, OutputFile);
1363 ClearSourceMgr = true;
1364 break;
1365 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001366
Chris Lattner47099742009-02-18 01:51:21 +00001367 case PrintPreprocessedInput: { // -E mode.
1368 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001369 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001370 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 break;
Chris Lattner47099742009-02-18 01:51:21 +00001372 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001373
Chris Lattner47099742009-02-18 01:51:21 +00001374 case ParseNoop: { // -parse-noop
1375 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001376 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001377 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 break;
Chris Lattner47099742009-02-18 01:51:21 +00001379 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001380
Chris Lattner47099742009-02-18 01:51:21 +00001381 case ParsePrintCallbacks: {
1382 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001383 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001384 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 break;
Chris Lattner47099742009-02-18 01:51:21 +00001386 }
1387
1388 case ParseSyntaxOnly: { // -fsyntax-only
1389 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001390 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001391 break;
Chris Lattner47099742009-02-18 01:51:21 +00001392 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001393
1394 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001395 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001396 ClearSourceMgr = true;
1397 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001398
Chris Lattner47099742009-02-18 01:51:21 +00001399 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001400 DoRewriteTest(PP, InFile, OutputFile);
1401 ClearSourceMgr = true;
1402 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001403 }
Chris Lattner47099742009-02-18 01:51:21 +00001404 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001405
1406 if (Consumer) {
1407 TranslationUnit *TU = 0;
1408 if (DisableFree) {
1409 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1410 PP.getSourceManager(),
1411 PP.getTargetInfo(),
1412 PP.getIdentifierTable(),
1413 PP.getSelectorTable(),
1414 /* FreeMemory = */ false);
1415 TU = new TranslationUnit(*Context);
1416 }
1417 ParseAST(PP, Consumer.get(), TU, Stats);
1418 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001419
1420 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001421 if (CheckDiagnostics(PP))
1422 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001423
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001425 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 PP.PrintStats();
1427 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001428 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001429 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001430 fprintf(stderr, "\n");
1431 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001432
1433 // For a multi-file compilation, some things are ok with nuking the source
1434 // manager tables, other require stable fileid/macroid's across multiple
1435 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001436 if (ClearSourceMgr)
1437 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001438
1439 if (DisableFree)
1440 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001441}
1442
Ted Kremenek20e97482007-12-12 23:41:08 +00001443static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1444 FileManager& FileMgr) {
1445
1446 if (VerifyDiagnostics) {
1447 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1448 exit (1);
1449 }
1450
1451 llvm::sys::Path Filename(InFile);
1452
1453 if (!Filename.isValid()) {
1454 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1455 exit (1);
1456 }
1457
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001458 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001459
1460 if (!TU) {
1461 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1462 InFile.c_str());
1463 exit (1);
1464 }
1465
Ted Kremenek63ea8632007-12-19 19:27:38 +00001466 // Observe that we use the source file name stored in the deserialized
1467 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001468 llvm::OwningPtr<ASTConsumer>
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001469 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001470 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001471
Ted Kremenek20e97482007-12-12 23:41:08 +00001472 if (!Consumer) {
1473 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1474 exit (1);
1475 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001476
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001477 Consumer->Initialize(TU->getContext());
Nico Weber7bfaaae2008-08-10 19:59:06 +00001478
Chris Lattnere66b65c2008-02-06 01:42:25 +00001479 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001480 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1481 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001482}
1483
1484
Reid Spencer5f016e22007-07-11 17:01:13 +00001485static llvm::cl::list<std::string>
1486InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1487
Ted Kremenek20e97482007-12-12 23:41:08 +00001488static bool isSerializedFile(const std::string& InFile) {
1489 if (InFile.size() < 4)
1490 return false;
1491
1492 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001493 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001494}
1495
Reid Spencer5f016e22007-07-11 17:01:13 +00001496
1497int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001499 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001500 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001501 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001502
Chris Lattner47099742009-02-18 01:51:21 +00001503 if (TimeReport)
1504 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1505
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 // If no input was specified, read from stdin.
1507 if (InputFilenames.empty())
1508 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001509
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 // Create a file manager object to provide access to and cache the filesystem.
1511 FileManager FileMgr;
1512
Ted Kremenek31e703b2007-12-11 23:28:38 +00001513 // Create the diagnostic client for reporting errors or for
1514 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001515 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001516
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001517 if (!VerifyDiagnostics) {
1518 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001519 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1520 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001521 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001522 !NoShowLocation,
1523 PrintSourceRangeInfo);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001524 } else {
1525 // When checking diagnostics, just buffer them up.
1526 TextDiagClient = new TextDiagnosticBuffer();
1527
1528 if (InputFilenames.size() != 1) {
1529 fprintf(stderr,
1530 "-verify only works on single input files for now.\n");
1531 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 }
1533 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001534
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001536 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1537 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001538 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001539 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001540
Chris Lattner4f037832007-12-05 23:24:17 +00001541 // -I- is a deprecated GCC feature, scan for it and reject it.
1542 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1543 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001544 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001545 I_dirs.erase(I_dirs.begin()+i);
1546 --i;
1547 }
1548 }
Chris Lattner11215192008-03-14 06:12:05 +00001549
1550 // Get information about the target being compiled for.
1551 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001552 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1553
Chris Lattner11215192008-03-14 06:12:05 +00001554 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001555 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1556 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001557 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001558 }
Chris Lattner4f037832007-12-05 23:24:17 +00001559
Daniel Dunbard4270232009-01-20 23:17:32 +00001560 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001561 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001562
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001563 llvm::OwningPtr<SourceManager> SourceMgr;
1564
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001566 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001567
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001568 if (isSerializedFile(InFile)) {
1569 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001570 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001571 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001572 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001573
1574 /// Create a SourceManager object. This tracks and owns all the file
1575 /// buffers allocated to a translation unit.
1576 if (!SourceMgr)
1577 SourceMgr.reset(new SourceManager());
1578 else
1579 SourceMgr->clearIDTables();
1580
1581 // Initialize language options, inferring file types from input filenames.
1582 LangOptions LangInfo;
1583 InitializeBaseLanguage();
1584 LangKind LK = GetLanguage(InFile);
1585 bool PCH = InitializeLangOptions(LangInfo, LK);
1586 InitializeGCMode(LangInfo);
1587 InitializeLanguageStandard(LangInfo, LK, Target.get());
1588
1589 // Process the -I options and set them in the HeaderInfo.
1590 HeaderSearch HeaderInfo(FileMgr);
1591
1592 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1593
1594 // Set up the preprocessor with these options.
1595 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1596 *SourceMgr.get(), HeaderInfo);
1597
1598 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1599
1600 if (!PP)
1601 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001602
Chris Lattnerf63aea32009-03-04 21:40:56 +00001603 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1604 // always reset to using TextDiagClient.
1605 llvm::OwningPtr<DiagnosticClient> TmpClient;
1606
1607 if (!HTMLDiag.empty()) {
1608 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1609 &PPFactory));
1610 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001611 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001612 else
1613 Diags.setClient(TextDiagClient);
1614
1615 // Process the source file.
1616 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1617
1618 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 }
Chris Lattner11215192008-03-14 06:12:05 +00001620
Mike Stump007f2a92009-01-28 02:43:35 +00001621 if (Verbose)
1622 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1623 " hosted on " LLVM_HOSTTRIPLE "\n");
1624
Ted Kremenek7a08e282008-08-07 18:13:12 +00001625 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1627 (NumDiagnostics == 1 ? "" : "s"));
1628
1629 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 FileMgr.PrintStats();
1631 fprintf(stderr, "\n");
1632 }
1633
Daniel Dunbar276373d2008-10-27 22:10:13 +00001634 // If verifying diagnostics and we reached here, all is well.
1635 if (VerifyDiagnostics)
1636 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001637
1638 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001639
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001640 // Managed static deconstruction. Useful for making things like
1641 // -time-passes usable.
1642 llvm::llvm_shutdown();
1643
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001644 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001645}