blob: b149a1da92b06005181d753789905c2634632dc0 [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",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000141 "Print DeclContexts and their Decls"),
142 clEnumValN(GeneratePCH, "emit-pth",
143 "Generate pre-tokenized header file"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000144 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000145 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000146 clEnumValN(EmitAssembly, "S",
147 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000148 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000149 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000150 clEnumValN(EmitBC, "emit-llvm-bc",
151 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000152 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
153 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000154 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000155 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000156 clEnumValN(RewriteTest, "rewrite-test",
157 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000158 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000159 "Rewrite ObjC into C (code rewriter example)"),
160 clEnumValN(RewriteMacros, "rewrite-macros",
161 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000162 clEnumValN(RewriteBlocks, "rewrite-blocks",
163 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000164 clEnumValEnd));
165
Ted Kremenekd01eae62007-12-19 19:47:59 +0000166
167static llvm::cl::opt<std::string>
168OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000169 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000170 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000171
Ted Kremenek57f25b22008-12-02 19:57:31 +0000172
173//===----------------------------------------------------------------------===//
174// PTH.
175//===----------------------------------------------------------------------===//
176
177static llvm::cl::opt<std::string>
178TokenCache("token-cache", llvm::cl::value_desc("path"),
179 llvm::cl::desc("Use specified token cache file"));
180
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000181//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000182// Diagnostic Options
183//===----------------------------------------------------------------------===//
184
Ted Kremenek10389cf2007-09-26 19:42:19 +0000185static llvm::cl::opt<bool>
186VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000187 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000188
Ted Kremenekfd75e312008-03-27 06:17:42 +0000189static llvm::cl::opt<std::string>
190HTMLDiag("html-diags",
191 llvm::cl::desc("Generate HTML to report diagnostics"),
192 llvm::cl::value_desc("HTML directory"));
193
Nico Weber0e13eaa2008-08-05 23:33:20 +0000194static llvm::cl::opt<bool>
195NoShowColumn("fno-show-column",
196 llvm::cl::desc("Do not include column number on diagnostics"));
197
198static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000199NoShowLocation("fno-show-source-location",
200 llvm::cl::desc("Do not include source location information with"
201 " diagnostics"));
202
203static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000204NoCaretDiagnostics("fno-caret-diagnostics",
205 llvm::cl::desc("Do not include source line and caret with"
206 " diagnostics"));
207
Chris Lattner695a4f52009-03-13 01:08:23 +0000208static llvm::cl::opt<bool>
209PrintSourceRangeInfo("fprint-source-range-info",
210 llvm::cl::desc("Print source range spans in numeric form"));
211
Nico Weber0e13eaa2008-08-05 23:33:20 +0000212
Chris Lattner4b009652007-07-25 00:24:17 +0000213//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000214// C++ Visualization.
215//===----------------------------------------------------------------------===//
216
217static llvm::cl::opt<std::string>
218InheritanceViewCls("cxx-inheritance-view",
219 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000220 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000221
222//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000223// Builtin Options
224//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000225
226static llvm::cl::opt<bool>
227TimeReport("ftime-report",
228 llvm::cl::desc("Print the amount of time each "
229 "phase of compilation takes"));
230
Douglas Gregor23d23262009-02-14 20:49:29 +0000231static llvm::cl::opt<bool>
232Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000233 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000234 "freestanding environment"));
235
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000236static llvm::cl::opt<bool>
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000237AllowBuiltins("fbuiltin",
238 llvm::cl::desc("Disable implicit builtin knowledge of functions"),
239 llvm::cl::init(true), llvm::cl::AllowInverse);
Chris Lattner911b8672009-03-13 22:38:49 +0000240
241
242static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000243MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000244 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000245 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000246
Douglas Gregor23d23262009-02-14 20:49:29 +0000247//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000248// Language Options
249//===----------------------------------------------------------------------===//
250
251enum LangKind {
252 langkind_unspecified,
253 langkind_c,
254 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000255 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000256 langkind_cxx,
257 langkind_cxx_cpp,
258 langkind_objc,
259 langkind_objc_cpp,
260 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000261 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000262};
263
Chris Lattner4b009652007-07-25 00:24:17 +0000264static llvm::cl::opt<LangKind>
265BaseLang("x", llvm::cl::desc("Base language to compile"),
266 llvm::cl::init(langkind_unspecified),
267 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
268 clEnumValN(langkind_cxx, "c++", "C++"),
269 clEnumValN(langkind_objc, "objective-c", "Objective C"),
270 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000271 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000272 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000273 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
274 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000275 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000276 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000277 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
278 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000279 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000280 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000281 clEnumValN(langkind_c, "c-header",
282 "C header"),
283 clEnumValN(langkind_objc, "objective-c-header",
284 "Objective-C header"),
285 clEnumValN(langkind_cxx, "c++-header",
286 "C++ header"),
287 clEnumValN(langkind_objcxx, "objective-c++-header",
288 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000289 clEnumValEnd));
290
291static llvm::cl::opt<bool>
292LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
293 llvm::cl::Hidden);
294static llvm::cl::opt<bool>
295LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
296 llvm::cl::Hidden);
297
Ted Kremenek11ad8952007-12-05 23:49:08 +0000298/// InitializeBaseLanguage - Handle the -x foo options.
299static void InitializeBaseLanguage() {
300 if (LangObjC)
301 BaseLang = langkind_objc;
302 else if (LangObjCXX)
303 BaseLang = langkind_objcxx;
304}
305
306static LangKind GetLanguage(const std::string &Filename) {
307 if (BaseLang != langkind_unspecified)
308 return BaseLang;
309
310 std::string::size_type DotPos = Filename.rfind('.');
311
312 if (DotPos == std::string::npos) {
313 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000314 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000315 }
316
Ted Kremenek11ad8952007-12-05 23:49:08 +0000317 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
318 // C header: .h
319 // C++ header: .hh or .H;
320 // assembler no preprocessing: .s
321 // assembler: .S
322 if (Ext == "c")
323 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000324 else if (Ext == "S" ||
325 // If the compiler is run on a .s file, preprocess it as .S
326 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000327 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000328 else if (Ext == "i")
329 return langkind_c_cpp;
330 else if (Ext == "ii")
331 return langkind_cxx_cpp;
332 else if (Ext == "m")
333 return langkind_objc;
334 else if (Ext == "mi")
335 return langkind_objc_cpp;
336 else if (Ext == "mm" || Ext == "M")
337 return langkind_objcxx;
338 else if (Ext == "mii")
339 return langkind_objcxx_cpp;
340 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
341 Ext == "c++" || Ext == "cp" || Ext == "cxx")
342 return langkind_cxx;
343 else
344 return langkind_c;
345}
346
347
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000348static void InitializeCOptions(LangOptions &Options) {
349 // Do nothing.
350}
351
352static void InitializeObjCOptions(LangOptions &Options) {
353 Options.ObjC1 = Options.ObjC2 = 1;
354}
355
356
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000357static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000358 // FIXME: implement -fpreprocessed mode.
359 bool NoPreprocess = false;
360
Ted Kremenek11ad8952007-12-05 23:49:08 +0000361 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000362 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000363 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000364 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000365 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000366 case langkind_c_cpp:
367 NoPreprocess = true;
368 // FALLTHROUGH
369 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000370 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000371 break;
372 case langkind_cxx_cpp:
373 NoPreprocess = true;
374 // FALLTHROUGH
375 case langkind_cxx:
376 Options.CPlusPlus = 1;
377 break;
378 case langkind_objc_cpp:
379 NoPreprocess = true;
380 // FALLTHROUGH
381 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000382 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000383 break;
384 case langkind_objcxx_cpp:
385 NoPreprocess = true;
386 // FALLTHROUGH
387 case langkind_objcxx:
388 Options.ObjC1 = Options.ObjC2 = 1;
389 Options.CPlusPlus = 1;
390 break;
391 }
392}
393
394/// LangStds - Language standards we support.
395enum LangStds {
396 lang_unspecified,
397 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000398 lang_gnu_START,
399 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000400 lang_cxx98, lang_gnucxx98,
401 lang_cxx0x, lang_gnucxx0x
402};
403
404static llvm::cl::opt<LangStds>
405LangStd("std", llvm::cl::desc("Language standard to compile for"),
406 llvm::cl::init(lang_unspecified),
407 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
408 clEnumValN(lang_c89, "c90", "ISO C 1990"),
409 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
410 clEnumValN(lang_c94, "iso9899:199409",
411 "ISO C 1990 with amendment 1"),
412 clEnumValN(lang_c99, "c99", "ISO C 1999"),
413// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
414 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
415// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
416 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000417 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000418 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000419 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000420 clEnumValN(lang_gnu99, "gnu9x",
421 "ISO C 1999 with GNU extensions"),
422 clEnumValN(lang_cxx98, "c++98",
423 "ISO C++ 1998 with amendments"),
424 clEnumValN(lang_gnucxx98, "gnu++98",
425 "ISO C++ 1998 with amendments and GNU "
426 "extensions (default for C++)"),
427 clEnumValN(lang_cxx0x, "c++0x",
428 "Upcoming ISO C++ 200x with amendments"),
429 clEnumValN(lang_gnucxx0x, "gnu++0x",
430 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000431 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000432 clEnumValEnd));
433
434static llvm::cl::opt<bool>
435NoOperatorNames("fno-operator-names",
436 llvm::cl::desc("Do not treat C++ operator name keywords as "
437 "synonyms for operators"));
438
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000439static llvm::cl::opt<bool>
440PascalStrings("fpascal-strings",
441 llvm::cl::desc("Recognize and construct Pascal-style "
442 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000443
444static llvm::cl::opt<bool>
445MSExtensions("fms-extensions",
446 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000447 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000448
449static llvm::cl::opt<bool>
450WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000451 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000452
453static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000454NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000455 llvm::cl::desc("Disallow implicit conversions between "
456 "vectors with a different number of "
457 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000458
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000459static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000460EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
461 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
462 llvm::cl::ZeroOrMore);
463
464static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000465EnableHeinousExtensions("fheinous-gnu-extensions",
466 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
467 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
468
469static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000470ObjCNonFragileABI("fobjc-nonfragile-abi",
471 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000472
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000473static llvm::cl::opt<bool>
474EmitAllDecls("femit-all-decls",
475 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000476
Daniel Dunbar91692d92008-08-11 17:36:14 +0000477// FIXME: This (and all GCC -f options) really come in -f... and
478// -fno-... forms, and additionally support automagic behavior when
479// they are not defined. For example, -fexceptions defaults to on or
480// off depending on the language. We should support this behavior in
481// some form (perhaps just add a facility for distinguishing when an
482// has its default value from when it has been set to its default
483// value).
484static llvm::cl::opt<bool>
485Exceptions("fexceptions",
486 llvm::cl::desc("Enable support for exception handling."));
487
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000488static llvm::cl::opt<bool>
489GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000490 llvm::cl::desc("Generate output compatible with the standard GNU "
491 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000492
493static llvm::cl::opt<bool>
494NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000495 llvm::cl::desc("Generate output compatible with the NeXT "
496 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000497
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000498
499
500static llvm::cl::opt<bool>
501Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
502
503static llvm::cl::opt<bool>
504Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
505
Chris Lattner738d3f62009-03-02 22:11:07 +0000506static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000507TargetFeatures("mattr", llvm::cl::CommaSeparated,
508 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
509
Douglas Gregor375733c2009-03-10 00:06:19 +0000510static llvm::cl::opt<unsigned>
511TemplateDepth("ftemplate-depth", llvm::cl::init(99),
512 llvm::cl::desc("Maximum depth of recursive template "
513 "instantiation"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000514
Chris Lattner4b009652007-07-25 00:24:17 +0000515// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000516// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000517static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
518 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000519 // Allow the target to set the default the langauge options as it sees fit.
520 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000521
Chris Lattnerf6790a82009-03-03 19:56:18 +0000522 // If there are any -mattr options, pass them to the target for validation and
523 // processing. The driver should have already consolidated all the
524 // target-feature settings and passed them to us in the -mattr list. The
525 // -mattr list is treated by the code generator as a diff against the -mcpu
526 // setting, but the driver should pass all enabled options as "+" settings.
527 // This means that the target should only look at + settings.
528 if (!TargetFeatures.empty()
529 // FIXME: The driver is not quite yet ready for this.
530 && 0) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000531 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000532 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
533 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000534 if (Opt != -1) {
535 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000536 fprintf(stderr, "invalid feature '%s'\n",
537 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000538 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000539 fprintf(stderr, "feature '%s': %s\n",
540 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000541 exit(1);
542 }
543 }
544
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000545 if (Ansi) // "The -ansi option is equivalent to -std=c89."
546 LangStd = lang_c89;
547
Chris Lattner4b009652007-07-25 00:24:17 +0000548 if (LangStd == lang_unspecified) {
549 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000550 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000551 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000552 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000553 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000554 case langkind_c_cpp:
555 case langkind_objc:
556 case langkind_objc_cpp:
557 LangStd = lang_gnu99;
558 break;
559 case langkind_cxx:
560 case langkind_cxx_cpp:
561 case langkind_objcxx:
562 case langkind_objcxx_cpp:
563 LangStd = lang_gnucxx98;
564 break;
565 }
566 }
567
568 switch (LangStd) {
569 default: assert(0 && "Unknown language standard!");
570
571 // Fall through from newer standards to older ones. This isn't really right.
572 // FIXME: Enable specifically the right features based on the language stds.
573 case lang_gnucxx0x:
574 case lang_cxx0x:
575 Options.CPlusPlus0x = 1;
576 // FALL THROUGH
577 case lang_gnucxx98:
578 case lang_cxx98:
579 Options.CPlusPlus = 1;
580 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000581 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000582 // FALL THROUGH.
583 case lang_gnu99:
584 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000585 Options.C99 = 1;
586 Options.HexFloats = 1;
587 // FALL THROUGH.
588 case lang_gnu89:
589 Options.BCPLComment = 1; // Only for C99/C++.
590 // FALL THROUGH.
591 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000592 Options.Digraphs = 1; // C94, C99, C++.
593 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000594 case lang_c89:
595 break;
596 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000597
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000598 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
599 Options.GNUMode = LangStd >= lang_gnu_START;
600
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000601 if (Options.CPlusPlus) {
602 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000603 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000604 }
Chris Lattner4b009652007-07-25 00:24:17 +0000605
Chris Lattner6ab935b2008-04-05 06:32:51 +0000606 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
607 Options.ImplicitInt = 1;
608 else
609 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000610
611 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
612 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000613 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000614 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000615 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000616
Chris Lattner58d5ba52008-12-05 00:10:44 +0000617 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
618 // even if they are normally on for the target. In GNU modes (e.g.
619 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000620 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000621 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000622 Options.Blocks = 0;
623
Daniel Dunbar551236b2009-03-15 00:11:28 +0000624 // Never accept '$' in identifiers when preprocessing assembler.
625 if (LK != langkind_asm_cpp)
626 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000627 if (PascalStrings.getPosition())
628 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000629 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000630 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000631 if (NoLaxVectorConversions.getPosition())
632 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000633 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000634 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000635 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000636
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000637 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000638 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000639 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000640 Options.Freestanding = Options.NoBuiltin = 1;
641
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000642 if (EnableHeinousExtensions)
643 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000644
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000645 Options.MathErrno = MathErrno;
646
Douglas Gregor375733c2009-03-10 00:06:19 +0000647 Options.InstantiationDepth = TemplateDepth;
648
Chris Lattnerddae7102008-12-04 22:54:33 +0000649 // Override the default runtime if the user requested it.
650 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000651 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000652 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000653 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000654
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000655 if (ObjCNonFragileABI)
656 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000657
658 if (EmitAllDecls)
659 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000660}
661
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000662static llvm::cl::opt<bool>
663ObjCExclusiveGC("fobjc-gc-only",
664 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000665 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000666
667static llvm::cl::opt<bool>
668ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000669 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000670
671void InitializeGCMode(LangOptions &Options) {
672 if (ObjCExclusiveGC)
673 Options.setGCMode(LangOptions::GCOnly);
674 else if (ObjCEnableGC)
675 Options.setGCMode(LangOptions::HybridGC);
676}
677
Mike Stumpdb789912009-04-01 20:28:16 +0000678static llvm::cl::opt<bool>
679OverflowChecking("ftrapv",
680 llvm::cl::desc("Trap on integer overflow"),
681 llvm::cl::init(false));
682
683void InitializeOverflowChecking(LangOptions &Options) {
684 Options.OverflowChecking = OverflowChecking;
685}
Chris Lattner4b009652007-07-25 00:24:17 +0000686//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000687// Target Triple Processing.
688//===----------------------------------------------------------------------===//
689
690static llvm::cl::opt<std::string>
691TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000692 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000693
Chris Lattnerfc457002008-03-05 01:18:20 +0000694static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000695Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000696
Chris Lattner2b168e02008-09-30 01:13:12 +0000697static llvm::cl::opt<std::string>
698MacOSVersionMin("mmacosx-version-min",
699 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
700
Chris Lattner01de9c82008-09-30 20:16:56 +0000701// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
702// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000703
704// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000705static void HandleMacOSVersionMin(std::string &Triple) {
706 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
707 if (DarwinDashIdx == std::string::npos) {
708 fprintf(stderr,
709 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
710 exit(1);
711 }
712 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
713
Chris Lattner01de9c82008-09-30 20:16:56 +0000714 // Remove the number.
715 Triple.resize(DarwinNumIdx);
716
717 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
718 bool MacOSVersionMinIsInvalid = false;
719 int VersionNum = 0;
720 if (MacOSVersionMin.size() < 4 ||
721 MacOSVersionMin.substr(0, 3) != "10." ||
722 !isdigit(MacOSVersionMin[3])) {
723 MacOSVersionMinIsInvalid = true;
724 } else {
725 const char *Start = MacOSVersionMin.c_str()+3;
726 char *End = 0;
727 VersionNum = (int)strtol(Start, &End, 10);
728
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000729 // The version number must be in the range 0-9.
730 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
731
Chris Lattner01de9c82008-09-30 20:16:56 +0000732 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
733 Triple += llvm::itostr(VersionNum+4);
734
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000735 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
736 // Add the period piece (.7) to the end of the triple. This gives us
737 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000738 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000739 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
740 MacOSVersionMinIsInvalid = true;
741 }
742 }
743
744 if (MacOSVersionMinIsInvalid) {
745 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000746 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000747 MacOSVersionMin.c_str());
748 exit(1);
749 }
750}
751
752/// CreateTargetTriple - Process the various options that affect the target
753/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000754static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000755 // Initialize base triple. If a -triple option has been specified, use
756 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000757 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000758 if (Triple.empty())
759 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000760
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000761 // If -arch foo was specified, remove the architecture from the triple we have
762 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000763
764 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +0000765 if (!Arch.empty()) {
766 // Decompose the base triple into "arch" and suffix.
767 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000768
Chris Lattner2b168e02008-09-30 01:13:12 +0000769 if (FirstDashIdx == std::string::npos) {
770 fprintf(stderr,
771 "Malformed target triple: \"%s\" ('-' could not be found).\n",
772 Triple.c_str());
773 exit(1);
774 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +0000775
776 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
777 if (Arch == "ppc")
778 Arch = "powerpc";
779 else if (Arch == "ppc64")
780 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +0000781
Chris Lattner2b168e02008-09-30 01:13:12 +0000782 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
783 }
784
785 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
786 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000787 if (!MacOSVersionMin.empty())
788 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000789
Chris Lattner2b168e02008-09-30 01:13:12 +0000790 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000791}
792
793//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000794// Preprocessor Initialization
795//===----------------------------------------------------------------------===//
796
797// FIXME: Preprocessor builtins to support.
798// -A... - Play with #assertions
799// -undef - Undefine all predefined macros
800
Chris Lattner695a4f52009-03-13 01:08:23 +0000801// FIXME: -imacros
802
Chris Lattner4b009652007-07-25 00:24:17 +0000803static llvm::cl::list<std::string>
804D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
805 llvm::cl::desc("Predefine the specified macro"));
806static llvm::cl::list<std::string>
807U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
808 llvm::cl::desc("Undefine the specified macro"));
809
Chris Lattner008da782008-01-10 01:53:41 +0000810static llvm::cl::list<std::string>
811ImplicitIncludes("include", llvm::cl::value_desc("file"),
812 llvm::cl::desc("Include file before parsing"));
813
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000814static llvm::cl::opt<std::string>
815ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
816 llvm::cl::desc("Include file before parsing"));
817
Chris Lattner4b009652007-07-25 00:24:17 +0000818// Append a #define line to Buf for Macro. Macro should be of the form XXX,
819// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
820// "#define XXX Y z W". To get a #define with no value, use "XXX=".
821static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
822 const char *Command = "#define ") {
823 Buf.insert(Buf.end(), Command, Command+strlen(Command));
824 if (const char *Equal = strchr(Macro, '=')) {
825 // Turn the = into ' '.
826 Buf.insert(Buf.end(), Macro, Equal);
827 Buf.push_back(' ');
828 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
829 } else {
830 // Push "macroname 1".
831 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
832 Buf.push_back(' ');
833 Buf.push_back('1');
834 }
835 Buf.push_back('\n');
836}
837
Chris Lattner008da782008-01-10 01:53:41 +0000838/// AddImplicitInclude - Add an implicit #include of the specified file to the
839/// predefines buffer.
840static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
841 const char *Inc = "#include \"";
842 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
843 Buf.insert(Buf.end(), File.begin(), File.end());
844 Buf.push_back('"');
845 Buf.push_back('\n');
846}
847
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000848/// AddImplicitIncludePTH - Add an implicit #include using the original file
849/// used to generate a PTH cache.
850static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
851 PTHManager *P = PP.getPTHManager();
852 assert(P && "No PTHManager.");
853 const char *OriginalFile = P->getOriginalSourceFile();
854
855 if (!OriginalFile) {
856 assert(!ImplicitIncludePTH.empty());
857 fprintf(stderr, "error: PTH file '%s' does not designate an original "
858 "source header file for -include-pth\n",
859 ImplicitIncludePTH.c_str());
860 exit (1);
861 }
862
863 AddImplicitInclude(Buf, OriginalFile);
864}
Chris Lattner4b009652007-07-25 00:24:17 +0000865
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000866/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000867/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000868///
Chris Lattner9d818a22008-04-19 23:25:44 +0000869static bool InitializePreprocessor(Preprocessor &PP,
870 bool InitializeSourceMgr,
871 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000872 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000873
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000874 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000875 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000876
877 if (InitializeSourceMgr) {
878 if (InFile != "-") {
879 const FileEntry *File = FileMgr.getFile(InFile);
880 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000881 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +0000882 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
883 << InFile.c_str();
Chris Lattner9d818a22008-04-19 23:25:44 +0000884 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000885 }
886 } else {
887 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar99617162009-03-21 17:56:30 +0000888
889 // If stdin was empty, SB is null. Cons up an empty memory
890 // buffer now.
891 if (!SB) {
892 const char *EmptyStr = "";
893 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
894 }
895
896 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000897 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +0000898 PP.getDiagnostics().Report(FullSourceLoc(),
899 diag::err_fe_error_reading_stdin);
Chris Lattner9d818a22008-04-19 23:25:44 +0000900 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000901 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000902 }
Chris Lattner4b009652007-07-25 00:24:17 +0000903 }
Sam Bishop61a20782008-04-14 14:41:57 +0000904
Chris Lattner47b6a162008-04-19 23:09:31 +0000905 std::vector<char> PredefineBuffer;
906
Chris Lattner4b009652007-07-25 00:24:17 +0000907 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000908 unsigned d = 0, D = D_macros.size();
909 unsigned u = 0, U = U_macros.size();
910 while (d < D || u < U) {
911 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
912 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
913 else
914 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
915 }
916
Chris Lattner008da782008-01-10 01:53:41 +0000917 // FIXME: Read any files specified by -imacros.
918
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000919 // Add implicit #includes from -include and -include-pth.
920 bool handledPTH = ImplicitIncludePTH.empty();
921 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc4ecf322009-03-20 00:40:03 +0000922 if (!handledPTH &&
923 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000924 AddImplicitIncludePTH(PredefineBuffer, PP);
925 handledPTH = true;
926 }
927
Chris Lattner008da782008-01-10 01:53:41 +0000928 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000929 }
930 if (!handledPTH && !ImplicitIncludePTH.empty())
931 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000932
Chris Lattner47b6a162008-04-19 23:09:31 +0000933 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000934 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000935 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000936
937 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000938 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000939}
940
941//===----------------------------------------------------------------------===//
942// Preprocessor include path information.
943//===----------------------------------------------------------------------===//
944
945// This tool exports a large number of command line options to control how the
946// preprocessor searches for header files. At root, however, the Preprocessor
947// object takes a very simple interface: a list of directories to search for
948//
949// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000950// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000951//
Chris Lattner4b009652007-07-25 00:24:17 +0000952
953static llvm::cl::opt<bool>
954nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
955
956// Various command line options. These four add directories to each chain.
957static llvm::cl::list<std::string>
958F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
959 llvm::cl::desc("Add directory to framework include search path"));
960static llvm::cl::list<std::string>
961I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
962 llvm::cl::desc("Add directory to include search path"));
963static llvm::cl::list<std::string>
964idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
965 llvm::cl::desc("Add directory to AFTER include search path"));
966static llvm::cl::list<std::string>
967iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
968 llvm::cl::desc("Add directory to QUOTE include search path"));
969static llvm::cl::list<std::string>
970isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
971 llvm::cl::desc("Add directory to SYSTEM include search path"));
972
973// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
974static llvm::cl::list<std::string>
975iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
976 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
977static llvm::cl::list<std::string>
978iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
979 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
980static llvm::cl::list<std::string>
981iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
982 llvm::cl::Prefix,
983 llvm::cl::desc("Set directory to include search path with prefix"));
984
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000985static llvm::cl::opt<std::string>
986isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
987 llvm::cl::desc("Set the system root directory (usually /)"));
988
Chris Lattner4b009652007-07-25 00:24:17 +0000989// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +0000990
Chris Lattner4b009652007-07-25 00:24:17 +0000991/// InitializeIncludePaths - Process the -I options and set them in the
992/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +0000993void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
994 FileManager &FM, const LangOptions &Lang) {
995 InitHeaderSearch Init(Headers, Verbose, isysroot);
996
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000997 // Handle -I... and -F... options, walking the lists in parallel.
998 unsigned Iidx = 0, Fidx = 0;
999 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1000 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001001 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001002 ++Iidx;
1003 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001004 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001005 ++Fidx;
1006 }
1007 }
Chris Lattner4b009652007-07-25 00:24:17 +00001008
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001009 // Consume what's left from whatever list was longer.
1010 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001011 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001012 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001013 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001014
1015 // Handle -idirafter... options.
1016 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001017 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1018 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001019
1020 // Handle -iquote... options.
1021 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001022 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001023
1024 // Handle -isystem... options.
1025 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001026 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001027
1028 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1029 // parallel, processing the values in order of occurance to get the right
1030 // prefixes.
1031 {
1032 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1033 unsigned iprefix_idx = 0;
1034 unsigned iwithprefix_idx = 0;
1035 unsigned iwithprefixbefore_idx = 0;
1036 bool iprefix_done = iprefix_vals.empty();
1037 bool iwithprefix_done = iwithprefix_vals.empty();
1038 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1039 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1040 if (!iprefix_done &&
1041 (iwithprefix_done ||
1042 iprefix_vals.getPosition(iprefix_idx) <
1043 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1044 (iwithprefixbefore_done ||
1045 iprefix_vals.getPosition(iprefix_idx) <
1046 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1047 Prefix = iprefix_vals[iprefix_idx];
1048 ++iprefix_idx;
1049 iprefix_done = iprefix_idx == iprefix_vals.size();
1050 } else if (!iwithprefix_done &&
1051 (iwithprefixbefore_done ||
1052 iwithprefix_vals.getPosition(iwithprefix_idx) <
1053 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001054 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1055 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001056 ++iwithprefix_idx;
1057 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1058 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001059 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1060 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001061 ++iwithprefixbefore_idx;
1062 iwithprefixbefore_done =
1063 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1064 }
1065 }
1066 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001067
Nico Weber770e3882008-08-22 09:25:22 +00001068 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001069
Daniel Dunbar4e604292009-02-21 20:52:41 +00001070 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001071 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001072 llvm::sys::Path::GetMainExecutable(Argv0,
1073 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001074 if (!MainExecutablePath.isEmpty()) {
1075 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1076 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001077
1078 // Get foo/lib/clang/1.0/include
1079 //
1080 // FIXME: Don't embed version here.
1081 MainExecutablePath.appendComponent("lib");
1082 MainExecutablePath.appendComponent("clang");
1083 MainExecutablePath.appendComponent("1.0");
1084 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001085
1086 // We pass true to ignore sysroot so that we *always* look for clang headers
1087 // relative to our executable, never relative to -isysroot.
1088 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1089 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001090 }
1091
Nico Weber770e3882008-08-22 09:25:22 +00001092 if (!nostdinc)
1093 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001094
1095 // Now that we have collected all of the include paths, merge them all
1096 // together and tell the preprocessor about them.
1097
Nico Weber770e3882008-08-22 09:25:22 +00001098 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001099}
1100
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001101//===----------------------------------------------------------------------===//
1102// Driver PreprocessorFactory - For lazily generating preprocessors ...
1103//===----------------------------------------------------------------------===//
1104
1105namespace {
1106class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001107 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001108 Diagnostic &Diags;
1109 const LangOptions &LangInfo;
1110 TargetInfo &Target;
1111 SourceManager &SourceMgr;
1112 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001113 bool InitializeSourceMgr;
1114
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001115public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001116 DriverPreprocessorFactory(const std::string &infile,
1117 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001118 TargetInfo &target, SourceManager &SM,
1119 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001120 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1121 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1122
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001123
1124 virtual ~DriverPreprocessorFactory() {}
1125
1126 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001127 llvm::OwningPtr<PTHManager> PTHMgr;
1128
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001129 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1130 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1131 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001132 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001133 }
1134
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001135 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001136 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1137 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001138 PTHMgr.reset(PTHManager::Create(x, &Diags,
1139 TokenCache.empty() ? Diagnostic::Error
1140 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001141 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001142
Ted Kremenek6348cc62009-03-22 06:42:39 +00001143 if (Diags.hasErrorOccurred())
1144 exit(1);
1145
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001146 // Create the Preprocessor.
1147 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1148 SourceMgr, HeaderInfo,
1149 PTHMgr.get()));
1150
1151 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1152 // That argument is used as the IdentifierInfoLookup argument to
1153 // IdentifierTable's ctor.
1154 if (PTHMgr) {
1155 PTHMgr->setPreprocessor(PP.get());
1156 PP->setPTHManager(PTHMgr.take());
1157 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001158
Chris Lattner9d818a22008-04-19 23:25:44 +00001159 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001160 return NULL;
1161 }
1162
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001163 /// FIXME: PP can only handle one callback
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001164 if (ProgAction != PrintPreprocessedInput) {
1165 std::string ErrStr;
1166 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1167 if (!DFG && !ErrStr.empty()) {
1168 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001169 return NULL;
1170 }
1171 }
1172
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001173 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001174 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001175 }
1176};
1177}
Chris Lattner4b009652007-07-25 00:24:17 +00001178
Chris Lattner4b009652007-07-25 00:24:17 +00001179//===----------------------------------------------------------------------===//
1180// Basic Parser driver
1181//===----------------------------------------------------------------------===//
1182
Chris Lattner9d818a22008-04-19 23:25:44 +00001183static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001184 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001185 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001186
1187 // Parsing the specified input file.
1188 P.ParseTranslationUnit();
1189 delete PA;
1190}
1191
1192//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001193// Code generation options
1194//===----------------------------------------------------------------------===//
1195
1196static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001197GenerateDebugInfo("g",
1198 llvm::cl::desc("Generate source level debug information"));
1199
1200static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001201OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001202
Chris Lattnerf04a7562009-03-26 05:00:52 +00001203static llvm::cl::opt<bool>
1204NoCommon("fno-common",
Mike Stumpf58df972009-03-27 20:15:22 +00001205 llvm::cl::desc("Compile common globals like normal definitions"),
Chris Lattner64c19972009-03-28 02:12:08 +00001206 llvm::cl::ValueDisallowed);
Chris Lattnerf04a7562009-03-26 05:00:52 +00001207
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001208// It might be nice to add bounds to the CommandLine library directly.
1209struct OptLevelParser : public llvm::cl::parser<unsigned> {
1210 bool parse(llvm::cl::Option &O, const char *ArgName,
1211 const std::string &Arg, unsigned &Val) {
1212 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1213 return true;
1214 // FIXME: Support -O4.
1215 if (Val > 3)
1216 return O.error(": '" + Arg + "' invalid optimization level!");
1217 return false;
1218 }
1219};
1220static llvm::cl::opt<unsigned, false, OptLevelParser>
1221OptLevel("O", llvm::cl::Prefix,
1222 llvm::cl::desc("Optimization level"),
1223 llvm::cl::init(0));
1224
Daniel Dunbar9101a632009-02-17 19:47:34 +00001225static llvm::cl::opt<std::string>
1226TargetCPU("mcpu",
1227 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1228
Chris Lattner8a9615c2009-03-16 18:41:18 +00001229static void InitializeCompileOptions(CompileOptions &Opts,
1230 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001231 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001232 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001233 if (OptSize) {
1234 // -Os implies -O2
1235 // FIXME: Diagnose conflicting options.
1236 Opts.OptimizationLevel = 2;
1237 } else {
1238 Opts.OptimizationLevel = OptLevel;
1239 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001240
1241 // FIXME: There are llvm-gcc options to control these selectively.
1242 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1243 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001244 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001245
1246#ifdef NDEBUG
1247 Opts.VerifyModule = 0;
1248#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001249
1250 Opts.CPU = TargetCPU;
1251 Opts.Features.insert(Opts.Features.end(),
1252 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001253
Chris Lattnerf04a7562009-03-26 05:00:52 +00001254 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1255
Chris Lattnere8f70712009-02-18 01:23:44 +00001256 // Handle -ftime-report.
1257 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001258}
1259
1260//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001261// Main driver
1262//===----------------------------------------------------------------------===//
1263
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001264/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001265/// action. These consumers can operate on both ASTs that are freshly
1266/// parsed from source files as well as those deserialized from Bitcode.
1267/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001268static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001269 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001270 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001271 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001272 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001273 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001274 default:
1275 return NULL;
1276
1277 case ASTPrint:
1278 return CreateASTPrinter();
1279
1280 case ASTDump:
1281 return CreateASTDumper();
1282
1283 case ASTView:
1284 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001285
Chris Lattner7f902922009-02-18 01:20:05 +00001286 case PrintDeclContext:
1287 return CreateDeclContextPrinter();
1288
1289 case EmitHTML:
1290 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001291
Chris Lattner7f902922009-02-18 01:20:05 +00001292 case InheritanceView:
1293 return CreateInheritanceViewer(InheritanceViewCls);
1294
1295 case TestSerialization:
1296 return CreateSerializationTest(Diag, FileMgr);
1297
1298 case EmitAssembly:
1299 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001300 case EmitBC:
1301 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001302 BackendAction Act;
1303 if (ProgAction == EmitAssembly)
1304 Act = Backend_EmitAssembly;
1305 else if (ProgAction == EmitLLVM)
1306 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001307 else if (ProgAction == EmitLLVMOnly)
1308 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001309 else
1310 Act = Backend_EmitBC;
1311
1312 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001313 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001314 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001315 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001316 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001317
Chris Lattner7f902922009-02-18 01:20:05 +00001318 case SerializeAST:
1319 // FIXME: Allow user to tailor where the file is written.
1320 return CreateASTSerializer(InFile, OutputFile, Diag);
1321
1322 case RewriteObjC:
1323 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001324
Chris Lattner7f902922009-02-18 01:20:05 +00001325 case RewriteBlocks:
1326 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1327
1328 case RunAnalysis:
1329 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001330 }
1331}
1332
Chris Lattner4b009652007-07-25 00:24:17 +00001333/// ProcessInputFile - Process a single input file with the specified state.
1334///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001335static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001336 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001337 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001338 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001339
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001340 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001341 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001342 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1343 PP.getFileManager(), PP.getLangOptions(),
1344 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001345
1346 if (!Consumer) {
1347 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001348 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001349 return;
1350 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001351
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001352 break;
1353
Chris Lattneraf669fb2008-10-12 05:03:36 +00001354 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001355 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001356 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001357 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001358 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001359 RawLex.SetKeepWhitespaceMode(true);
1360
1361 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001362 RawLex.LexFromRawLexer(RawTok);
1363 while (RawTok.isNot(tok::eof)) {
1364 PP.DumpToken(RawTok, true);
1365 fprintf(stderr, "\n");
1366 RawLex.LexFromRawLexer(RawTok);
1367 }
1368 ClearSourceMgr = true;
1369 break;
1370 }
Chris Lattner4b009652007-07-25 00:24:17 +00001371 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001372 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001373 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001374 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001375 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001376 do {
1377 PP.Lex(Tok);
1378 PP.DumpToken(Tok, true);
1379 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001380 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001381 ClearSourceMgr = true;
1382 break;
1383 }
1384 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001385 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001386 Token Tok;
1387 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001388 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001389 do {
1390 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001391 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001392 ClearSourceMgr = true;
1393 break;
1394 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001395
1396 case GeneratePCH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001397 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001398 CacheTokens(PP, OutputFile);
1399 ClearSourceMgr = true;
1400 break;
1401 }
Chris Lattner4b009652007-07-25 00:24:17 +00001402
Chris Lattnerefe33382009-02-18 01:51:21 +00001403 case PrintPreprocessedInput: { // -E mode.
1404 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001405 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001406 ClearSourceMgr = true;
1407 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001408 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001409
Chris Lattnerefe33382009-02-18 01:51:21 +00001410 case ParseNoop: { // -parse-noop
1411 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001412 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001413 ClearSourceMgr = true;
1414 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001415 }
Chris Lattner4b009652007-07-25 00:24:17 +00001416
Chris Lattnerefe33382009-02-18 01:51:21 +00001417 case ParsePrintCallbacks: {
1418 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001419 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001420 ClearSourceMgr = true;
1421 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001422 }
1423
1424 case ParseSyntaxOnly: { // -fsyntax-only
1425 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001426 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001427 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001428 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001429
1430 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001431 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001432 ClearSourceMgr = true;
1433 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001434
Chris Lattnerefe33382009-02-18 01:51:21 +00001435 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001436 DoRewriteTest(PP, InFile, OutputFile);
1437 ClearSourceMgr = true;
1438 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001439 }
Chris Lattnerefe33382009-02-18 01:51:21 +00001440 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001441
1442 if (Consumer) {
Chris Lattner143fd6d2009-03-28 01:37:17 +00001443 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner143fd6d2009-03-28 01:37:17 +00001444
1445 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1446 PP.getSourceManager(),
1447 PP.getTargetInfo(),
1448 PP.getIdentifierTable(),
1449 PP.getSelectorTable(),
1450 /* FreeMemory = */ !DisableFree));
Chris Lattner143fd6d2009-03-28 01:37:17 +00001451
1452
Chris Lattner07b08c02009-03-28 04:13:34 +00001453 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner143fd6d2009-03-28 01:37:17 +00001454
1455 // If in -disable-free mode, don't deallocate these when they go out of
1456 // scope.
Chris Lattner07b08c02009-03-28 04:13:34 +00001457 if (DisableFree)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001458 ContextOwner.take();
Ted Kremenek88eebed2009-01-28 04:29:29 +00001459 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001460
1461 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001462 if (CheckDiagnostics(PP))
1463 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001464
Chris Lattner4b009652007-07-25 00:24:17 +00001465 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001466 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001467 PP.PrintStats();
1468 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001469 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001470 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001471 fprintf(stderr, "\n");
1472 }
1473
1474 // For a multi-file compilation, some things are ok with nuking the source
1475 // manager tables, other require stable fileid/macroid's across multiple
1476 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001477 if (ClearSourceMgr)
1478 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001479
1480 if (DisableFree)
1481 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001482}
1483
Ted Kremenek80d53372007-12-12 23:41:08 +00001484static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1485 FileManager& FileMgr) {
1486
1487 if (VerifyDiagnostics) {
1488 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1489 exit (1);
1490 }
1491
1492 llvm::sys::Path Filename(InFile);
1493
1494 if (!Filename.isValid()) {
1495 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1496 exit (1);
1497 }
1498
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001499 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner06459ae2009-03-28 03:49:26 +00001500
1501 // Create the memory buffer that contains the contents of the file.
1502 llvm::OwningPtr<llvm::MemoryBuffer>
1503 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1504
1505 if (MBuffer)
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001506 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001507
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001508 if (!Ctx) {
Ted Kremenek2bd42412007-12-13 18:11:11 +00001509 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1510 InFile.c_str());
1511 exit (1);
1512 }
1513
Ted Kremenekab749372007-12-19 19:27:38 +00001514 // Observe that we use the source file name stored in the deserialized
1515 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001516 llvm::OwningPtr<ASTConsumer>
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001517 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001518 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001519
Ted Kremenek80d53372007-12-12 23:41:08 +00001520 if (!Consumer) {
1521 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1522 exit (1);
1523 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001524
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001525 Consumer->Initialize(*Ctx);
Nico Weberd2a6ac92008-08-10 19:59:06 +00001526
Chris Lattner8d72ee02008-02-06 01:42:25 +00001527 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001528 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1529 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1530 I != E; ++I)
Chris Lattnera17991f2009-03-29 16:50:03 +00001531 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek80d53372007-12-12 23:41:08 +00001532}
1533
1534
Chris Lattner4b009652007-07-25 00:24:17 +00001535static llvm::cl::list<std::string>
1536InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1537
Ted Kremenek80d53372007-12-12 23:41:08 +00001538static bool isSerializedFile(const std::string& InFile) {
1539 if (InFile.size() < 4)
1540 return false;
1541
1542 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00001543 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00001544}
1545
Chris Lattner4b009652007-07-25 00:24:17 +00001546
1547int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001548 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001549 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001550 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001551 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001552
Chris Lattnerefe33382009-02-18 01:51:21 +00001553 if (TimeReport)
1554 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1555
Chris Lattner4b009652007-07-25 00:24:17 +00001556 // If no input was specified, read from stdin.
1557 if (InputFilenames.empty())
1558 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001559
Chris Lattner4b009652007-07-25 00:24:17 +00001560 // Create a file manager object to provide access to and cache the filesystem.
1561 FileManager FileMgr;
1562
Ted Kremenekb240e822007-12-11 23:28:38 +00001563 // Create the diagnostic client for reporting errors or for
1564 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001565 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001566
Ted Kremenek5c341732008-08-07 17:49:57 +00001567 if (!VerifyDiagnostics) {
1568 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001569 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1570 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001571 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00001572 !NoShowLocation,
1573 PrintSourceRangeInfo);
Ted Kremenek5c341732008-08-07 17:49:57 +00001574 } else {
1575 // When checking diagnostics, just buffer them up.
1576 TextDiagClient = new TextDiagnosticBuffer();
1577
1578 if (InputFilenames.size() != 1) {
1579 fprintf(stderr,
1580 "-verify only works on single input files for now.\n");
1581 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001582 }
1583 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001584
Chris Lattner4b009652007-07-25 00:24:17 +00001585 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001586 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1587 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001588 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001589 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001590
Chris Lattner45a56e02007-12-05 23:24:17 +00001591 // -I- is a deprecated GCC feature, scan for it and reject it.
1592 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1593 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001594 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001595 I_dirs.erase(I_dirs.begin()+i);
1596 --i;
1597 }
1598 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001599
1600 // Get information about the target being compiled for.
1601 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001602 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1603
Chris Lattner2c77d852008-03-14 06:12:05 +00001604 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001605 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1606 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001607 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001608 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001609
Daniel Dunbar9c321102009-01-20 23:17:32 +00001610 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001611 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001612
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001613 llvm::OwningPtr<SourceManager> SourceMgr;
1614
Chris Lattner4b009652007-07-25 00:24:17 +00001615 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001616 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001617
Ted Kremenek5c341732008-08-07 17:49:57 +00001618 if (isSerializedFile(InFile)) {
1619 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001620 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00001621 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001622 }
Chris Lattner2b989562009-03-04 21:40:56 +00001623
1624 /// Create a SourceManager object. This tracks and owns all the file
1625 /// buffers allocated to a translation unit.
1626 if (!SourceMgr)
1627 SourceMgr.reset(new SourceManager());
1628 else
1629 SourceMgr->clearIDTables();
1630
1631 // Initialize language options, inferring file types from input filenames.
1632 LangOptions LangInfo;
1633 InitializeBaseLanguage();
1634 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001635 InitializeLangOptions(LangInfo, LK);
Chris Lattner2b989562009-03-04 21:40:56 +00001636 InitializeGCMode(LangInfo);
Mike Stumpdb789912009-04-01 20:28:16 +00001637 InitializeOverflowChecking(LangInfo);
Chris Lattner2b989562009-03-04 21:40:56 +00001638 InitializeLanguageStandard(LangInfo, LK, Target.get());
1639
1640 // Process the -I options and set them in the HeaderInfo.
1641 HeaderSearch HeaderInfo(FileMgr);
1642
1643 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1644
1645 // Set up the preprocessor with these options.
1646 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1647 *SourceMgr.get(), HeaderInfo);
1648
1649 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1650
1651 if (!PP)
1652 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001653
Chris Lattner2b989562009-03-04 21:40:56 +00001654 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1655 // always reset to using TextDiagClient.
1656 llvm::OwningPtr<DiagnosticClient> TmpClient;
1657
1658 if (!HTMLDiag.empty()) {
1659 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1660 &PPFactory));
1661 Diags.setClient(TmpClient.get());
Ted Kremenek80d53372007-12-12 23:41:08 +00001662 }
Chris Lattner2b989562009-03-04 21:40:56 +00001663 else
1664 Diags.setClient(TextDiagClient);
1665
1666 // Process the source file.
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001667 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattner2b989562009-03-04 21:40:56 +00001668
1669 HeaderInfo.ClearFileInfo();
Chris Lattner4b009652007-07-25 00:24:17 +00001670 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001671
Mike Stump91d01352009-01-28 02:43:35 +00001672 if (Verbose)
1673 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1674 " hosted on " LLVM_HOSTTRIPLE "\n");
1675
Ted Kremenekec6c5252008-08-07 18:13:12 +00001676 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001677 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1678 (NumDiagnostics == 1 ? "" : "s"));
1679
1680 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001681 FileMgr.PrintStats();
1682 fprintf(stderr, "\n");
1683 }
1684
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001685 // If verifying diagnostics and we reached here, all is well.
1686 if (VerifyDiagnostics)
1687 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001688
1689 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001690
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001691 // Managed static deconstruction. Useful for making things like
1692 // -time-passes usable.
1693 llvm::llvm_shutdown();
1694
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001695 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001696}