blob: 1a114a637e82091969420e4f8186f68f584923bb [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattner39fb14e2009-02-18 01:17:01 +000020// -Wfatal-errors
Chris Lattner4b009652007-07-25 00:24:17 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Ted Kremenek377a3192009-03-31 18:58:14 +000025#include "clang-cc.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000029#include "clang/Frontend/InitHeaderSearch.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000030#include "clang/Frontend/PathDiagnosticClients.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000031#include "clang/Frontend/TextDiagnosticBuffer.h"
32#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000033#include "clang/Analysis/PathDiagnostic.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000034#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000035#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000036#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000037#include "clang/AST/ASTConsumer.h"
Chris Lattnerfc318192009-03-28 04:31:31 +000038#include "clang/AST/ASTContext.h"
39#include "clang/AST/Decl.h"
Chris Lattnera17991f2009-03-29 16:50:03 +000040#include "clang/AST/DeclGroup.h"
Chris Lattner4b009652007-07-25 00:24:17 +000041#include "clang/Parse/Parser.h"
42#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000043#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000044#include "clang/Basic/FileManager.h"
45#include "clang/Basic/SourceManager.h"
46#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000047#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000048#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000049#include "llvm/ADT/StringExtras.h"
50#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000051#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000052#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000053#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000054#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000055#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000056#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000057#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000058#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000059#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000060using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// Global options.
64//===----------------------------------------------------------------------===//
65
Chris Lattnerefe33382009-02-18 01:51:21 +000066/// ClangFrontendTimer - The front-end activities should charge time to it with
67/// TimeRegion. The -ftime-report option controls whether this will do
68/// anything.
69llvm::Timer *ClangFrontendTimer = 0;
70
Daniel Dunbar4efedde2008-10-16 16:54:18 +000071static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000072
Chris Lattner4b009652007-07-25 00:24:17 +000073static llvm::cl::opt<bool>
74Verbose("v", llvm::cl::desc("Enable verbose output"));
75static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000076Stats("print-stats",
77 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000078static llvm::cl::opt<bool>
79DisableFree("disable-free",
80 llvm::cl::desc("Disable freeing of memory on exit"),
81 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000082
83enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000084 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000085 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000086 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000087 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000088 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000089 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000090 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000091 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +000092 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek397de012007-12-13 00:37:31 +000093 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000094 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000095 ASTPrint, // Parse ASTs and print them.
96 ASTDump, // Parse ASTs and dump them.
97 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000098 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000099 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +0000100 ParsePrintCallbacks, // Parse and print each callback.
101 ParseSyntaxOnly, // Parse and perform semantic analysis.
102 ParseNoop, // Parse with noop callbacks.
103 RunPreprocessorOnly, // Just lex, no output.
104 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000105 DumpTokens, // Dump out preprocessed tokens.
106 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000107 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000108 GeneratePCH, // Generate precompiled header.
109 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000110};
111
112static llvm::cl::opt<ProgActions>
113ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
114 llvm::cl::init(ParseSyntaxOnly),
115 llvm::cl::values(
116 clEnumValN(RunPreprocessorOnly, "Eonly",
117 "Just run preprocessor, no output (for timings)"),
118 clEnumValN(PrintPreprocessedInput, "E",
119 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000120 clEnumValN(DumpRawTokens, "dump-raw-tokens",
121 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000122 clEnumValN(RunAnalysis, "analyze",
123 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000124 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000125 "Run preprocessor, dump internal rep of tokens"),
126 clEnumValN(ParseNoop, "parse-noop",
127 "Run parser with noop callbacks (for timings)"),
128 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
129 "Run parser and perform semantic analysis"),
130 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
131 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000132 clEnumValN(EmitHTML, "emit-html",
133 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000134 clEnumValN(ASTPrint, "ast-print",
135 "Build ASTs and then pretty-print them"),
136 clEnumValN(ASTDump, "ast-dump",
137 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000138 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000139 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000140 clEnumValN(PrintDeclContext, "print-decl-contexts",
141 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000142 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000143 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000144 clEnumValN(EmitAssembly, "S",
145 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000146 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000147 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000148 clEnumValN(EmitBC, "emit-llvm-bc",
149 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000150 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
151 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000152 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000153 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000154 clEnumValN(RewriteTest, "rewrite-test",
155 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000156 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000157 "Rewrite ObjC into C (code rewriter example)"),
158 clEnumValN(RewriteMacros, "rewrite-macros",
159 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000160 clEnumValN(RewriteBlocks, "rewrite-blocks",
161 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000162 clEnumValEnd));
163
Ted Kremenekd01eae62007-12-19 19:47:59 +0000164
165static llvm::cl::opt<std::string>
166OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000167 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000168 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000169
Ted Kremenek57f25b22008-12-02 19:57:31 +0000170
171//===----------------------------------------------------------------------===//
172// PTH.
173//===----------------------------------------------------------------------===//
174
175static llvm::cl::opt<std::string>
176TokenCache("token-cache", llvm::cl::value_desc("path"),
177 llvm::cl::desc("Use specified token cache file"));
178
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000179//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000180// Diagnostic Options
181//===----------------------------------------------------------------------===//
182
Ted Kremenek10389cf2007-09-26 19:42:19 +0000183static llvm::cl::opt<bool>
184VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000185 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000186
Ted Kremenekfd75e312008-03-27 06:17:42 +0000187static llvm::cl::opt<std::string>
188HTMLDiag("html-diags",
189 llvm::cl::desc("Generate HTML to report diagnostics"),
190 llvm::cl::value_desc("HTML directory"));
191
Nico Weber0e13eaa2008-08-05 23:33:20 +0000192static llvm::cl::opt<bool>
193NoShowColumn("fno-show-column",
194 llvm::cl::desc("Do not include column number on diagnostics"));
195
196static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000197NoShowLocation("fno-show-source-location",
198 llvm::cl::desc("Do not include source location information with"
199 " diagnostics"));
200
201static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000202NoCaretDiagnostics("fno-caret-diagnostics",
203 llvm::cl::desc("Do not include source line and caret with"
204 " diagnostics"));
205
Chris Lattner695a4f52009-03-13 01:08:23 +0000206static llvm::cl::opt<bool>
207PrintSourceRangeInfo("fprint-source-range-info",
208 llvm::cl::desc("Print source range spans in numeric form"));
209
Nico Weber0e13eaa2008-08-05 23:33:20 +0000210
Chris Lattner4b009652007-07-25 00:24:17 +0000211//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000212// C++ Visualization.
213//===----------------------------------------------------------------------===//
214
215static llvm::cl::opt<std::string>
216InheritanceViewCls("cxx-inheritance-view",
217 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000218 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000219
220//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000221// Builtin Options
222//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000223
224static llvm::cl::opt<bool>
225TimeReport("ftime-report",
226 llvm::cl::desc("Print the amount of time each "
227 "phase of compilation takes"));
228
Douglas Gregor23d23262009-02-14 20:49:29 +0000229static llvm::cl::opt<bool>
230Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000231 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000232 "freestanding environment"));
233
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000234static llvm::cl::opt<bool>
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000235AllowBuiltins("fbuiltin",
236 llvm::cl::desc("Disable implicit builtin knowledge of functions"),
237 llvm::cl::init(true), llvm::cl::AllowInverse);
Chris Lattner911b8672009-03-13 22:38:49 +0000238
239
240static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000241MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000242 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000243 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000244
Douglas Gregor23d23262009-02-14 20:49:29 +0000245//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000246// Language Options
247//===----------------------------------------------------------------------===//
248
249enum LangKind {
250 langkind_unspecified,
251 langkind_c,
252 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000253 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000254 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000255 langkind_cxx,
256 langkind_cxx_cpp,
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000257 langkind_cxx_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000258 langkind_objc,
259 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000260 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000261 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000262 langkind_objcxx_cpp,
263 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000264};
265
Chris Lattner4b009652007-07-25 00:24:17 +0000266static llvm::cl::opt<LangKind>
267BaseLang("x", llvm::cl::desc("Base language to compile"),
268 llvm::cl::init(langkind_unspecified),
269 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
270 clEnumValN(langkind_cxx, "c++", "C++"),
271 clEnumValN(langkind_objc, "objective-c", "Objective C"),
272 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000273 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000274 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000275 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
276 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000277 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000278 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000279 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
280 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000281 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000282 "Preprocessed Objective C++"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000283 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000284 "Precompiled C header"),
285 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000286 "Precompiled Objective-C header"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000287 clEnumValN(langkind_cxx_pch, "c++-header",
288 "Precompiled C++ header"),
Ted Kremenekceacc812009-01-09 00:38:08 +0000289 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
290 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000291 clEnumValEnd));
292
293static llvm::cl::opt<bool>
294LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
295 llvm::cl::Hidden);
296static llvm::cl::opt<bool>
297LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
298 llvm::cl::Hidden);
299
Ted Kremenek11ad8952007-12-05 23:49:08 +0000300/// InitializeBaseLanguage - Handle the -x foo options.
301static void InitializeBaseLanguage() {
302 if (LangObjC)
303 BaseLang = langkind_objc;
304 else if (LangObjCXX)
305 BaseLang = langkind_objcxx;
306}
307
308static LangKind GetLanguage(const std::string &Filename) {
309 if (BaseLang != langkind_unspecified)
310 return BaseLang;
311
312 std::string::size_type DotPos = Filename.rfind('.');
313
314 if (DotPos == std::string::npos) {
315 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000316 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000317 }
318
Ted Kremenek11ad8952007-12-05 23:49:08 +0000319 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
320 // C header: .h
321 // C++ header: .hh or .H;
322 // assembler no preprocessing: .s
323 // assembler: .S
324 if (Ext == "c")
325 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000326 else if (Ext == "S" ||
327 // If the compiler is run on a .s file, preprocess it as .S
328 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000329 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000330 else if (Ext == "i")
331 return langkind_c_cpp;
332 else if (Ext == "ii")
333 return langkind_cxx_cpp;
334 else if (Ext == "m")
335 return langkind_objc;
336 else if (Ext == "mi")
337 return langkind_objc_cpp;
338 else if (Ext == "mm" || Ext == "M")
339 return langkind_objcxx;
340 else if (Ext == "mii")
341 return langkind_objcxx_cpp;
342 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
343 Ext == "c++" || Ext == "cp" || Ext == "cxx")
344 return langkind_cxx;
345 else
346 return langkind_c;
347}
348
349
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000350static void InitializeCOptions(LangOptions &Options) {
351 // Do nothing.
352}
353
354static void InitializeObjCOptions(LangOptions &Options) {
355 Options.ObjC1 = Options.ObjC2 = 1;
356}
357
358
359static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000360 // FIXME: implement -fpreprocessed mode.
361 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000362 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000363
364 // Test for 'PCH'.
365 switch (LK) {
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000366 default:
367 break;
368 case langkind_c_pch:
369 LK = langkind_c;
370 PCH = true;
371 break;
372 case langkind_objc_pch:
373 LK = langkind_objc;
374 PCH = true;
375 break;
376 case langkind_cxx_pch:
377 LK = langkind_cxx;
378 PCH = true;
379 break;
380 case langkind_objcxx_pch:
381 LK = langkind_objcxx;
382 PCH = true;
383 break;
Ted Kremenekceacc812009-01-09 00:38:08 +0000384 }
Chris Lattner4b009652007-07-25 00:24:17 +0000385
Ted Kremenek11ad8952007-12-05 23:49:08 +0000386 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000387 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000388 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000389 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000390 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000391 case langkind_c_cpp:
392 NoPreprocess = true;
393 // FALLTHROUGH
394 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000395 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000396 break;
397 case langkind_cxx_cpp:
398 NoPreprocess = true;
399 // FALLTHROUGH
400 case langkind_cxx:
401 Options.CPlusPlus = 1;
402 break;
403 case langkind_objc_cpp:
404 NoPreprocess = true;
405 // FALLTHROUGH
406 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000407 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000408 break;
409 case langkind_objcxx_cpp:
410 NoPreprocess = true;
411 // FALLTHROUGH
412 case langkind_objcxx:
413 Options.ObjC1 = Options.ObjC2 = 1;
414 Options.CPlusPlus = 1;
415 break;
416 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000417
418 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000419}
420
421/// LangStds - Language standards we support.
422enum LangStds {
423 lang_unspecified,
424 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000425 lang_gnu_START,
426 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000427 lang_cxx98, lang_gnucxx98,
428 lang_cxx0x, lang_gnucxx0x
429};
430
431static llvm::cl::opt<LangStds>
432LangStd("std", llvm::cl::desc("Language standard to compile for"),
433 llvm::cl::init(lang_unspecified),
434 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
435 clEnumValN(lang_c89, "c90", "ISO C 1990"),
436 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
437 clEnumValN(lang_c94, "iso9899:199409",
438 "ISO C 1990 with amendment 1"),
439 clEnumValN(lang_c99, "c99", "ISO C 1999"),
440// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
441 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
442// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
443 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000444 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000445 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000446 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000447 clEnumValN(lang_gnu99, "gnu9x",
448 "ISO C 1999 with GNU extensions"),
449 clEnumValN(lang_cxx98, "c++98",
450 "ISO C++ 1998 with amendments"),
451 clEnumValN(lang_gnucxx98, "gnu++98",
452 "ISO C++ 1998 with amendments and GNU "
453 "extensions (default for C++)"),
454 clEnumValN(lang_cxx0x, "c++0x",
455 "Upcoming ISO C++ 200x with amendments"),
456 clEnumValN(lang_gnucxx0x, "gnu++0x",
457 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000458 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000459 clEnumValEnd));
460
461static llvm::cl::opt<bool>
462NoOperatorNames("fno-operator-names",
463 llvm::cl::desc("Do not treat C++ operator name keywords as "
464 "synonyms for operators"));
465
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000466static llvm::cl::opt<bool>
467PascalStrings("fpascal-strings",
468 llvm::cl::desc("Recognize and construct Pascal-style "
469 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000470
471static llvm::cl::opt<bool>
472MSExtensions("fms-extensions",
473 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000474 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000475
476static llvm::cl::opt<bool>
477WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000478 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000479
480static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000481NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000482 llvm::cl::desc("Disallow implicit conversions between "
483 "vectors with a different number of "
484 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000485
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000486static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000487EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
488 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
489 llvm::cl::ZeroOrMore);
490
491static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000492EnableHeinousExtensions("fheinous-gnu-extensions",
493 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
494 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
495
496static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000497ObjCNonFragileABI("fobjc-nonfragile-abi",
498 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000499
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000500static llvm::cl::opt<bool>
501EmitAllDecls("femit-all-decls",
502 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000503
Daniel Dunbar91692d92008-08-11 17:36:14 +0000504// FIXME: This (and all GCC -f options) really come in -f... and
505// -fno-... forms, and additionally support automagic behavior when
506// they are not defined. For example, -fexceptions defaults to on or
507// off depending on the language. We should support this behavior in
508// some form (perhaps just add a facility for distinguishing when an
509// has its default value from when it has been set to its default
510// value).
511static llvm::cl::opt<bool>
512Exceptions("fexceptions",
513 llvm::cl::desc("Enable support for exception handling."));
514
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000515static llvm::cl::opt<bool>
516GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000517 llvm::cl::desc("Generate output compatible with the standard GNU "
518 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000519
520static llvm::cl::opt<bool>
521NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000522 llvm::cl::desc("Generate output compatible with the NeXT "
523 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000524
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000525
526
527static llvm::cl::opt<bool>
528Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
529
530static llvm::cl::opt<bool>
531Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
532
Chris Lattner738d3f62009-03-02 22:11:07 +0000533static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000534TargetFeatures("mattr", llvm::cl::CommaSeparated,
535 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
536
Douglas Gregor375733c2009-03-10 00:06:19 +0000537static llvm::cl::opt<unsigned>
538TemplateDepth("ftemplate-depth", llvm::cl::init(99),
539 llvm::cl::desc("Maximum depth of recursive template "
540 "instantiation"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000541
Chris Lattner4b009652007-07-25 00:24:17 +0000542// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000543// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000544static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
545 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000546 // Allow the target to set the default the langauge options as it sees fit.
547 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000548
Chris Lattnerf6790a82009-03-03 19:56:18 +0000549 // If there are any -mattr options, pass them to the target for validation and
550 // processing. The driver should have already consolidated all the
551 // target-feature settings and passed them to us in the -mattr list. The
552 // -mattr list is treated by the code generator as a diff against the -mcpu
553 // setting, but the driver should pass all enabled options as "+" settings.
554 // This means that the target should only look at + settings.
555 if (!TargetFeatures.empty()
556 // FIXME: The driver is not quite yet ready for this.
557 && 0) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000558 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000559 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
560 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000561 if (Opt != -1) {
562 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000563 fprintf(stderr, "invalid feature '%s'\n",
564 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000565 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000566 fprintf(stderr, "feature '%s': %s\n",
567 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000568 exit(1);
569 }
570 }
571
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000572 if (Ansi) // "The -ansi option is equivalent to -std=c89."
573 LangStd = lang_c89;
574
Chris Lattner4b009652007-07-25 00:24:17 +0000575 if (LangStd == lang_unspecified) {
576 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000577 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000578 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000579 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000580 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000581 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000582 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000583 case langkind_objc:
584 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000585 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000586 LangStd = lang_gnu99;
587 break;
588 case langkind_cxx:
589 case langkind_cxx_cpp:
Ted Kremenek6be44de2009-03-19 18:21:42 +0000590 case langkind_cxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000591 case langkind_objcxx:
592 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000593 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000594 LangStd = lang_gnucxx98;
595 break;
596 }
597 }
598
599 switch (LangStd) {
600 default: assert(0 && "Unknown language standard!");
601
602 // Fall through from newer standards to older ones. This isn't really right.
603 // FIXME: Enable specifically the right features based on the language stds.
604 case lang_gnucxx0x:
605 case lang_cxx0x:
606 Options.CPlusPlus0x = 1;
607 // FALL THROUGH
608 case lang_gnucxx98:
609 case lang_cxx98:
610 Options.CPlusPlus = 1;
611 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000612 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000613 // FALL THROUGH.
614 case lang_gnu99:
615 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000616 Options.C99 = 1;
617 Options.HexFloats = 1;
618 // FALL THROUGH.
619 case lang_gnu89:
620 Options.BCPLComment = 1; // Only for C99/C++.
621 // FALL THROUGH.
622 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000623 Options.Digraphs = 1; // C94, C99, C++.
624 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000625 case lang_c89:
626 break;
627 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000628
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000629 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
630 Options.GNUMode = LangStd >= lang_gnu_START;
631
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000632 if (Options.CPlusPlus) {
633 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000634 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000635 }
Chris Lattner4b009652007-07-25 00:24:17 +0000636
Chris Lattner6ab935b2008-04-05 06:32:51 +0000637 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
638 Options.ImplicitInt = 1;
639 else
640 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000641
642 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
643 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000644 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000645 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000646 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000647
Chris Lattner58d5ba52008-12-05 00:10:44 +0000648 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
649 // even if they are normally on for the target. In GNU modes (e.g.
650 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000651 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000652 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000653 Options.Blocks = 0;
654
Daniel Dunbar551236b2009-03-15 00:11:28 +0000655 // Never accept '$' in identifiers when preprocessing assembler.
656 if (LK != langkind_asm_cpp)
657 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000658 if (PascalStrings.getPosition())
659 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000660 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000661 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000662 if (NoLaxVectorConversions.getPosition())
663 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000664 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000665 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000666 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000667
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000668 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000669 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000670 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000671 Options.Freestanding = Options.NoBuiltin = 1;
672
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000673 if (EnableHeinousExtensions)
674 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000675
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000676 Options.MathErrno = MathErrno;
677
Douglas Gregor375733c2009-03-10 00:06:19 +0000678 Options.InstantiationDepth = TemplateDepth;
679
Chris Lattnerddae7102008-12-04 22:54:33 +0000680 // Override the default runtime if the user requested it.
681 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000682 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000683 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000684 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000685
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000686 if (ObjCNonFragileABI)
687 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000688
689 if (EmitAllDecls)
690 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000691}
692
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000693static llvm::cl::opt<bool>
694ObjCExclusiveGC("fobjc-gc-only",
695 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000696 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000697
698static llvm::cl::opt<bool>
699ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000700 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000701
702void InitializeGCMode(LangOptions &Options) {
703 if (ObjCExclusiveGC)
704 Options.setGCMode(LangOptions::GCOnly);
705 else if (ObjCEnableGC)
706 Options.setGCMode(LangOptions::HybridGC);
707}
708
Chris Lattner4b009652007-07-25 00:24:17 +0000709//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000710// Target Triple Processing.
711//===----------------------------------------------------------------------===//
712
713static llvm::cl::opt<std::string>
714TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000715 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000716
Chris Lattnerfc457002008-03-05 01:18:20 +0000717static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000718Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000719
Chris Lattner2b168e02008-09-30 01:13:12 +0000720static llvm::cl::opt<std::string>
721MacOSVersionMin("mmacosx-version-min",
722 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
723
Chris Lattner01de9c82008-09-30 20:16:56 +0000724// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
725// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000726
727// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000728static void HandleMacOSVersionMin(std::string &Triple) {
729 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
730 if (DarwinDashIdx == std::string::npos) {
731 fprintf(stderr,
732 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
733 exit(1);
734 }
735 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
736
Chris Lattner01de9c82008-09-30 20:16:56 +0000737 // Remove the number.
738 Triple.resize(DarwinNumIdx);
739
740 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
741 bool MacOSVersionMinIsInvalid = false;
742 int VersionNum = 0;
743 if (MacOSVersionMin.size() < 4 ||
744 MacOSVersionMin.substr(0, 3) != "10." ||
745 !isdigit(MacOSVersionMin[3])) {
746 MacOSVersionMinIsInvalid = true;
747 } else {
748 const char *Start = MacOSVersionMin.c_str()+3;
749 char *End = 0;
750 VersionNum = (int)strtol(Start, &End, 10);
751
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000752 // The version number must be in the range 0-9.
753 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
754
Chris Lattner01de9c82008-09-30 20:16:56 +0000755 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
756 Triple += llvm::itostr(VersionNum+4);
757
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000758 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
759 // Add the period piece (.7) to the end of the triple. This gives us
760 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000761 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000762 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
763 MacOSVersionMinIsInvalid = true;
764 }
765 }
766
767 if (MacOSVersionMinIsInvalid) {
768 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000769 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000770 MacOSVersionMin.c_str());
771 exit(1);
772 }
773}
774
775/// CreateTargetTriple - Process the various options that affect the target
776/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000777static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000778 // Initialize base triple. If a -triple option has been specified, use
779 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000780 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000781 if (Triple.empty())
782 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000783
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000784 // If -arch foo was specified, remove the architecture from the triple we have
785 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000786
787 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +0000788 if (!Arch.empty()) {
789 // Decompose the base triple into "arch" and suffix.
790 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000791
Chris Lattner2b168e02008-09-30 01:13:12 +0000792 if (FirstDashIdx == std::string::npos) {
793 fprintf(stderr,
794 "Malformed target triple: \"%s\" ('-' could not be found).\n",
795 Triple.c_str());
796 exit(1);
797 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +0000798
799 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
800 if (Arch == "ppc")
801 Arch = "powerpc";
802 else if (Arch == "ppc64")
803 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +0000804
Chris Lattner2b168e02008-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 Lattner01de9c82008-09-30 20:16:56 +0000810 if (!MacOSVersionMin.empty())
811 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000812
Chris Lattner2b168e02008-09-30 01:13:12 +0000813 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000814}
815
816//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000817// Preprocessor Initialization
818//===----------------------------------------------------------------------===//
819
820// FIXME: Preprocessor builtins to support.
821// -A... - Play with #assertions
822// -undef - Undefine all predefined macros
823
Chris Lattner695a4f52009-03-13 01:08:23 +0000824// FIXME: -imacros
825
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner008da782008-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
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000837static llvm::cl::opt<std::string>
838ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
839 llvm::cl::desc("Include file before parsing"));
840
Chris Lattner4b009652007-07-25 00:24:17 +0000841// Append a #define line to Buf for Macro. Macro should be of the form XXX,
842// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
843// "#define XXX Y z W". To get a #define with no value, use "XXX=".
844static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
845 const char *Command = "#define ") {
846 Buf.insert(Buf.end(), Command, Command+strlen(Command));
847 if (const char *Equal = strchr(Macro, '=')) {
848 // Turn the = into ' '.
849 Buf.insert(Buf.end(), Macro, Equal);
850 Buf.push_back(' ');
851 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
852 } else {
853 // Push "macroname 1".
854 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
855 Buf.push_back(' ');
856 Buf.push_back('1');
857 }
858 Buf.push_back('\n');
859}
860
Chris Lattner008da782008-01-10 01:53:41 +0000861/// AddImplicitInclude - Add an implicit #include of the specified file to the
862/// predefines buffer.
863static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
864 const char *Inc = "#include \"";
865 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
866 Buf.insert(Buf.end(), File.begin(), File.end());
867 Buf.push_back('"');
868 Buf.push_back('\n');
869}
870
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000871/// AddImplicitIncludePTH - Add an implicit #include using the original file
872/// used to generate a PTH cache.
873static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
874 PTHManager *P = PP.getPTHManager();
875 assert(P && "No PTHManager.");
876 const char *OriginalFile = P->getOriginalSourceFile();
877
878 if (!OriginalFile) {
879 assert(!ImplicitIncludePTH.empty());
880 fprintf(stderr, "error: PTH file '%s' does not designate an original "
881 "source header file for -include-pth\n",
882 ImplicitIncludePTH.c_str());
883 exit (1);
884 }
885
886 AddImplicitInclude(Buf, OriginalFile);
887}
Chris Lattner4b009652007-07-25 00:24:17 +0000888
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000889/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000890/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000891///
Chris Lattner9d818a22008-04-19 23:25:44 +0000892static bool InitializePreprocessor(Preprocessor &PP,
893 bool InitializeSourceMgr,
894 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000895 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000896
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000897 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000898 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000899
900 if (InitializeSourceMgr) {
901 if (InFile != "-") {
902 const FileEntry *File = FileMgr.getFile(InFile);
903 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000904 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +0000905 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
906 << InFile.c_str();
Chris Lattner9d818a22008-04-19 23:25:44 +0000907 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000908 }
909 } else {
910 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar99617162009-03-21 17:56:30 +0000911
912 // If stdin was empty, SB is null. Cons up an empty memory
913 // buffer now.
914 if (!SB) {
915 const char *EmptyStr = "";
916 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
917 }
918
919 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000920 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +0000921 PP.getDiagnostics().Report(FullSourceLoc(),
922 diag::err_fe_error_reading_stdin);
Chris Lattner9d818a22008-04-19 23:25:44 +0000923 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000924 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000925 }
Chris Lattner4b009652007-07-25 00:24:17 +0000926 }
Sam Bishop61a20782008-04-14 14:41:57 +0000927
Chris Lattner47b6a162008-04-19 23:09:31 +0000928 std::vector<char> PredefineBuffer;
929
Chris Lattner4b009652007-07-25 00:24:17 +0000930 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000931 unsigned d = 0, D = D_macros.size();
932 unsigned u = 0, U = U_macros.size();
933 while (d < D || u < U) {
934 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
935 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
936 else
937 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
938 }
939
Chris Lattner008da782008-01-10 01:53:41 +0000940 // FIXME: Read any files specified by -imacros.
941
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000942 // Add implicit #includes from -include and -include-pth.
943 bool handledPTH = ImplicitIncludePTH.empty();
944 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc4ecf322009-03-20 00:40:03 +0000945 if (!handledPTH &&
946 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000947 AddImplicitIncludePTH(PredefineBuffer, PP);
948 handledPTH = true;
949 }
950
Chris Lattner008da782008-01-10 01:53:41 +0000951 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000952 }
953 if (!handledPTH && !ImplicitIncludePTH.empty())
954 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000955
Chris Lattner47b6a162008-04-19 23:09:31 +0000956 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000957 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000958 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000959
960 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000961 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000962}
963
964//===----------------------------------------------------------------------===//
965// Preprocessor include path information.
966//===----------------------------------------------------------------------===//
967
968// This tool exports a large number of command line options to control how the
969// preprocessor searches for header files. At root, however, the Preprocessor
970// object takes a very simple interface: a list of directories to search for
971//
972// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000973// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000974//
Chris Lattner4b009652007-07-25 00:24:17 +0000975
976static llvm::cl::opt<bool>
977nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
978
979// Various command line options. These four add directories to each chain.
980static llvm::cl::list<std::string>
981F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
982 llvm::cl::desc("Add directory to framework include search path"));
983static llvm::cl::list<std::string>
984I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
985 llvm::cl::desc("Add directory to include search path"));
986static llvm::cl::list<std::string>
987idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
988 llvm::cl::desc("Add directory to AFTER include search path"));
989static llvm::cl::list<std::string>
990iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
991 llvm::cl::desc("Add directory to QUOTE include search path"));
992static llvm::cl::list<std::string>
993isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
994 llvm::cl::desc("Add directory to SYSTEM include search path"));
995
996// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
997static llvm::cl::list<std::string>
998iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
999 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1000static llvm::cl::list<std::string>
1001iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1002 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1003static llvm::cl::list<std::string>
1004iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1005 llvm::cl::Prefix,
1006 llvm::cl::desc("Set directory to include search path with prefix"));
1007
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001008static llvm::cl::opt<std::string>
1009isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1010 llvm::cl::desc("Set the system root directory (usually /)"));
1011
Chris Lattner4b009652007-07-25 00:24:17 +00001012// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001013
Chris Lattner4b009652007-07-25 00:24:17 +00001014/// InitializeIncludePaths - Process the -I options and set them in the
1015/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001016void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1017 FileManager &FM, const LangOptions &Lang) {
1018 InitHeaderSearch Init(Headers, Verbose, isysroot);
1019
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001020 // Handle -I... and -F... options, walking the lists in parallel.
1021 unsigned Iidx = 0, Fidx = 0;
1022 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1023 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001024 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001025 ++Iidx;
1026 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001027 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001028 ++Fidx;
1029 }
1030 }
Chris Lattner4b009652007-07-25 00:24:17 +00001031
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001032 // Consume what's left from whatever list was longer.
1033 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001034 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001035 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001036 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001037
1038 // Handle -idirafter... options.
1039 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001040 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1041 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001042
1043 // Handle -iquote... options.
1044 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001045 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001046
1047 // Handle -isystem... options.
1048 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001049 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001050
1051 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1052 // parallel, processing the values in order of occurance to get the right
1053 // prefixes.
1054 {
1055 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1056 unsigned iprefix_idx = 0;
1057 unsigned iwithprefix_idx = 0;
1058 unsigned iwithprefixbefore_idx = 0;
1059 bool iprefix_done = iprefix_vals.empty();
1060 bool iwithprefix_done = iwithprefix_vals.empty();
1061 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1062 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1063 if (!iprefix_done &&
1064 (iwithprefix_done ||
1065 iprefix_vals.getPosition(iprefix_idx) <
1066 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1067 (iwithprefixbefore_done ||
1068 iprefix_vals.getPosition(iprefix_idx) <
1069 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1070 Prefix = iprefix_vals[iprefix_idx];
1071 ++iprefix_idx;
1072 iprefix_done = iprefix_idx == iprefix_vals.size();
1073 } else if (!iwithprefix_done &&
1074 (iwithprefixbefore_done ||
1075 iwithprefix_vals.getPosition(iwithprefix_idx) <
1076 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001077 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1078 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001079 ++iwithprefix_idx;
1080 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1081 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001082 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1083 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001084 ++iwithprefixbefore_idx;
1085 iwithprefixbefore_done =
1086 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1087 }
1088 }
1089 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001090
Nico Weber770e3882008-08-22 09:25:22 +00001091 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001092
Daniel Dunbar4e604292009-02-21 20:52:41 +00001093 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001094 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001095 llvm::sys::Path::GetMainExecutable(Argv0,
1096 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001097 if (!MainExecutablePath.isEmpty()) {
1098 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1099 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001100
1101 // Get foo/lib/clang/1.0/include
1102 //
1103 // FIXME: Don't embed version here.
1104 MainExecutablePath.appendComponent("lib");
1105 MainExecutablePath.appendComponent("clang");
1106 MainExecutablePath.appendComponent("1.0");
1107 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001108
1109 // We pass true to ignore sysroot so that we *always* look for clang headers
1110 // relative to our executable, never relative to -isysroot.
1111 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1112 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001113 }
1114
Nico Weber770e3882008-08-22 09:25:22 +00001115 if (!nostdinc)
1116 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001117
1118 // Now that we have collected all of the include paths, merge them all
1119 // together and tell the preprocessor about them.
1120
Nico Weber770e3882008-08-22 09:25:22 +00001121 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001122}
1123
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001124//===----------------------------------------------------------------------===//
1125// Driver PreprocessorFactory - For lazily generating preprocessors ...
1126//===----------------------------------------------------------------------===//
1127
1128namespace {
1129class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001130 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001131 Diagnostic &Diags;
1132 const LangOptions &LangInfo;
1133 TargetInfo &Target;
1134 SourceManager &SourceMgr;
1135 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001136 bool InitializeSourceMgr;
1137
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001138public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001139 DriverPreprocessorFactory(const std::string &infile,
1140 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001141 TargetInfo &target, SourceManager &SM,
1142 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001143 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1144 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1145
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001146
1147 virtual ~DriverPreprocessorFactory() {}
1148
1149 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001150 llvm::OwningPtr<PTHManager> PTHMgr;
1151
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001152 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1153 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1154 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001155 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001156 }
1157
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001158 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001159 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1160 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001161 PTHMgr.reset(PTHManager::Create(x, &Diags,
1162 TokenCache.empty() ? Diagnostic::Error
1163 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001164 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001165
Ted Kremenek6348cc62009-03-22 06:42:39 +00001166 if (Diags.hasErrorOccurred())
1167 exit(1);
1168
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001169 // Create the Preprocessor.
1170 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1171 SourceMgr, HeaderInfo,
1172 PTHMgr.get()));
1173
1174 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1175 // That argument is used as the IdentifierInfoLookup argument to
1176 // IdentifierTable's ctor.
1177 if (PTHMgr) {
1178 PTHMgr->setPreprocessor(PP.get());
1179 PP->setPTHManager(PTHMgr.take());
1180 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001181
Chris Lattner9d818a22008-04-19 23:25:44 +00001182 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001183 return NULL;
1184 }
1185
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001186 /// FIXME: PP can only handle one callback
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001187 if (ProgAction != PrintPreprocessedInput) {
1188 std::string ErrStr;
1189 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1190 if (!DFG && !ErrStr.empty()) {
1191 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001192 return NULL;
1193 }
1194 }
1195
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001196 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001197 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001198 }
1199};
1200}
Chris Lattner4b009652007-07-25 00:24:17 +00001201
Chris Lattner4b009652007-07-25 00:24:17 +00001202//===----------------------------------------------------------------------===//
1203// Basic Parser driver
1204//===----------------------------------------------------------------------===//
1205
Chris Lattner9d818a22008-04-19 23:25:44 +00001206static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001207 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001208 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001209
1210 // Parsing the specified input file.
1211 P.ParseTranslationUnit();
1212 delete PA;
1213}
1214
1215//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001216// Code generation options
1217//===----------------------------------------------------------------------===//
1218
1219static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001220GenerateDebugInfo("g",
1221 llvm::cl::desc("Generate source level debug information"));
1222
1223static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001224OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001225
Chris Lattnerf04a7562009-03-26 05:00:52 +00001226static llvm::cl::opt<bool>
1227NoCommon("fno-common",
Mike Stumpf58df972009-03-27 20:15:22 +00001228 llvm::cl::desc("Compile common globals like normal definitions"),
Chris Lattner64c19972009-03-28 02:12:08 +00001229 llvm::cl::ValueDisallowed);
Chris Lattnerf04a7562009-03-26 05:00:52 +00001230
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001231// It might be nice to add bounds to the CommandLine library directly.
1232struct OptLevelParser : public llvm::cl::parser<unsigned> {
1233 bool parse(llvm::cl::Option &O, const char *ArgName,
1234 const std::string &Arg, unsigned &Val) {
1235 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1236 return true;
1237 // FIXME: Support -O4.
1238 if (Val > 3)
1239 return O.error(": '" + Arg + "' invalid optimization level!");
1240 return false;
1241 }
1242};
1243static llvm::cl::opt<unsigned, false, OptLevelParser>
1244OptLevel("O", llvm::cl::Prefix,
1245 llvm::cl::desc("Optimization level"),
1246 llvm::cl::init(0));
1247
Daniel Dunbar9101a632009-02-17 19:47:34 +00001248static llvm::cl::opt<std::string>
1249TargetCPU("mcpu",
1250 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1251
Chris Lattner8a9615c2009-03-16 18:41:18 +00001252static void InitializeCompileOptions(CompileOptions &Opts,
1253 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001254 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001255 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001256 if (OptSize) {
1257 // -Os implies -O2
1258 // FIXME: Diagnose conflicting options.
1259 Opts.OptimizationLevel = 2;
1260 } else {
1261 Opts.OptimizationLevel = OptLevel;
1262 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001263
1264 // FIXME: There are llvm-gcc options to control these selectively.
1265 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1266 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001267 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001268
1269#ifdef NDEBUG
1270 Opts.VerifyModule = 0;
1271#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001272
1273 Opts.CPU = TargetCPU;
1274 Opts.Features.insert(Opts.Features.end(),
1275 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001276
Chris Lattnerf04a7562009-03-26 05:00:52 +00001277 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1278
Chris Lattnere8f70712009-02-18 01:23:44 +00001279 // Handle -ftime-report.
1280 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001281}
1282
1283//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001284// Main driver
1285//===----------------------------------------------------------------------===//
1286
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001287/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001288/// action. These consumers can operate on both ASTs that are freshly
1289/// parsed from source files as well as those deserialized from Bitcode.
1290/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001291static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001292 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001293 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001294 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001295 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001296 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001297 default:
1298 return NULL;
1299
1300 case ASTPrint:
1301 return CreateASTPrinter();
1302
1303 case ASTDump:
1304 return CreateASTDumper();
1305
1306 case ASTView:
1307 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001308
Chris Lattner7f902922009-02-18 01:20:05 +00001309 case PrintDeclContext:
1310 return CreateDeclContextPrinter();
1311
1312 case EmitHTML:
1313 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001314
Chris Lattner7f902922009-02-18 01:20:05 +00001315 case InheritanceView:
1316 return CreateInheritanceViewer(InheritanceViewCls);
1317
1318 case TestSerialization:
1319 return CreateSerializationTest(Diag, FileMgr);
1320
1321 case EmitAssembly:
1322 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001323 case EmitBC:
1324 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001325 BackendAction Act;
1326 if (ProgAction == EmitAssembly)
1327 Act = Backend_EmitAssembly;
1328 else if (ProgAction == EmitLLVM)
1329 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001330 else if (ProgAction == EmitLLVMOnly)
1331 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001332 else
1333 Act = Backend_EmitBC;
1334
1335 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001336 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001337 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001338 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001339 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001340
Chris Lattner7f902922009-02-18 01:20:05 +00001341 case SerializeAST:
1342 // FIXME: Allow user to tailor where the file is written.
1343 return CreateASTSerializer(InFile, OutputFile, Diag);
1344
1345 case RewriteObjC:
1346 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001347
Chris Lattner7f902922009-02-18 01:20:05 +00001348 case RewriteBlocks:
1349 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1350
1351 case RunAnalysis:
1352 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001353 }
1354}
1355
Chris Lattner4b009652007-07-25 00:24:17 +00001356/// ProcessInputFile - Process a single input file with the specified state.
1357///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001358static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001359 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001360 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001361 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001362
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001363 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001364 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001365 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1366 PP.getFileManager(), PP.getLangOptions(),
1367 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001368
1369 if (!Consumer) {
1370 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001371 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001372 return;
1373 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001374
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001375 break;
1376
Chris Lattneraf669fb2008-10-12 05:03:36 +00001377 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001378 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001379 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001380 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001381 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001382 RawLex.SetKeepWhitespaceMode(true);
1383
1384 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001385 RawLex.LexFromRawLexer(RawTok);
1386 while (RawTok.isNot(tok::eof)) {
1387 PP.DumpToken(RawTok, true);
1388 fprintf(stderr, "\n");
1389 RawLex.LexFromRawLexer(RawTok);
1390 }
1391 ClearSourceMgr = true;
1392 break;
1393 }
Chris Lattner4b009652007-07-25 00:24:17 +00001394 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001395 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001396 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001397 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001398 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001399 do {
1400 PP.Lex(Tok);
1401 PP.DumpToken(Tok, true);
1402 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001403 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001404 ClearSourceMgr = true;
1405 break;
1406 }
1407 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001408 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001409 Token Tok;
1410 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001411 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001412 do {
1413 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001414 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001415 ClearSourceMgr = true;
1416 break;
1417 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001418
1419 case GeneratePCH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001420 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001421 CacheTokens(PP, OutputFile);
1422 ClearSourceMgr = true;
1423 break;
1424 }
Chris Lattner4b009652007-07-25 00:24:17 +00001425
Chris Lattnerefe33382009-02-18 01:51:21 +00001426 case PrintPreprocessedInput: { // -E mode.
1427 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001428 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001429 ClearSourceMgr = true;
1430 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001431 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001432
Chris Lattnerefe33382009-02-18 01:51:21 +00001433 case ParseNoop: { // -parse-noop
1434 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001435 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001436 ClearSourceMgr = true;
1437 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001438 }
Chris Lattner4b009652007-07-25 00:24:17 +00001439
Chris Lattnerefe33382009-02-18 01:51:21 +00001440 case ParsePrintCallbacks: {
1441 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001442 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001443 ClearSourceMgr = true;
1444 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001445 }
1446
1447 case ParseSyntaxOnly: { // -fsyntax-only
1448 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001449 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001450 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001451 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001452
1453 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001454 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001455 ClearSourceMgr = true;
1456 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001457
Chris Lattnerefe33382009-02-18 01:51:21 +00001458 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001459 DoRewriteTest(PP, InFile, OutputFile);
1460 ClearSourceMgr = true;
1461 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001462 }
Chris Lattnerefe33382009-02-18 01:51:21 +00001463 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001464
1465 if (Consumer) {
Chris Lattner143fd6d2009-03-28 01:37:17 +00001466 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner143fd6d2009-03-28 01:37:17 +00001467
1468 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1469 PP.getSourceManager(),
1470 PP.getTargetInfo(),
1471 PP.getIdentifierTable(),
1472 PP.getSelectorTable(),
1473 /* FreeMemory = */ !DisableFree));
Chris Lattner143fd6d2009-03-28 01:37:17 +00001474
1475
Chris Lattner07b08c02009-03-28 04:13:34 +00001476 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner143fd6d2009-03-28 01:37:17 +00001477
1478 // If in -disable-free mode, don't deallocate these when they go out of
1479 // scope.
Chris Lattner07b08c02009-03-28 04:13:34 +00001480 if (DisableFree)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001481 ContextOwner.take();
Ted Kremenek88eebed2009-01-28 04:29:29 +00001482 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001483
1484 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001485 if (CheckDiagnostics(PP))
1486 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001487
Chris Lattner4b009652007-07-25 00:24:17 +00001488 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001489 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001490 PP.PrintStats();
1491 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001492 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001493 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001494 fprintf(stderr, "\n");
1495 }
1496
1497 // For a multi-file compilation, some things are ok with nuking the source
1498 // manager tables, other require stable fileid/macroid's across multiple
1499 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001500 if (ClearSourceMgr)
1501 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001502
1503 if (DisableFree)
1504 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001505}
1506
Ted Kremenek80d53372007-12-12 23:41:08 +00001507static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1508 FileManager& FileMgr) {
1509
1510 if (VerifyDiagnostics) {
1511 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1512 exit (1);
1513 }
1514
1515 llvm::sys::Path Filename(InFile);
1516
1517 if (!Filename.isValid()) {
1518 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1519 exit (1);
1520 }
1521
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001522 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner06459ae2009-03-28 03:49:26 +00001523
1524 // Create the memory buffer that contains the contents of the file.
1525 llvm::OwningPtr<llvm::MemoryBuffer>
1526 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1527
1528 if (MBuffer)
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001529 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001530
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001531 if (!Ctx) {
Ted Kremenek2bd42412007-12-13 18:11:11 +00001532 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1533 InFile.c_str());
1534 exit (1);
1535 }
1536
Ted Kremenekab749372007-12-19 19:27:38 +00001537 // Observe that we use the source file name stored in the deserialized
1538 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001539 llvm::OwningPtr<ASTConsumer>
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001540 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001541 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001542
Ted Kremenek80d53372007-12-12 23:41:08 +00001543 if (!Consumer) {
1544 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1545 exit (1);
1546 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001547
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001548 Consumer->Initialize(*Ctx);
Nico Weberd2a6ac92008-08-10 19:59:06 +00001549
Chris Lattner8d72ee02008-02-06 01:42:25 +00001550 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001551 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1552 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1553 I != E; ++I)
Chris Lattnera17991f2009-03-29 16:50:03 +00001554 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek80d53372007-12-12 23:41:08 +00001555}
1556
1557
Chris Lattner4b009652007-07-25 00:24:17 +00001558static llvm::cl::list<std::string>
1559InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1560
Ted Kremenek80d53372007-12-12 23:41:08 +00001561static bool isSerializedFile(const std::string& InFile) {
1562 if (InFile.size() < 4)
1563 return false;
1564
1565 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00001566 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00001567}
1568
Chris Lattner4b009652007-07-25 00:24:17 +00001569
1570int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001571 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001572 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001573 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001574 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001575
Chris Lattnerefe33382009-02-18 01:51:21 +00001576 if (TimeReport)
1577 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1578
Chris Lattner4b009652007-07-25 00:24:17 +00001579 // If no input was specified, read from stdin.
1580 if (InputFilenames.empty())
1581 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001582
Chris Lattner4b009652007-07-25 00:24:17 +00001583 // Create a file manager object to provide access to and cache the filesystem.
1584 FileManager FileMgr;
1585
Ted Kremenekb240e822007-12-11 23:28:38 +00001586 // Create the diagnostic client for reporting errors or for
1587 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001588 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001589
Ted Kremenek5c341732008-08-07 17:49:57 +00001590 if (!VerifyDiagnostics) {
1591 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001592 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1593 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001594 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00001595 !NoShowLocation,
1596 PrintSourceRangeInfo);
Ted Kremenek5c341732008-08-07 17:49:57 +00001597 } else {
1598 // When checking diagnostics, just buffer them up.
1599 TextDiagClient = new TextDiagnosticBuffer();
1600
1601 if (InputFilenames.size() != 1) {
1602 fprintf(stderr,
1603 "-verify only works on single input files for now.\n");
1604 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001605 }
1606 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001607
Chris Lattner4b009652007-07-25 00:24:17 +00001608 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001609 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1610 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001611 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001612 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001613
Chris Lattner45a56e02007-12-05 23:24:17 +00001614 // -I- is a deprecated GCC feature, scan for it and reject it.
1615 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1616 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001617 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001618 I_dirs.erase(I_dirs.begin()+i);
1619 --i;
1620 }
1621 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001622
1623 // Get information about the target being compiled for.
1624 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001625 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1626
Chris Lattner2c77d852008-03-14 06:12:05 +00001627 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001628 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1629 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001630 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001631 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001632
Daniel Dunbar9c321102009-01-20 23:17:32 +00001633 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001634 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001635
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001636 llvm::OwningPtr<SourceManager> SourceMgr;
1637
Chris Lattner4b009652007-07-25 00:24:17 +00001638 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001639 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001640
Ted Kremenek5c341732008-08-07 17:49:57 +00001641 if (isSerializedFile(InFile)) {
1642 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001643 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00001644 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001645 }
Chris Lattner2b989562009-03-04 21:40:56 +00001646
1647 /// Create a SourceManager object. This tracks and owns all the file
1648 /// buffers allocated to a translation unit.
1649 if (!SourceMgr)
1650 SourceMgr.reset(new SourceManager());
1651 else
1652 SourceMgr->clearIDTables();
1653
1654 // Initialize language options, inferring file types from input filenames.
1655 LangOptions LangInfo;
1656 InitializeBaseLanguage();
1657 LangKind LK = GetLanguage(InFile);
1658 bool PCH = InitializeLangOptions(LangInfo, LK);
1659 InitializeGCMode(LangInfo);
1660 InitializeLanguageStandard(LangInfo, LK, Target.get());
1661
1662 // Process the -I options and set them in the HeaderInfo.
1663 HeaderSearch HeaderInfo(FileMgr);
1664
1665 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1666
1667 // Set up the preprocessor with these options.
1668 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1669 *SourceMgr.get(), HeaderInfo);
1670
1671 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1672
1673 if (!PP)
1674 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001675
Chris Lattner2b989562009-03-04 21:40:56 +00001676 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1677 // always reset to using TextDiagClient.
1678 llvm::OwningPtr<DiagnosticClient> TmpClient;
1679
1680 if (!HTMLDiag.empty()) {
1681 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1682 &PPFactory));
1683 Diags.setClient(TmpClient.get());
Ted Kremenek80d53372007-12-12 23:41:08 +00001684 }
Chris Lattner2b989562009-03-04 21:40:56 +00001685 else
1686 Diags.setClient(TextDiagClient);
1687
1688 // Process the source file.
1689 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1690
1691 HeaderInfo.ClearFileInfo();
Chris Lattner4b009652007-07-25 00:24:17 +00001692 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001693
Mike Stump91d01352009-01-28 02:43:35 +00001694 if (Verbose)
1695 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1696 " hosted on " LLVM_HOSTTRIPLE "\n");
1697
Ted Kremenekec6c5252008-08-07 18:13:12 +00001698 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001699 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1700 (NumDiagnostics == 1 ? "" : "s"));
1701
1702 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001703 FileMgr.PrintStats();
1704 fprintf(stderr, "\n");
1705 }
1706
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001707 // If verifying diagnostics and we reached here, all is well.
1708 if (VerifyDiagnostics)
1709 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001710
1711 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001712
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001713 // Managed static deconstruction. Useful for making things like
1714 // -time-passes usable.
1715 llvm::llvm_shutdown();
1716
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001717 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001718}