blob: 7f46f46fed7ba428500eedc2dbe35ac9d08d4d2c [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>
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000234AllowBuiltins("fbuiltin",
235 llvm::cl::desc("Disable implicit builtin knowledge of functions"),
236 llvm::cl::init(true), llvm::cl::AllowInverse);
Chris Lattner7644f072009-03-13 22:38:49 +0000237
238
239static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000240MathErrno("fmath-errno",
Chris Lattner5ea9d1b2009-02-17 00:30:31 +0000241 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner5bef8dd2009-02-17 00:35:09 +0000242 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000243
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000244//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000245// Language Options
246//===----------------------------------------------------------------------===//
247
248enum LangKind {
249 langkind_unspecified,
250 langkind_c,
251 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000252 langkind_asm_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000253 langkind_c_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 langkind_cxx,
255 langkind_cxx_cpp,
Chris Lattnerc76d8072009-02-06 06:19:20 +0000256 langkind_cxx_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 langkind_objc,
258 langkind_objc_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000259 langkind_objc_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 langkind_objcxx,
Ted Kremenekf8901912009-01-09 00:38:08 +0000261 langkind_objcxx_cpp,
262 langkind_objcxx_pch
Reid Spencer5f016e22007-07-11 17:01:13 +0000263};
264
Reid Spencer5f016e22007-07-11 17:01:13 +0000265static llvm::cl::opt<LangKind>
266BaseLang("x", llvm::cl::desc("Base language to compile"),
267 llvm::cl::init(langkind_unspecified),
268 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
269 clEnumValN(langkind_cxx, "c++", "C++"),
270 clEnumValN(langkind_objc, "objective-c", "Objective C"),
271 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000272 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000274 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
275 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000277 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
279 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000280 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 "Preprocessed Objective C++"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000282 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek85888962008-10-21 00:54:44 +0000283 "Precompiled C header"),
284 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekf8901912009-01-09 00:38:08 +0000285 "Precompiled Objective-C header"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000286 clEnumValN(langkind_cxx_pch, "c++-header",
287 "Precompiled C++ header"),
Ted Kremenekf8901912009-01-09 00:38:08 +0000288 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
289 "Precompiled Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 clEnumValEnd));
291
292static llvm::cl::opt<bool>
293LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
294 llvm::cl::Hidden);
295static llvm::cl::opt<bool>
296LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
297 llvm::cl::Hidden);
298
Ted Kremenek8904f152007-12-05 23:49:08 +0000299/// InitializeBaseLanguage - Handle the -x foo options.
300static void InitializeBaseLanguage() {
301 if (LangObjC)
302 BaseLang = langkind_objc;
303 else if (LangObjCXX)
304 BaseLang = langkind_objcxx;
305}
306
307static LangKind GetLanguage(const std::string &Filename) {
308 if (BaseLang != langkind_unspecified)
309 return BaseLang;
310
311 std::string::size_type DotPos = Filename.rfind('.');
312
313 if (DotPos == std::string::npos) {
314 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000315 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 }
317
Ted Kremenek8904f152007-12-05 23:49:08 +0000318 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
319 // C header: .h
320 // C++ header: .hh or .H;
321 // assembler no preprocessing: .s
322 // assembler: .S
323 if (Ext == "c")
324 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000325 else if (Ext == "S" ||
326 // If the compiler is run on a .s file, preprocess it as .S
327 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000328 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000329 else if (Ext == "i")
330 return langkind_c_cpp;
331 else if (Ext == "ii")
332 return langkind_cxx_cpp;
333 else if (Ext == "m")
334 return langkind_objc;
335 else if (Ext == "mi")
336 return langkind_objc_cpp;
337 else if (Ext == "mm" || Ext == "M")
338 return langkind_objcxx;
339 else if (Ext == "mii")
340 return langkind_objcxx_cpp;
341 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
342 Ext == "c++" || Ext == "cp" || Ext == "cxx")
343 return langkind_cxx;
344 else
345 return langkind_c;
346}
347
348
Ted Kremenek85888962008-10-21 00:54:44 +0000349static void InitializeCOptions(LangOptions &Options) {
350 // Do nothing.
351}
352
353static void InitializeObjCOptions(LangOptions &Options) {
354 Options.ObjC1 = Options.ObjC2 = 1;
355}
356
357
358static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 // FIXME: implement -fpreprocessed mode.
360 bool NoPreprocess = false;
Ted Kremenek85888962008-10-21 00:54:44 +0000361 bool PCH = false;
Ted Kremenekf8901912009-01-09 00:38:08 +0000362
363 // Test for 'PCH'.
364 switch (LK) {
Chris Lattnerc76d8072009-02-06 06:19:20 +0000365 default:
366 break;
367 case langkind_c_pch:
368 LK = langkind_c;
369 PCH = true;
370 break;
371 case langkind_objc_pch:
372 LK = langkind_objc;
373 PCH = true;
374 break;
375 case langkind_cxx_pch:
376 LK = langkind_cxx;
377 PCH = true;
378 break;
379 case langkind_objcxx_pch:
380 LK = langkind_objcxx;
381 PCH = true;
382 break;
Ted Kremenekf8901912009-01-09 00:38:08 +0000383 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000384
Ted Kremenek8904f152007-12-05 23:49:08 +0000385 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000387 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000388 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000389 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 case langkind_c_cpp:
391 NoPreprocess = true;
392 // FALLTHROUGH
393 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000394 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 break;
396 case langkind_cxx_cpp:
397 NoPreprocess = true;
398 // FALLTHROUGH
399 case langkind_cxx:
400 Options.CPlusPlus = 1;
401 break;
402 case langkind_objc_cpp:
403 NoPreprocess = true;
404 // FALLTHROUGH
405 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000406 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 break;
408 case langkind_objcxx_cpp:
409 NoPreprocess = true;
410 // FALLTHROUGH
411 case langkind_objcxx:
412 Options.ObjC1 = Options.ObjC2 = 1;
413 Options.CPlusPlus = 1;
414 break;
415 }
Ted Kremenek85888962008-10-21 00:54:44 +0000416
417 return PCH;
Reid Spencer5f016e22007-07-11 17:01:13 +0000418}
419
420/// LangStds - Language standards we support.
421enum LangStds {
422 lang_unspecified,
423 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000424 lang_gnu_START,
425 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000426 lang_cxx98, lang_gnucxx98,
427 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000428};
429
430static llvm::cl::opt<LangStds>
431LangStd("std", llvm::cl::desc("Language standard to compile for"),
432 llvm::cl::init(lang_unspecified),
433 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
434 clEnumValN(lang_c89, "c90", "ISO C 1990"),
435 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
436 clEnumValN(lang_c94, "iso9899:199409",
437 "ISO C 1990 with amendment 1"),
438 clEnumValN(lang_c99, "c99", "ISO C 1999"),
439// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
440 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
441// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
442 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000443 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000444 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000445 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 clEnumValN(lang_gnu99, "gnu9x",
447 "ISO C 1999 with GNU extensions"),
448 clEnumValN(lang_cxx98, "c++98",
449 "ISO C++ 1998 with amendments"),
450 clEnumValN(lang_gnucxx98, "gnu++98",
451 "ISO C++ 1998 with amendments and GNU "
452 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000453 clEnumValN(lang_cxx0x, "c++0x",
454 "Upcoming ISO C++ 200x with amendments"),
455 clEnumValN(lang_gnucxx0x, "gnu++0x",
456 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000457 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000458 clEnumValEnd));
459
460static llvm::cl::opt<bool>
461NoOperatorNames("fno-operator-names",
462 llvm::cl::desc("Do not treat C++ operator name keywords as "
463 "synonyms for operators"));
464
Anders Carlssonee98ac52007-10-15 02:50:23 +0000465static llvm::cl::opt<bool>
466PascalStrings("fpascal-strings",
467 llvm::cl::desc("Recognize and construct Pascal-style "
468 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000469
470static llvm::cl::opt<bool>
471MSExtensions("fms-extensions",
472 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000473 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000474
475static llvm::cl::opt<bool>
476WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000477 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000478
479static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000480NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000481 llvm::cl::desc("Disallow implicit conversions between "
482 "vectors with a different number of "
483 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000484
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000485static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000486EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
487 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
488 llvm::cl::ZeroOrMore);
489
490static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000491EnableHeinousExtensions("fheinous-gnu-extensions",
492 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
493 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
494
495static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000496ObjCNonFragileABI("fobjc-nonfragile-abi",
497 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000498
Daniel Dunbard604c402009-02-04 21:19:06 +0000499static llvm::cl::opt<bool>
500EmitAllDecls("femit-all-decls",
501 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000502
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000503// FIXME: This (and all GCC -f options) really come in -f... and
504// -fno-... forms, and additionally support automagic behavior when
505// they are not defined. For example, -fexceptions defaults to on or
506// off depending on the language. We should support this behavior in
507// some form (perhaps just add a facility for distinguishing when an
508// has its default value from when it has been set to its default
509// value).
510static llvm::cl::opt<bool>
511Exceptions("fexceptions",
512 llvm::cl::desc("Enable support for exception handling."));
513
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000514static llvm::cl::opt<bool>
515GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000516 llvm::cl::desc("Generate output compatible with the standard GNU "
517 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000518
519static llvm::cl::opt<bool>
520NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000521 llvm::cl::desc("Generate output compatible with the NeXT "
522 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000523
Ted Kremenekea644d82008-09-03 21:22:16 +0000524
525
526static llvm::cl::opt<bool>
527Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
528
529static llvm::cl::opt<bool>
530Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
531
Chris Lattner16167a62009-03-02 22:11:07 +0000532static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000533TargetFeatures("mattr", llvm::cl::CommaSeparated,
534 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
535
Douglas Gregor26dce442009-03-10 00:06:19 +0000536static llvm::cl::opt<unsigned>
537TemplateDepth("ftemplate-depth", llvm::cl::init(99),
538 llvm::cl::desc("Maximum depth of recursive template "
539 "instantiation"));
Chris Lattner16167a62009-03-02 22:11:07 +0000540
Reid Spencer5f016e22007-07-11 17:01:13 +0000541// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000542// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000543static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
544 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000545 // Allow the target to set the default the langauge options as it sees fit.
546 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000547
Chris Lattner6328cc32009-03-03 19:56:18 +0000548 // If there are any -mattr options, pass them to the target for validation and
549 // processing. The driver should have already consolidated all the
550 // target-feature settings and passed them to us in the -mattr list. The
551 // -mattr list is treated by the code generator as a diff against the -mcpu
552 // setting, but the driver should pass all enabled options as "+" settings.
553 // This means that the target should only look at + settings.
554 if (!TargetFeatures.empty()
555 // FIXME: The driver is not quite yet ready for this.
556 && 0) {
Chris Lattner16167a62009-03-02 22:11:07 +0000557 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000558 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
559 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000560 if (Opt != -1) {
561 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000562 fprintf(stderr, "invalid feature '%s'\n",
563 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000564 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000565 fprintf(stderr, "feature '%s': %s\n",
566 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000567 exit(1);
568 }
569 }
570
Ted Kremenekea644d82008-09-03 21:22:16 +0000571 if (Ansi) // "The -ansi option is equivalent to -std=c89."
572 LangStd = lang_c89;
573
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 if (LangStd == lang_unspecified) {
575 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000576 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000577 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000579 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 case langkind_c_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000581 case langkind_c_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 case langkind_objc:
583 case langkind_objc_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000584 case langkind_objc_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000585 LangStd = lang_gnu99;
586 break;
587 case langkind_cxx:
588 case langkind_cxx_cpp:
Ted Kremenekab56c5d2009-03-19 18:21:42 +0000589 case langkind_cxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000590 case langkind_objcxx:
591 case langkind_objcxx_cpp:
Ted Kremenekf8901912009-01-09 00:38:08 +0000592 case langkind_objcxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 LangStd = lang_gnucxx98;
594 break;
595 }
596 }
597
598 switch (LangStd) {
599 default: assert(0 && "Unknown language standard!");
600
601 // Fall through from newer standards to older ones. This isn't really right.
602 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000603 case lang_gnucxx0x:
604 case lang_cxx0x:
605 Options.CPlusPlus0x = 1;
606 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000607 case lang_gnucxx98:
608 case lang_cxx98:
609 Options.CPlusPlus = 1;
610 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000611 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 // FALL THROUGH.
613 case lang_gnu99:
614 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 Options.C99 = 1;
616 Options.HexFloats = 1;
617 // FALL THROUGH.
618 case lang_gnu89:
619 Options.BCPLComment = 1; // Only for C99/C++.
620 // FALL THROUGH.
621 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000622 Options.Digraphs = 1; // C94, C99, C++.
623 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 case lang_c89:
625 break;
626 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000627
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000628 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
629 Options.GNUMode = LangStd >= lang_gnu_START;
630
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000631 if (Options.CPlusPlus) {
632 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000633 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000634 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000635
Chris Lattnerd658b562008-04-05 06:32:51 +0000636 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
637 Options.ImplicitInt = 1;
638 else
639 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000640
641 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
642 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000643 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000644 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000645 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000646
Chris Lattner802db9b2008-12-05 00:10:44 +0000647 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
648 // even if they are normally on for the target. In GNU modes (e.g.
649 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000650 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000651 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000652 Options.Blocks = 0;
653
Daniel Dunbar85c49102009-03-15 00:11:28 +0000654 // Never accept '$' in identifiers when preprocessing assembler.
655 if (LK != langkind_asm_cpp)
656 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000657 if (PascalStrings.getPosition())
658 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000659 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000660 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000661 if (NoLaxVectorConversions.getPosition())
662 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000663 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000664 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000665 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000666
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000667 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000668 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000669 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000670 Options.Freestanding = Options.NoBuiltin = 1;
671
Chris Lattner810f6d52009-03-13 17:38:01 +0000672 if (EnableHeinousExtensions)
673 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000674
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000675 Options.MathErrno = MathErrno;
676
Douglas Gregor26dce442009-03-10 00:06:19 +0000677 Options.InstantiationDepth = TemplateDepth;
678
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000679 // Override the default runtime if the user requested it.
680 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000681 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000682 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000683 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000684
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000685 if (ObjCNonFragileABI)
686 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000687
688 if (EmitAllDecls)
689 Options.EmitAllDecls = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000690}
691
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000692static llvm::cl::opt<bool>
693ObjCExclusiveGC("fobjc-gc-only",
694 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000695 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000696
697static llvm::cl::opt<bool>
698ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000699 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000700
701void InitializeGCMode(LangOptions &Options) {
702 if (ObjCExclusiveGC)
703 Options.setGCMode(LangOptions::GCOnly);
704 else if (ObjCEnableGC)
705 Options.setGCMode(LangOptions::HybridGC);
706}
707
Reid Spencer5f016e22007-07-11 17:01:13 +0000708//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000709// Target Triple Processing.
710//===----------------------------------------------------------------------===//
711
712static llvm::cl::opt<std::string>
713TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000714 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000715
Chris Lattner42e67372008-03-05 01:18:20 +0000716static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000717Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000718
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000719static llvm::cl::opt<std::string>
720MacOSVersionMin("mmacosx-version-min",
721 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
722
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000723// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
724// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
725static void HandleMacOSVersionMin(std::string &Triple) {
726 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
727 if (DarwinDashIdx == std::string::npos) {
728 fprintf(stderr,
729 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
730 exit(1);
731 }
732 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
733
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000734 // Remove the number.
735 Triple.resize(DarwinNumIdx);
736
737 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
738 bool MacOSVersionMinIsInvalid = false;
739 int VersionNum = 0;
740 if (MacOSVersionMin.size() < 4 ||
741 MacOSVersionMin.substr(0, 3) != "10." ||
742 !isdigit(MacOSVersionMin[3])) {
743 MacOSVersionMinIsInvalid = true;
744 } else {
745 const char *Start = MacOSVersionMin.c_str()+3;
746 char *End = 0;
747 VersionNum = (int)strtol(Start, &End, 10);
748
Chris Lattner079f2c462008-09-30 20:30:12 +0000749 // The version number must be in the range 0-9.
750 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
751
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000752 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
753 Triple += llvm::itostr(VersionNum+4);
754
Chris Lattner079f2c462008-09-30 20:30:12 +0000755 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
756 // Add the period piece (.7) to the end of the triple. This gives us
757 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000758 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000759 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
760 MacOSVersionMinIsInvalid = true;
761 }
762 }
763
764 if (MacOSVersionMinIsInvalid) {
765 fprintf(stderr,
766 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
767 MacOSVersionMin.c_str());
768 exit(1);
769 }
770}
771
772/// CreateTargetTriple - Process the various options that affect the target
773/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000774static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000775 // Initialize base triple. If a -triple option has been specified, use
776 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000777 std::string Triple = TargetTriple;
Daniel Dunbare553a722008-10-02 01:21:33 +0000778 if (Triple.empty()) {
779 Triple = LLVM_HOSTTRIPLE;
780
Daniel Dunbara6291902008-12-12 18:34:35 +0000781 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
782 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
783 Triple[2] == '8' && Triple[3] == '6')
784 Triple[1] = '3';
785
Daniel Dunbare553a722008-10-02 01:21:33 +0000786 // On darwin, we want to update the version to match that of the
787 // host.
788 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
789 if (DarwinDashIdx != std::string::npos) {
790 Triple.resize(DarwinDashIdx + strlen("-darwin"));
791
Daniel Dunbara6291902008-12-12 18:34:35 +0000792 // Only add the major part of the os version.
Chris Lattnera05ff452009-01-22 20:57:52 +0000793 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbara6291902008-12-12 18:34:35 +0000794 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbare553a722008-10-02 01:21:33 +0000795 }
796 }
Ted Kremenekae360762007-12-03 22:06:55 +0000797
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000798 // If -arch foo was specified, remove the architecture from the triple we have
799 // so far and replace it with the specified one.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000800 if (!Arch.empty()) {
801 // Decompose the base triple into "arch" and suffix.
802 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000803
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000804 if (FirstDashIdx == std::string::npos) {
805 fprintf(stderr,
806 "Malformed target triple: \"%s\" ('-' could not be found).\n",
807 Triple.c_str());
808 exit(1);
809 }
Chris Lattner37e217c2009-03-24 16:18:41 +0000810
811 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
812 if (Arch == "ppc")
813 Arch = "powerpc";
814 else if (Arch == "ppc64")
815 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +0000816
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000817 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
818 }
819
820 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
821 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000822 if (!MacOSVersionMin.empty())
823 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000824
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000825 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000826}
827
828//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000829// Preprocessor Initialization
830//===----------------------------------------------------------------------===//
831
832// FIXME: Preprocessor builtins to support.
833// -A... - Play with #assertions
834// -undef - Undefine all predefined macros
835
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000836// FIXME: -imacros
837
Reid Spencer5f016e22007-07-11 17:01:13 +0000838static llvm::cl::list<std::string>
839D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
840 llvm::cl::desc("Predefine the specified macro"));
841static llvm::cl::list<std::string>
842U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
843 llvm::cl::desc("Undefine the specified macro"));
844
Chris Lattner64299f82008-01-10 01:53:41 +0000845static llvm::cl::list<std::string>
846ImplicitIncludes("include", llvm::cl::value_desc("file"),
847 llvm::cl::desc("Include file before parsing"));
848
Ted Kremenek748d5d62009-03-20 00:26:38 +0000849static llvm::cl::opt<std::string>
850ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
851 llvm::cl::desc("Include file before parsing"));
852
Reid Spencer5f016e22007-07-11 17:01:13 +0000853// Append a #define line to Buf for Macro. Macro should be of the form XXX,
854// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
855// "#define XXX Y z W". To get a #define with no value, use "XXX=".
856static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
857 const char *Command = "#define ") {
858 Buf.insert(Buf.end(), Command, Command+strlen(Command));
859 if (const char *Equal = strchr(Macro, '=')) {
860 // Turn the = into ' '.
861 Buf.insert(Buf.end(), Macro, Equal);
862 Buf.push_back(' ');
863 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
864 } else {
865 // Push "macroname 1".
866 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
867 Buf.push_back(' ');
868 Buf.push_back('1');
869 }
870 Buf.push_back('\n');
871}
872
Chris Lattner64299f82008-01-10 01:53:41 +0000873/// AddImplicitInclude - Add an implicit #include of the specified file to the
874/// predefines buffer.
875static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
876 const char *Inc = "#include \"";
877 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
878 Buf.insert(Buf.end(), File.begin(), File.end());
879 Buf.push_back('"');
880 Buf.push_back('\n');
881}
882
Ted Kremenek748d5d62009-03-20 00:26:38 +0000883/// AddImplicitIncludePTH - Add an implicit #include using the original file
884/// used to generate a PTH cache.
885static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
886 PTHManager *P = PP.getPTHManager();
887 assert(P && "No PTHManager.");
888 const char *OriginalFile = P->getOriginalSourceFile();
889
890 if (!OriginalFile) {
891 assert(!ImplicitIncludePTH.empty());
892 fprintf(stderr, "error: PTH file '%s' does not designate an original "
893 "source header file for -include-pth\n",
894 ImplicitIncludePTH.c_str());
895 exit (1);
896 }
897
898 AddImplicitInclude(Buf, OriginalFile);
899}
Reid Spencer5f016e22007-07-11 17:01:13 +0000900
Chris Lattner53b0dab2007-10-09 22:10:18 +0000901/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000902/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000903///
Chris Lattner51574ea2008-04-19 23:25:44 +0000904static bool InitializePreprocessor(Preprocessor &PP,
905 bool InitializeSourceMgr,
906 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000907 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000908
Chris Lattner53b0dab2007-10-09 22:10:18 +0000909 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000910 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000911
912 if (InitializeSourceMgr) {
913 if (InFile != "-") {
914 const FileEntry *File = FileMgr.getFile(InFile);
915 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +0000916 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000917 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
918 << InFile.c_str();
Chris Lattner51574ea2008-04-19 23:25:44 +0000919 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000920 }
921 } else {
922 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar56743882009-03-21 17:56:30 +0000923
924 // If stdin was empty, SB is null. Cons up an empty memory
925 // buffer now.
926 if (!SB) {
927 const char *EmptyStr = "";
928 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
929 }
930
931 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000932 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000933 PP.getDiagnostics().Report(FullSourceLoc(),
934 diag::err_fe_error_reading_stdin);
Chris Lattner51574ea2008-04-19 23:25:44 +0000935 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000936 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000937 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000938 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000939
Chris Lattneraa391972008-04-19 23:09:31 +0000940 std::vector<char> PredefineBuffer;
941
Reid Spencer5f016e22007-07-11 17:01:13 +0000942 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000943 unsigned d = 0, D = D_macros.size();
944 unsigned u = 0, U = U_macros.size();
945 while (d < D || u < U) {
946 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
947 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
948 else
949 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
950 }
951
Chris Lattner64299f82008-01-10 01:53:41 +0000952 // FIXME: Read any files specified by -imacros.
953
Ted Kremenek748d5d62009-03-20 00:26:38 +0000954 // Add implicit #includes from -include and -include-pth.
955 bool handledPTH = ImplicitIncludePTH.empty();
956 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc53b60a2009-03-20 00:40:03 +0000957 if (!handledPTH &&
958 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek748d5d62009-03-20 00:26:38 +0000959 AddImplicitIncludePTH(PredefineBuffer, PP);
960 handledPTH = true;
961 }
962
Chris Lattner64299f82008-01-10 01:53:41 +0000963 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek748d5d62009-03-20 00:26:38 +0000964 }
965 if (!handledPTH && !ImplicitIncludePTH.empty())
966 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000967
Chris Lattneraa391972008-04-19 23:09:31 +0000968 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000969 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000970 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000971
972 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000973 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000974}
975
976//===----------------------------------------------------------------------===//
977// Preprocessor include path information.
978//===----------------------------------------------------------------------===//
979
980// This tool exports a large number of command line options to control how the
981// preprocessor searches for header files. At root, however, the Preprocessor
982// object takes a very simple interface: a list of directories to search for
983//
984// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000985// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000986//
Reid Spencer5f016e22007-07-11 17:01:13 +0000987
988static llvm::cl::opt<bool>
989nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
990
991// Various command line options. These four add directories to each chain.
992static llvm::cl::list<std::string>
993F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
994 llvm::cl::desc("Add directory to framework include search path"));
995static llvm::cl::list<std::string>
996I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
997 llvm::cl::desc("Add directory to include search path"));
998static llvm::cl::list<std::string>
999idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1000 llvm::cl::desc("Add directory to AFTER include search path"));
1001static llvm::cl::list<std::string>
1002iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1003 llvm::cl::desc("Add directory to QUOTE include search path"));
1004static llvm::cl::list<std::string>
1005isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1006 llvm::cl::desc("Add directory to SYSTEM include search path"));
1007
1008// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1009static llvm::cl::list<std::string>
1010iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1011 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1012static llvm::cl::list<std::string>
1013iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1014 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1015static llvm::cl::list<std::string>
1016iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1017 llvm::cl::Prefix,
1018 llvm::cl::desc("Set directory to include search path with prefix"));
1019
Chris Lattner0c946412007-08-26 17:47:35 +00001020static llvm::cl::opt<std::string>
1021isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1022 llvm::cl::desc("Set the system root directory (usually /)"));
1023
Reid Spencer5f016e22007-07-11 17:01:13 +00001024// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001025
Reid Spencer5f016e22007-07-11 17:01:13 +00001026/// InitializeIncludePaths - Process the -I options and set them in the
1027/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001028void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1029 FileManager &FM, const LangOptions &Lang) {
1030 InitHeaderSearch Init(Headers, Verbose, isysroot);
1031
Ted Kremenekf3721112008-05-31 00:27:00 +00001032 // Handle -I... and -F... options, walking the lists in parallel.
1033 unsigned Iidx = 0, Fidx = 0;
1034 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1035 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001036 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001037 ++Iidx;
1038 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001039 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001040 ++Fidx;
1041 }
1042 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001043
Ted Kremenekf3721112008-05-31 00:27:00 +00001044 // Consume what's left from whatever list was longer.
1045 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001046 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001047 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001048 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001049
1050 // Handle -idirafter... options.
1051 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001052 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1053 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001054
1055 // Handle -iquote... options.
1056 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001057 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001058
1059 // Handle -isystem... options.
1060 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001061 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001062
1063 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1064 // parallel, processing the values in order of occurance to get the right
1065 // prefixes.
1066 {
1067 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1068 unsigned iprefix_idx = 0;
1069 unsigned iwithprefix_idx = 0;
1070 unsigned iwithprefixbefore_idx = 0;
1071 bool iprefix_done = iprefix_vals.empty();
1072 bool iwithprefix_done = iwithprefix_vals.empty();
1073 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1074 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1075 if (!iprefix_done &&
1076 (iwithprefix_done ||
1077 iprefix_vals.getPosition(iprefix_idx) <
1078 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1079 (iwithprefixbefore_done ||
1080 iprefix_vals.getPosition(iprefix_idx) <
1081 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1082 Prefix = iprefix_vals[iprefix_idx];
1083 ++iprefix_idx;
1084 iprefix_done = iprefix_idx == iprefix_vals.size();
1085 } else if (!iwithprefix_done &&
1086 (iwithprefixbefore_done ||
1087 iwithprefix_vals.getPosition(iwithprefix_idx) <
1088 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001089 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1090 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001091 ++iwithprefix_idx;
1092 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1093 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001094 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1095 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001096 ++iwithprefixbefore_idx;
1097 iwithprefixbefore_done =
1098 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1099 }
1100 }
1101 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001102
Nico Weber0fca0222008-08-22 09:25:22 +00001103 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001104
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001105 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001106 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001107 llvm::sys::Path::GetMainExecutable(Argv0,
1108 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001109 if (!MainExecutablePath.isEmpty()) {
1110 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1111 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001112
1113 // Get foo/lib/clang/1.0/include
1114 //
1115 // FIXME: Don't embed version here.
1116 MainExecutablePath.appendComponent("lib");
1117 MainExecutablePath.appendComponent("clang");
1118 MainExecutablePath.appendComponent("1.0");
1119 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001120
1121 // We pass true to ignore sysroot so that we *always* look for clang headers
1122 // relative to our executable, never relative to -isysroot.
1123 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1124 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001125 }
1126
Nico Weber0fca0222008-08-22 09:25:22 +00001127 if (!nostdinc)
1128 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001129
1130 // Now that we have collected all of the include paths, merge them all
1131 // together and tell the preprocessor about them.
1132
Nico Weber0fca0222008-08-22 09:25:22 +00001133 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001134}
1135
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001136//===----------------------------------------------------------------------===//
1137// Driver PreprocessorFactory - For lazily generating preprocessors ...
1138//===----------------------------------------------------------------------===//
1139
1140namespace {
1141class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001142 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001143 Diagnostic &Diags;
1144 const LangOptions &LangInfo;
1145 TargetInfo &Target;
1146 SourceManager &SourceMgr;
1147 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001148 bool InitializeSourceMgr;
1149
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001150public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001151 DriverPreprocessorFactory(const std::string &infile,
1152 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001153 TargetInfo &target, SourceManager &SM,
1154 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001155 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1156 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1157
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001158
1159 virtual ~DriverPreprocessorFactory() {}
1160
1161 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001162 llvm::OwningPtr<PTHManager> PTHMgr;
1163
Ted Kremenek748d5d62009-03-20 00:26:38 +00001164 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1165 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1166 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001167 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001168 }
1169
Ted Kremenek72b1b152009-01-15 18:47:46 +00001170 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001171 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1172 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001173 PTHMgr.reset(PTHManager::Create(x, &Diags,
1174 TokenCache.empty() ? Diagnostic::Error
1175 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001176 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001177
Ted Kremenek22f0d092009-03-22 06:42:39 +00001178 if (Diags.hasErrorOccurred())
1179 exit(1);
1180
Ted Kremenek72b1b152009-01-15 18:47:46 +00001181 // Create the Preprocessor.
1182 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1183 SourceMgr, HeaderInfo,
1184 PTHMgr.get()));
1185
1186 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1187 // That argument is used as the IdentifierInfoLookup argument to
1188 // IdentifierTable's ctor.
1189 if (PTHMgr) {
1190 PTHMgr->setPreprocessor(PP.get());
1191 PP->setPTHManager(PTHMgr.take());
1192 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001193
Chris Lattner51574ea2008-04-19 23:25:44 +00001194 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001195 return NULL;
1196 }
1197
Daniel Dunbar750c3582008-10-24 22:12:41 +00001198 /// FIXME: PP can only handle one callback
1199 if (ProgAction != PrintPreprocessedInput) {
1200 const char* ErrStr;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001201 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001202 if (!DFG && ErrStr) {
Ted Kremenek9a30c242008-10-25 20:19:34 +00001203 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001204 return NULL;
1205 }
1206 }
1207
Ted Kremenek339b9c22008-04-17 22:31:54 +00001208 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001209 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001210 }
1211};
1212}
Reid Spencer5f016e22007-07-11 17:01:13 +00001213
Reid Spencer5f016e22007-07-11 17:01:13 +00001214//===----------------------------------------------------------------------===//
1215// Basic Parser driver
1216//===----------------------------------------------------------------------===//
1217
Chris Lattner51574ea2008-04-19 23:25:44 +00001218static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001220 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001221
1222 // Parsing the specified input file.
1223 P.ParseTranslationUnit();
1224 delete PA;
1225}
1226
1227//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001228// Code generation options
1229//===----------------------------------------------------------------------===//
1230
1231static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001232GenerateDebugInfo("g",
1233 llvm::cl::desc("Generate source level debug information"));
1234
1235static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00001236OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbar70f92432008-10-23 05:50:47 +00001237
Chris Lattnerbd360642009-03-26 05:00:52 +00001238static llvm::cl::opt<bool>
1239NoCommon("fno-common",
Mike Stump1c9b7422009-03-27 20:15:22 +00001240 llvm::cl::desc("Compile common globals like normal definitions"),
Chris Lattner925a7042009-03-28 02:12:08 +00001241 llvm::cl::ValueDisallowed);
Chris Lattnerbd360642009-03-26 05:00:52 +00001242
Daniel Dunbar70f92432008-10-23 05:50:47 +00001243// It might be nice to add bounds to the CommandLine library directly.
1244struct OptLevelParser : public llvm::cl::parser<unsigned> {
1245 bool parse(llvm::cl::Option &O, const char *ArgName,
1246 const std::string &Arg, unsigned &Val) {
1247 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1248 return true;
1249 // FIXME: Support -O4.
1250 if (Val > 3)
1251 return O.error(": '" + Arg + "' invalid optimization level!");
1252 return false;
1253 }
1254};
1255static llvm::cl::opt<unsigned, false, OptLevelParser>
1256OptLevel("O", llvm::cl::Prefix,
1257 llvm::cl::desc("Optimization level"),
1258 llvm::cl::init(0));
1259
Daniel Dunbara034ba82009-02-17 19:47:34 +00001260static llvm::cl::opt<std::string>
1261TargetCPU("mcpu",
1262 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1263
Chris Lattner7afae712009-03-16 18:41:18 +00001264static void InitializeCompileOptions(CompileOptions &Opts,
1265 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001266 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001267 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001268 if (OptSize) {
1269 // -Os implies -O2
1270 // FIXME: Diagnose conflicting options.
1271 Opts.OptimizationLevel = 2;
1272 } else {
1273 Opts.OptimizationLevel = OptLevel;
1274 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001275
1276 // FIXME: There are llvm-gcc options to control these selectively.
1277 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1278 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001279 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001280
1281#ifdef NDEBUG
1282 Opts.VerifyModule = 0;
1283#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001284
1285 Opts.CPU = TargetCPU;
1286 Opts.Features.insert(Opts.Features.end(),
1287 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001288
Chris Lattnerbd360642009-03-26 05:00:52 +00001289 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1290
Chris Lattner44502662009-02-18 01:23:44 +00001291 // Handle -ftime-report.
1292 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001293}
1294
1295//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001296// Main driver
1297//===----------------------------------------------------------------------===//
1298
Ted Kremenekdb094a22007-12-05 18:27:04 +00001299/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001300/// action. These consumers can operate on both ASTs that are freshly
1301/// parsed from source files as well as those deserialized from Bitcode.
1302/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001303static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001304 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001305 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001306 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001307 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001308 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001309 default:
1310 return NULL;
1311
1312 case ASTPrint:
1313 return CreateASTPrinter();
1314
1315 case ASTDump:
1316 return CreateASTDumper();
1317
1318 case ASTView:
1319 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001320
Chris Lattner8a5c8092009-02-18 01:20:05 +00001321 case PrintDeclContext:
1322 return CreateDeclContextPrinter();
1323
1324 case EmitHTML:
1325 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001326
Chris Lattner8a5c8092009-02-18 01:20:05 +00001327 case InheritanceView:
1328 return CreateInheritanceViewer(InheritanceViewCls);
1329
1330 case TestSerialization:
1331 return CreateSerializationTest(Diag, FileMgr);
1332
1333 case EmitAssembly:
1334 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001335 case EmitBC:
1336 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001337 BackendAction Act;
1338 if (ProgAction == EmitAssembly)
1339 Act = Backend_EmitAssembly;
1340 else if (ProgAction == EmitLLVM)
1341 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001342 else if (ProgAction == EmitLLVMOnly)
1343 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001344 else
1345 Act = Backend_EmitBC;
1346
1347 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001348 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001349 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001350 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001351 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001352
Chris Lattner8a5c8092009-02-18 01:20:05 +00001353 case SerializeAST:
1354 // FIXME: Allow user to tailor where the file is written.
1355 return CreateASTSerializer(InFile, OutputFile, Diag);
1356
1357 case RewriteObjC:
1358 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001359
Chris Lattner8a5c8092009-02-18 01:20:05 +00001360 case RewriteBlocks:
1361 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1362
1363 case RunAnalysis:
1364 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001365 }
1366}
1367
Reid Spencer5f016e22007-07-11 17:01:13 +00001368/// ProcessInputFile - Process a single input file with the specified state.
1369///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001370static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001371 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001372 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001373 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001374
Ted Kremenek85888962008-10-21 00:54:44 +00001375 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001377 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1378 PP.getFileManager(), PP.getLangOptions(),
1379 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001380
1381 if (!Consumer) {
1382 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001383 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001384 return;
1385 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001386
Ted Kremenekdb094a22007-12-05 18:27:04 +00001387 break;
1388
Chris Lattnerc106c102008-10-12 05:03:36 +00001389 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001390 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001391 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001392 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001393 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001394 RawLex.SetKeepWhitespaceMode(true);
1395
1396 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001397 RawLex.LexFromRawLexer(RawTok);
1398 while (RawTok.isNot(tok::eof)) {
1399 PP.DumpToken(RawTok, true);
1400 fprintf(stderr, "\n");
1401 RawLex.LexFromRawLexer(RawTok);
1402 }
1403 ClearSourceMgr = true;
1404 break;
1405 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001407 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001408 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001409 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001410 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 do {
1412 PP.Lex(Tok);
1413 PP.DumpToken(Tok, true);
1414 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001415 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001416 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 break;
1418 }
1419 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001420 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001421 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001423 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 do {
1425 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001426 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001427 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 break;
1429 }
Ted Kremenek85888962008-10-21 00:54:44 +00001430
1431 case GeneratePCH: {
Chris Lattner47099742009-02-18 01:51:21 +00001432 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001433 CacheTokens(PP, OutputFile);
1434 ClearSourceMgr = true;
1435 break;
1436 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001437
Chris Lattner47099742009-02-18 01:51:21 +00001438 case PrintPreprocessedInput: { // -E mode.
1439 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001440 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001441 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 break;
Chris Lattner47099742009-02-18 01:51:21 +00001443 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001444
Chris Lattner47099742009-02-18 01:51:21 +00001445 case ParseNoop: { // -parse-noop
1446 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001447 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001448 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 break;
Chris Lattner47099742009-02-18 01:51:21 +00001450 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001451
Chris Lattner47099742009-02-18 01:51:21 +00001452 case ParsePrintCallbacks: {
1453 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001454 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001455 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 break;
Chris Lattner47099742009-02-18 01:51:21 +00001457 }
1458
1459 case ParseSyntaxOnly: { // -fsyntax-only
1460 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001461 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001462 break;
Chris Lattner47099742009-02-18 01:51:21 +00001463 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001464
1465 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001466 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001467 ClearSourceMgr = true;
1468 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001469
Chris Lattner47099742009-02-18 01:51:21 +00001470 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001471 DoRewriteTest(PP, InFile, OutputFile);
1472 ClearSourceMgr = true;
1473 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001474 }
Chris Lattner47099742009-02-18 01:51:21 +00001475 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001476
1477 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001478 llvm::OwningPtr<ASTContext> ContextOwner;
1479 llvm::OwningPtr<TranslationUnit> TranslationUnitOwner;
1480
1481 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1482 PP.getSourceManager(),
1483 PP.getTargetInfo(),
1484 PP.getIdentifierTable(),
1485 PP.getSelectorTable(),
1486 /* FreeMemory = */ !DisableFree));
1487 TranslationUnitOwner.reset(new TranslationUnit(*ContextOwner.get()));
1488
1489
1490 ParseAST(PP, Consumer.get(), *TranslationUnitOwner.get(), Stats);
1491
1492 // If in -disable-free mode, don't deallocate these when they go out of
1493 // scope.
Ted Kremenek46157b52009-01-28 04:29:29 +00001494 if (DisableFree) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001495 ContextOwner.take();
1496 TranslationUnitOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001497 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001498 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001499
1500 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001501 if (CheckDiagnostics(PP))
1502 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001503
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001505 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 PP.PrintStats();
1507 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001508 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001509 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 fprintf(stderr, "\n");
1511 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001512
1513 // For a multi-file compilation, some things are ok with nuking the source
1514 // manager tables, other require stable fileid/macroid's across multiple
1515 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001516 if (ClearSourceMgr)
1517 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001518
1519 if (DisableFree)
1520 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001521}
1522
Ted Kremenek20e97482007-12-12 23:41:08 +00001523static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1524 FileManager& FileMgr) {
1525
1526 if (VerifyDiagnostics) {
1527 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1528 exit (1);
1529 }
1530
1531 llvm::sys::Path Filename(InFile);
1532
1533 if (!Filename.isValid()) {
1534 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1535 exit (1);
1536 }
1537
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001538 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001539
1540 if (!TU) {
1541 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1542 InFile.c_str());
1543 exit (1);
1544 }
1545
Ted Kremenek63ea8632007-12-19 19:27:38 +00001546 // Observe that we use the source file name stored in the deserialized
1547 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001548 llvm::OwningPtr<ASTConsumer>
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001549 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001550 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001551
Ted Kremenek20e97482007-12-12 23:41:08 +00001552 if (!Consumer) {
1553 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1554 exit (1);
1555 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001556
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001557 Consumer->Initialize(TU->getContext());
Nico Weber7bfaaae2008-08-10 19:59:06 +00001558
Chris Lattnere66b65c2008-02-06 01:42:25 +00001559 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001560 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1561 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001562}
1563
1564
Reid Spencer5f016e22007-07-11 17:01:13 +00001565static llvm::cl::list<std::string>
1566InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1567
Ted Kremenek20e97482007-12-12 23:41:08 +00001568static bool isSerializedFile(const std::string& InFile) {
1569 if (InFile.size() < 4)
1570 return false;
1571
1572 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001573 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001574}
1575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576
1577int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001579 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001580 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001581 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001582
Chris Lattner47099742009-02-18 01:51:21 +00001583 if (TimeReport)
1584 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1585
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 // If no input was specified, read from stdin.
1587 if (InputFilenames.empty())
1588 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001589
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 // Create a file manager object to provide access to and cache the filesystem.
1591 FileManager FileMgr;
1592
Ted Kremenek31e703b2007-12-11 23:28:38 +00001593 // Create the diagnostic client for reporting errors or for
1594 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001595 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001596
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001597 if (!VerifyDiagnostics) {
1598 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001599 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1600 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001601 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001602 !NoShowLocation,
1603 PrintSourceRangeInfo);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001604 } else {
1605 // When checking diagnostics, just buffer them up.
1606 TextDiagClient = new TextDiagnosticBuffer();
1607
1608 if (InputFilenames.size() != 1) {
1609 fprintf(stderr,
1610 "-verify only works on single input files for now.\n");
1611 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 }
1613 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001614
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001616 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1617 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001618 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001619 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001620
Chris Lattner4f037832007-12-05 23:24:17 +00001621 // -I- is a deprecated GCC feature, scan for it and reject it.
1622 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1623 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001624 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001625 I_dirs.erase(I_dirs.begin()+i);
1626 --i;
1627 }
1628 }
Chris Lattner11215192008-03-14 06:12:05 +00001629
1630 // Get information about the target being compiled for.
1631 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001632 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1633
Chris Lattner11215192008-03-14 06:12:05 +00001634 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001635 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1636 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001637 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001638 }
Chris Lattner4f037832007-12-05 23:24:17 +00001639
Daniel Dunbard4270232009-01-20 23:17:32 +00001640 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001641 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001642
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001643 llvm::OwningPtr<SourceManager> SourceMgr;
1644
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001646 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001647
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001648 if (isSerializedFile(InFile)) {
1649 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001650 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001651 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001652 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001653
1654 /// Create a SourceManager object. This tracks and owns all the file
1655 /// buffers allocated to a translation unit.
1656 if (!SourceMgr)
1657 SourceMgr.reset(new SourceManager());
1658 else
1659 SourceMgr->clearIDTables();
1660
1661 // Initialize language options, inferring file types from input filenames.
1662 LangOptions LangInfo;
1663 InitializeBaseLanguage();
1664 LangKind LK = GetLanguage(InFile);
1665 bool PCH = InitializeLangOptions(LangInfo, LK);
1666 InitializeGCMode(LangInfo);
1667 InitializeLanguageStandard(LangInfo, LK, Target.get());
1668
1669 // Process the -I options and set them in the HeaderInfo.
1670 HeaderSearch HeaderInfo(FileMgr);
1671
1672 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1673
1674 // Set up the preprocessor with these options.
1675 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1676 *SourceMgr.get(), HeaderInfo);
1677
1678 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1679
1680 if (!PP)
1681 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001682
Chris Lattnerf63aea32009-03-04 21:40:56 +00001683 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1684 // always reset to using TextDiagClient.
1685 llvm::OwningPtr<DiagnosticClient> TmpClient;
1686
1687 if (!HTMLDiag.empty()) {
1688 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1689 &PPFactory));
1690 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001691 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001692 else
1693 Diags.setClient(TextDiagClient);
1694
1695 // Process the source file.
1696 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1697
1698 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 }
Chris Lattner11215192008-03-14 06:12:05 +00001700
Mike Stump007f2a92009-01-28 02:43:35 +00001701 if (Verbose)
1702 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1703 " hosted on " LLVM_HOSTTRIPLE "\n");
1704
Ted Kremenek7a08e282008-08-07 18:13:12 +00001705 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1707 (NumDiagnostics == 1 ? "" : "s"));
1708
1709 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 FileMgr.PrintStats();
1711 fprintf(stderr, "\n");
1712 }
1713
Daniel Dunbar276373d2008-10-27 22:10:13 +00001714 // If verifying diagnostics and we reached here, all is well.
1715 if (VerifyDiagnostics)
1716 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001717
1718 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001719
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001720 // Managed static deconstruction. Useful for making things like
1721 // -time-passes usable.
1722 llvm::llvm_shutdown();
1723
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001724 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001725}