blob: adfc8602fdb9c2187ebb3851ca79cde3ea1bfe87 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattner39fb14e2009-02-18 01:17:01 +000020// -Wfatal-errors
Chris Lattner4b009652007-07-25 00:24:17 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
28#include "clang/Frontend/PathDiagnosticClients.h"
29#include "clang/Frontend/InitHeaderSearch.h"
30#include "clang/Frontend/TextDiagnosticBuffer.h"
31#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000032#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000033#include "clang/AST/Decl.h"
Ted Kremenekac881932007-12-18 21:34:28 +000034#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000039#include "clang/Parse/Parser.h"
40#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000041#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000042#include "clang/Basic/FileManager.h"
43#include "clang/Basic/SourceManager.h"
44#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000045#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000046#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000049#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000050#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000051#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000052#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000053#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000054#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000055#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000056#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000057#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000058using namespace clang;
59
60//===----------------------------------------------------------------------===//
61// Global options.
62//===----------------------------------------------------------------------===//
63
Chris Lattnerefe33382009-02-18 01:51:21 +000064/// ClangFrontendTimer - The front-end activities should charge time to it with
65/// TimeRegion. The -ftime-report option controls whether this will do
66/// anything.
67llvm::Timer *ClangFrontendTimer = 0;
68
Daniel Dunbar4efedde2008-10-16 16:54:18 +000069static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000070
Chris Lattner4b009652007-07-25 00:24:17 +000071static llvm::cl::opt<bool>
72Verbose("v", llvm::cl::desc("Enable verbose output"));
73static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000074Stats("print-stats",
75 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000076static llvm::cl::opt<bool>
77DisableFree("disable-free",
78 llvm::cl::desc("Disable freeing of memory on exit"),
79 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000080
81enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000082 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000083 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000084 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000085 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000086 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000087 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000088 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000089 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +000090 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek397de012007-12-13 00:37:31 +000091 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000092 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000093 ASTPrint, // Parse ASTs and print them.
94 ASTDump, // Parse ASTs and dump them.
95 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000096 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000097 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000098 ParsePrintCallbacks, // Parse and print each callback.
99 ParseSyntaxOnly, // Parse and perform semantic analysis.
100 ParseNoop, // Parse with noop callbacks.
101 RunPreprocessorOnly, // Just lex, no output.
102 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000103 DumpTokens, // Dump out preprocessed tokens.
104 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000105 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000106 GeneratePCH, // Generate precompiled header.
107 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000108};
109
110static llvm::cl::opt<ProgActions>
111ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
112 llvm::cl::init(ParseSyntaxOnly),
113 llvm::cl::values(
114 clEnumValN(RunPreprocessorOnly, "Eonly",
115 "Just run preprocessor, no output (for timings)"),
116 clEnumValN(PrintPreprocessedInput, "E",
117 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000118 clEnumValN(DumpRawTokens, "dump-raw-tokens",
119 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000120 clEnumValN(RunAnalysis, "analyze",
121 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000122 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000123 "Run preprocessor, dump internal rep of tokens"),
124 clEnumValN(ParseNoop, "parse-noop",
125 "Run parser with noop callbacks (for timings)"),
126 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
127 "Run parser and perform semantic analysis"),
128 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
129 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000130 clEnumValN(EmitHTML, "emit-html",
131 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000132 clEnumValN(ASTPrint, "ast-print",
133 "Build ASTs and then pretty-print them"),
134 clEnumValN(ASTDump, "ast-dump",
135 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000136 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000137 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000138 clEnumValN(PrintDeclContext, "print-decl-contexts",
139 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000140 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000141 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000142 clEnumValN(EmitAssembly, "S",
143 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000144 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000145 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000146 clEnumValN(EmitBC, "emit-llvm-bc",
147 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000148 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
149 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000150 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000151 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000152 clEnumValN(RewriteTest, "rewrite-test",
153 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000154 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000155 "Rewrite ObjC into C (code rewriter example)"),
156 clEnumValN(RewriteMacros, "rewrite-macros",
157 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000158 clEnumValN(RewriteBlocks, "rewrite-blocks",
159 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000160 clEnumValEnd));
161
Ted Kremenekd01eae62007-12-19 19:47:59 +0000162
163static llvm::cl::opt<std::string>
164OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000165 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000166 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000167
168//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000169// Code Generator Options
170//===----------------------------------------------------------------------===//
171static llvm::cl::opt<bool>
172GenerateDebugInfo("g",
173 llvm::cl::desc("Generate source level debug information"));
174
Ted Kremenek57f25b22008-12-02 19:57:31 +0000175
176//===----------------------------------------------------------------------===//
177// PTH.
178//===----------------------------------------------------------------------===//
179
180static llvm::cl::opt<std::string>
181TokenCache("token-cache", llvm::cl::value_desc("path"),
182 llvm::cl::desc("Use specified token cache file"));
183
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000184//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000185// Diagnostic Options
186//===----------------------------------------------------------------------===//
187
Ted Kremenek10389cf2007-09-26 19:42:19 +0000188static llvm::cl::opt<bool>
189VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000190 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000191
Ted Kremenekfd75e312008-03-27 06:17:42 +0000192static llvm::cl::opt<std::string>
193HTMLDiag("html-diags",
194 llvm::cl::desc("Generate HTML to report diagnostics"),
195 llvm::cl::value_desc("HTML directory"));
196
Nico Weber0e13eaa2008-08-05 23:33:20 +0000197static llvm::cl::opt<bool>
198NoShowColumn("fno-show-column",
199 llvm::cl::desc("Do not include column number on diagnostics"));
200
201static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000202NoShowLocation("fno-show-source-location",
203 llvm::cl::desc("Do not include source location information with"
204 " diagnostics"));
205
206static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000207NoCaretDiagnostics("fno-caret-diagnostics",
208 llvm::cl::desc("Do not include source line and caret with"
209 " diagnostics"));
210
211
Chris Lattner4b009652007-07-25 00:24:17 +0000212//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000213// C++ Visualization.
214//===----------------------------------------------------------------------===//
215
216static llvm::cl::opt<std::string>
217InheritanceViewCls("cxx-inheritance-view",
218 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000219 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000220
221//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000222// Builtin Options
223//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000224
225static llvm::cl::opt<bool>
226TimeReport("ftime-report",
227 llvm::cl::desc("Print the amount of time each "
228 "phase of compilation takes"));
229
Douglas Gregor23d23262009-02-14 20:49:29 +0000230static llvm::cl::opt<bool>
231Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000232 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000233 "freestanding environment"));
234
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000235static llvm::cl::opt<bool>
236MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000237 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000238 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000239
Douglas Gregor23d23262009-02-14 20:49:29 +0000240//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000241// Language Options
242//===----------------------------------------------------------------------===//
243
244enum LangKind {
245 langkind_unspecified,
246 langkind_c,
247 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000248 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000249 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000250 langkind_cxx,
251 langkind_cxx_cpp,
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000252 langkind_cxx_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000253 langkind_objc,
254 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000255 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000256 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000257 langkind_objcxx_cpp,
258 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000259};
260
Chris Lattner4b009652007-07-25 00:24:17 +0000261static llvm::cl::opt<LangKind>
262BaseLang("x", llvm::cl::desc("Base language to compile"),
263 llvm::cl::init(langkind_unspecified),
264 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
265 clEnumValN(langkind_cxx, "c++", "C++"),
266 clEnumValN(langkind_objc, "objective-c", "Objective C"),
267 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000268 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000269 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000270 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
271 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000272 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000273 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000274 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
275 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000276 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000277 "Preprocessed Objective C++"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000278 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000279 "Precompiled C header"),
280 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000281 "Precompiled Objective-C header"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000282 clEnumValN(langkind_cxx_pch, "c++-header",
283 "Precompiled C++ header"),
Ted Kremenekceacc812009-01-09 00:38:08 +0000284 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
285 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000286 clEnumValEnd));
287
288static llvm::cl::opt<bool>
289LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
290 llvm::cl::Hidden);
291static llvm::cl::opt<bool>
292LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
293 llvm::cl::Hidden);
294
Ted Kremenek11ad8952007-12-05 23:49:08 +0000295/// InitializeBaseLanguage - Handle the -x foo options.
296static void InitializeBaseLanguage() {
297 if (LangObjC)
298 BaseLang = langkind_objc;
299 else if (LangObjCXX)
300 BaseLang = langkind_objcxx;
301}
302
303static LangKind GetLanguage(const std::string &Filename) {
304 if (BaseLang != langkind_unspecified)
305 return BaseLang;
306
307 std::string::size_type DotPos = Filename.rfind('.');
308
309 if (DotPos == std::string::npos) {
310 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000311 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000312 }
313
Ted Kremenek11ad8952007-12-05 23:49:08 +0000314 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
315 // C header: .h
316 // C++ header: .hh or .H;
317 // assembler no preprocessing: .s
318 // assembler: .S
319 if (Ext == "c")
320 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000321 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000322 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000323 else if (Ext == "i")
324 return langkind_c_cpp;
325 else if (Ext == "ii")
326 return langkind_cxx_cpp;
327 else if (Ext == "m")
328 return langkind_objc;
329 else if (Ext == "mi")
330 return langkind_objc_cpp;
331 else if (Ext == "mm" || Ext == "M")
332 return langkind_objcxx;
333 else if (Ext == "mii")
334 return langkind_objcxx_cpp;
335 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
336 Ext == "c++" || Ext == "cp" || Ext == "cxx")
337 return langkind_cxx;
338 else
339 return langkind_c;
340}
341
342
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000343static void InitializeCOptions(LangOptions &Options) {
344 // Do nothing.
345}
346
347static void InitializeObjCOptions(LangOptions &Options) {
348 Options.ObjC1 = Options.ObjC2 = 1;
349}
350
351
352static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000353 // FIXME: implement -fpreprocessed mode.
354 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000355 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000356
357 // Test for 'PCH'.
358 switch (LK) {
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000359 default:
360 break;
361 case langkind_c_pch:
362 LK = langkind_c;
363 PCH = true;
364 break;
365 case langkind_objc_pch:
366 LK = langkind_objc;
367 PCH = true;
368 break;
369 case langkind_cxx_pch:
370 LK = langkind_cxx;
371 PCH = true;
372 break;
373 case langkind_objcxx_pch:
374 LK = langkind_objcxx;
375 PCH = true;
376 break;
Ted Kremenekceacc812009-01-09 00:38:08 +0000377 }
Chris Lattner4b009652007-07-25 00:24:17 +0000378
Ted Kremenek11ad8952007-12-05 23:49:08 +0000379 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000380 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000381 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000382 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000383 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000384 case langkind_c_cpp:
385 NoPreprocess = true;
386 // FALLTHROUGH
387 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000388 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000389 break;
390 case langkind_cxx_cpp:
391 NoPreprocess = true;
392 // FALLTHROUGH
393 case langkind_cxx:
394 Options.CPlusPlus = 1;
395 break;
396 case langkind_objc_cpp:
397 NoPreprocess = true;
398 // FALLTHROUGH
399 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000400 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000401 break;
402 case langkind_objcxx_cpp:
403 NoPreprocess = true;
404 // FALLTHROUGH
405 case langkind_objcxx:
406 Options.ObjC1 = Options.ObjC2 = 1;
407 Options.CPlusPlus = 1;
408 break;
409 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000410
411 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000412}
413
414/// LangStds - Language standards we support.
415enum LangStds {
416 lang_unspecified,
417 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000418 lang_gnu_START,
419 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000420 lang_cxx98, lang_gnucxx98,
421 lang_cxx0x, lang_gnucxx0x
422};
423
424static llvm::cl::opt<LangStds>
425LangStd("std", llvm::cl::desc("Language standard to compile for"),
426 llvm::cl::init(lang_unspecified),
427 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
428 clEnumValN(lang_c89, "c90", "ISO C 1990"),
429 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
430 clEnumValN(lang_c94, "iso9899:199409",
431 "ISO C 1990 with amendment 1"),
432 clEnumValN(lang_c99, "c99", "ISO C 1999"),
433// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
434 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
435// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
436 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000437 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000438 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000439 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000440 clEnumValN(lang_gnu99, "gnu9x",
441 "ISO C 1999 with GNU extensions"),
442 clEnumValN(lang_cxx98, "c++98",
443 "ISO C++ 1998 with amendments"),
444 clEnumValN(lang_gnucxx98, "gnu++98",
445 "ISO C++ 1998 with amendments and GNU "
446 "extensions (default for C++)"),
447 clEnumValN(lang_cxx0x, "c++0x",
448 "Upcoming ISO C++ 200x with amendments"),
449 clEnumValN(lang_gnucxx0x, "gnu++0x",
450 "Upcoming ISO C++ 200x with amendments and GNU "
451 "extensions (default for C++)"),
452 clEnumValEnd));
453
454static llvm::cl::opt<bool>
455NoOperatorNames("fno-operator-names",
456 llvm::cl::desc("Do not treat C++ operator name keywords as "
457 "synonyms for operators"));
458
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000459static llvm::cl::opt<bool>
460PascalStrings("fpascal-strings",
461 llvm::cl::desc("Recognize and construct Pascal-style "
462 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000463
464static llvm::cl::opt<bool>
465MSExtensions("fms-extensions",
466 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000467 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000468
469static llvm::cl::opt<bool>
470WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000471 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000472
473static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000474NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000475 llvm::cl::desc("Disallow implicit conversions between "
476 "vectors with a different number of "
477 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000478
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000479static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000480EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
481 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
482 llvm::cl::ZeroOrMore);
483
484static llvm::cl::opt<bool>
485ObjCNonFragileABI("fobjc-nonfragile-abi",
486 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000487
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000488static llvm::cl::opt<bool>
489EmitAllDecls("femit-all-decls",
490 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000491
Daniel Dunbar91692d92008-08-11 17:36:14 +0000492// FIXME: This (and all GCC -f options) really come in -f... and
493// -fno-... forms, and additionally support automagic behavior when
494// they are not defined. For example, -fexceptions defaults to on or
495// off depending on the language. We should support this behavior in
496// some form (perhaps just add a facility for distinguishing when an
497// has its default value from when it has been set to its default
498// value).
499static llvm::cl::opt<bool>
500Exceptions("fexceptions",
501 llvm::cl::desc("Enable support for exception handling."));
502
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000503static llvm::cl::opt<bool>
504GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000505 llvm::cl::desc("Generate output compatible with the standard GNU "
506 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000507
508static llvm::cl::opt<bool>
509NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000510 llvm::cl::desc("Generate output compatible with the NeXT "
511 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000512
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000513
514
515static llvm::cl::opt<bool>
516Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
517
518static llvm::cl::opt<bool>
519Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
520
Chris Lattner738d3f62009-03-02 22:11:07 +0000521static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000522TargetFeatures("mattr", llvm::cl::CommaSeparated,
523 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
524
Chris Lattner738d3f62009-03-02 22:11:07 +0000525
526
Chris Lattner4b009652007-07-25 00:24:17 +0000527// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000528// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000529static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
530 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000531 // Allow the target to set the default the langauge options as it sees fit.
532 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000533
Chris Lattnerf6790a82009-03-03 19:56:18 +0000534 // If there are any -mattr options, pass them to the target for validation and
535 // processing. The driver should have already consolidated all the
536 // target-feature settings and passed them to us in the -mattr list. The
537 // -mattr list is treated by the code generator as a diff against the -mcpu
538 // setting, but the driver should pass all enabled options as "+" settings.
539 // This means that the target should only look at + settings.
540 if (!TargetFeatures.empty()
541 // FIXME: The driver is not quite yet ready for this.
542 && 0) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000543 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000544 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
545 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000546 if (Opt != -1) {
547 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000548 fprintf(stderr, "invalid feature '%s'\n",
549 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000550 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000551 fprintf(stderr, "feature '%s': %s\n",
552 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000553 exit(1);
554 }
555 }
556
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000557 if (Ansi) // "The -ansi option is equivalent to -std=c89."
558 LangStd = lang_c89;
559
Chris Lattner4b009652007-07-25 00:24:17 +0000560 if (LangStd == lang_unspecified) {
561 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000562 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000563 default: assert(0 && "Unknown base language");
564 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000565 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000566 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000567 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000568 case langkind_objc:
569 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000570 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000571 LangStd = lang_gnu99;
572 break;
573 case langkind_cxx:
574 case langkind_cxx_cpp:
575 case langkind_objcxx:
576 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000577 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000578 LangStd = lang_gnucxx98;
579 break;
580 }
581 }
582
583 switch (LangStd) {
584 default: assert(0 && "Unknown language standard!");
585
586 // Fall through from newer standards to older ones. This isn't really right.
587 // FIXME: Enable specifically the right features based on the language stds.
588 case lang_gnucxx0x:
589 case lang_cxx0x:
590 Options.CPlusPlus0x = 1;
591 // FALL THROUGH
592 case lang_gnucxx98:
593 case lang_cxx98:
594 Options.CPlusPlus = 1;
595 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000596 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000597 // FALL THROUGH.
598 case lang_gnu99:
599 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000600 Options.C99 = 1;
601 Options.HexFloats = 1;
602 // FALL THROUGH.
603 case lang_gnu89:
604 Options.BCPLComment = 1; // Only for C99/C++.
605 // FALL THROUGH.
606 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000607 Options.Digraphs = 1; // C94, C99, C++.
608 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000609 case lang_c89:
610 break;
611 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000612
613 if (Options.CPlusPlus) {
614 Options.C99 = 0;
615 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
616 }
Chris Lattner4b009652007-07-25 00:24:17 +0000617
Chris Lattner6ab935b2008-04-05 06:32:51 +0000618 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
619 Options.ImplicitInt = 1;
620 else
621 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000622
623 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
624 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000625 Options.Trigraphs = LangStd < lang_gnu_START;
626 if (Trigraphs.getPosition())
627 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000628
Chris Lattner58d5ba52008-12-05 00:10:44 +0000629 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
630 // even if they are normally on for the target. In GNU modes (e.g.
631 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000632 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
633 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000634 Options.Blocks = 0;
635
Chris Lattner4b009652007-07-25 00:24:17 +0000636 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000637 if (PascalStrings.getPosition())
638 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000639 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000640 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000641 if (NoLaxVectorConversions.getPosition())
642 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000643 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000644 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000645 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000646
Douglas Gregor23d23262009-02-14 20:49:29 +0000647 if (Freestanding)
648 Options.Freestanding = 1;
649
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000650 Options.MathErrno = MathErrno;
651
Chris Lattnerddae7102008-12-04 22:54:33 +0000652 // Override the default runtime if the user requested it.
653 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000654 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000655 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000656 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000657
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000658 if (ObjCNonFragileABI)
659 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000660
661 if (EmitAllDecls)
662 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000663}
664
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000665static llvm::cl::opt<bool>
666ObjCExclusiveGC("fobjc-gc-only",
667 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000668 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000669
670static llvm::cl::opt<bool>
671ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000672 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000673
674void InitializeGCMode(LangOptions &Options) {
675 if (ObjCExclusiveGC)
676 Options.setGCMode(LangOptions::GCOnly);
677 else if (ObjCEnableGC)
678 Options.setGCMode(LangOptions::HybridGC);
679}
680
Chris Lattner4b009652007-07-25 00:24:17 +0000681//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000682// Target Triple Processing.
683//===----------------------------------------------------------------------===//
684
685static llvm::cl::opt<std::string>
686TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000687 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000688
Chris Lattnerfc457002008-03-05 01:18:20 +0000689static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000690Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000691
Chris Lattner2b168e02008-09-30 01:13:12 +0000692static llvm::cl::opt<std::string>
693MacOSVersionMin("mmacosx-version-min",
694 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
695
Chris Lattner01de9c82008-09-30 20:16:56 +0000696// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
697// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
698static void HandleMacOSVersionMin(std::string &Triple) {
699 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
700 if (DarwinDashIdx == std::string::npos) {
701 fprintf(stderr,
702 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
703 exit(1);
704 }
705 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
706
Chris Lattner01de9c82008-09-30 20:16:56 +0000707 // Remove the number.
708 Triple.resize(DarwinNumIdx);
709
710 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
711 bool MacOSVersionMinIsInvalid = false;
712 int VersionNum = 0;
713 if (MacOSVersionMin.size() < 4 ||
714 MacOSVersionMin.substr(0, 3) != "10." ||
715 !isdigit(MacOSVersionMin[3])) {
716 MacOSVersionMinIsInvalid = true;
717 } else {
718 const char *Start = MacOSVersionMin.c_str()+3;
719 char *End = 0;
720 VersionNum = (int)strtol(Start, &End, 10);
721
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000722 // The version number must be in the range 0-9.
723 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
724
Chris Lattner01de9c82008-09-30 20:16:56 +0000725 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
726 Triple += llvm::itostr(VersionNum+4);
727
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000728 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
729 // Add the period piece (.7) to the end of the triple. This gives us
730 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000731 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000732 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
733 MacOSVersionMinIsInvalid = true;
734 }
735 }
736
737 if (MacOSVersionMinIsInvalid) {
738 fprintf(stderr,
739 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
740 MacOSVersionMin.c_str());
741 exit(1);
742 }
743}
744
745/// CreateTargetTriple - Process the various options that affect the target
746/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000747static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000748 // Initialize base triple. If a -triple option has been specified, use
749 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000750 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000751 if (Triple.empty()) {
752 Triple = LLVM_HOSTTRIPLE;
753
Daniel Dunbar81caece2008-12-12 18:34:35 +0000754 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
755 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
756 Triple[2] == '8' && Triple[3] == '6')
757 Triple[1] = '3';
758
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000759 // On darwin, we want to update the version to match that of the
760 // host.
761 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
762 if (DarwinDashIdx != std::string::npos) {
763 Triple.resize(DarwinDashIdx + strlen("-darwin"));
764
Daniel Dunbar81caece2008-12-12 18:34:35 +0000765 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000766 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000767 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000768 }
769 }
Ted Kremenek40499482007-12-03 22:06:55 +0000770
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000771 // If -arch foo was specified, remove the architecture from the triple we have
772 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000773 if (!Arch.empty()) {
774 // Decompose the base triple into "arch" and suffix.
775 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000776
Chris Lattner2b168e02008-09-30 01:13:12 +0000777 if (FirstDashIdx == std::string::npos) {
778 fprintf(stderr,
779 "Malformed target triple: \"%s\" ('-' could not be found).\n",
780 Triple.c_str());
781 exit(1);
782 }
Ted Kremenek40499482007-12-03 22:06:55 +0000783
Chris Lattner2b168e02008-09-30 01:13:12 +0000784 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
785 }
786
787 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
788 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000789 if (!MacOSVersionMin.empty())
790 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000791
Chris Lattner2b168e02008-09-30 01:13:12 +0000792 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000793}
794
795//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000796// Preprocessor Initialization
797//===----------------------------------------------------------------------===//
798
799// FIXME: Preprocessor builtins to support.
800// -A... - Play with #assertions
801// -undef - Undefine all predefined macros
802
803static 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
814
Chris Lattner4b009652007-07-25 00:24:17 +0000815// Append a #define line to Buf for Macro. Macro should be of the form XXX,
816// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
817// "#define XXX Y z W". To get a #define with no value, use "XXX=".
818static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
819 const char *Command = "#define ") {
820 Buf.insert(Buf.end(), Command, Command+strlen(Command));
821 if (const char *Equal = strchr(Macro, '=')) {
822 // Turn the = into ' '.
823 Buf.insert(Buf.end(), Macro, Equal);
824 Buf.push_back(' ');
825 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
826 } else {
827 // Push "macroname 1".
828 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
829 Buf.push_back(' ');
830 Buf.push_back('1');
831 }
832 Buf.push_back('\n');
833}
834
Chris Lattner008da782008-01-10 01:53:41 +0000835/// AddImplicitInclude - Add an implicit #include of the specified file to the
836/// predefines buffer.
837static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
838 const char *Inc = "#include \"";
839 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
840 Buf.insert(Buf.end(), File.begin(), File.end());
841 Buf.push_back('"');
842 Buf.push_back('\n');
843}
844
Chris Lattner4b009652007-07-25 00:24:17 +0000845
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000846/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000847/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000848///
Chris Lattner9d818a22008-04-19 23:25:44 +0000849static bool InitializePreprocessor(Preprocessor &PP,
850 bool InitializeSourceMgr,
851 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000852 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000853
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000854 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000855 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000856
857 if (InitializeSourceMgr) {
858 if (InFile != "-") {
859 const FileEntry *File = FileMgr.getFile(InFile);
860 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000861 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000862 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000863 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000864 }
865 } else {
866 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
867 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000868 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000869 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000870 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000871 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000872 }
Chris Lattner4b009652007-07-25 00:24:17 +0000873 }
Sam Bishop61a20782008-04-14 14:41:57 +0000874
Chris Lattner47b6a162008-04-19 23:09:31 +0000875 std::vector<char> PredefineBuffer;
876
Chris Lattner4b009652007-07-25 00:24:17 +0000877 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000878 unsigned d = 0, D = D_macros.size();
879 unsigned u = 0, U = U_macros.size();
880 while (d < D || u < U) {
881 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
882 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
883 else
884 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
885 }
886
Chris Lattner008da782008-01-10 01:53:41 +0000887 // FIXME: Read any files specified by -imacros.
888
889 // Add implicit #includes from -include.
890 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
891 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000892
Chris Lattner47b6a162008-04-19 23:09:31 +0000893 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000894 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000895 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000896
897 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000898 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000899}
900
901//===----------------------------------------------------------------------===//
902// Preprocessor include path information.
903//===----------------------------------------------------------------------===//
904
905// This tool exports a large number of command line options to control how the
906// preprocessor searches for header files. At root, however, the Preprocessor
907// object takes a very simple interface: a list of directories to search for
908//
909// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000910// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000911//
Chris Lattner008da782008-01-10 01:53:41 +0000912// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000913
914static llvm::cl::opt<bool>
915nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
916
917// Various command line options. These four add directories to each chain.
918static llvm::cl::list<std::string>
919F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
920 llvm::cl::desc("Add directory to framework include search path"));
921static llvm::cl::list<std::string>
922I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
923 llvm::cl::desc("Add directory to include search path"));
924static llvm::cl::list<std::string>
925idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
926 llvm::cl::desc("Add directory to AFTER include search path"));
927static llvm::cl::list<std::string>
928iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
929 llvm::cl::desc("Add directory to QUOTE include search path"));
930static llvm::cl::list<std::string>
931isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
932 llvm::cl::desc("Add directory to SYSTEM include search path"));
933
934// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
935static llvm::cl::list<std::string>
936iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
937 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
938static llvm::cl::list<std::string>
939iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
940 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
941static llvm::cl::list<std::string>
942iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
943 llvm::cl::Prefix,
944 llvm::cl::desc("Set directory to include search path with prefix"));
945
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000946static llvm::cl::opt<std::string>
947isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
948 llvm::cl::desc("Set the system root directory (usually /)"));
949
Chris Lattner4b009652007-07-25 00:24:17 +0000950// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +0000951
Chris Lattner4b009652007-07-25 00:24:17 +0000952/// InitializeIncludePaths - Process the -I options and set them in the
953/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +0000954void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
955 FileManager &FM, const LangOptions &Lang) {
956 InitHeaderSearch Init(Headers, Verbose, isysroot);
957
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000958 // Handle -I... and -F... options, walking the lists in parallel.
959 unsigned Iidx = 0, Fidx = 0;
960 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
961 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +0000962 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000963 ++Iidx;
964 } else {
Nico Weber770e3882008-08-22 09:25:22 +0000965 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000966 ++Fidx;
967 }
968 }
Chris Lattner4b009652007-07-25 00:24:17 +0000969
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000970 // Consume what's left from whatever list was longer.
971 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +0000972 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000973 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +0000974 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000975
976 // Handle -idirafter... options.
977 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000978 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
979 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000980
981 // Handle -iquote... options.
982 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000983 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000984
985 // Handle -isystem... options.
986 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000987 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000988
989 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
990 // parallel, processing the values in order of occurance to get the right
991 // prefixes.
992 {
993 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
994 unsigned iprefix_idx = 0;
995 unsigned iwithprefix_idx = 0;
996 unsigned iwithprefixbefore_idx = 0;
997 bool iprefix_done = iprefix_vals.empty();
998 bool iwithprefix_done = iwithprefix_vals.empty();
999 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1000 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1001 if (!iprefix_done &&
1002 (iwithprefix_done ||
1003 iprefix_vals.getPosition(iprefix_idx) <
1004 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1005 (iwithprefixbefore_done ||
1006 iprefix_vals.getPosition(iprefix_idx) <
1007 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1008 Prefix = iprefix_vals[iprefix_idx];
1009 ++iprefix_idx;
1010 iprefix_done = iprefix_idx == iprefix_vals.size();
1011 } else if (!iwithprefix_done &&
1012 (iwithprefixbefore_done ||
1013 iwithprefix_vals.getPosition(iwithprefix_idx) <
1014 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001015 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1016 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001017 ++iwithprefix_idx;
1018 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1019 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001020 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1021 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001022 ++iwithprefixbefore_idx;
1023 iwithprefixbefore_done =
1024 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1025 }
1026 }
1027 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001028
Nico Weber770e3882008-08-22 09:25:22 +00001029 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001030
Daniel Dunbar4e604292009-02-21 20:52:41 +00001031 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001032 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001033 llvm::sys::Path::GetMainExecutable(Argv0,
1034 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001035 if (!MainExecutablePath.isEmpty()) {
1036 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1037 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001038
1039 // Get foo/lib/clang/1.0/include
1040 //
1041 // FIXME: Don't embed version here.
1042 MainExecutablePath.appendComponent("lib");
1043 MainExecutablePath.appendComponent("clang");
1044 MainExecutablePath.appendComponent("1.0");
1045 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001046
1047 // We pass true to ignore sysroot so that we *always* look for clang headers
1048 // relative to our executable, never relative to -isysroot.
1049 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1050 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001051 }
1052
Nico Weber770e3882008-08-22 09:25:22 +00001053 if (!nostdinc)
1054 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001055
1056 // Now that we have collected all of the include paths, merge them all
1057 // together and tell the preprocessor about them.
1058
Nico Weber770e3882008-08-22 09:25:22 +00001059 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001060}
1061
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001062//===----------------------------------------------------------------------===//
1063// Driver PreprocessorFactory - For lazily generating preprocessors ...
1064//===----------------------------------------------------------------------===//
1065
1066namespace {
1067class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001068 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001069 Diagnostic &Diags;
1070 const LangOptions &LangInfo;
1071 TargetInfo &Target;
1072 SourceManager &SourceMgr;
1073 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001074 bool InitializeSourceMgr;
1075
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001076public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001077 DriverPreprocessorFactory(const std::string &infile,
1078 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001079 TargetInfo &target, SourceManager &SM,
1080 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001081 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1082 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1083
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001084
1085 virtual ~DriverPreprocessorFactory() {}
1086
1087 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001088 llvm::OwningPtr<PTHManager> PTHMgr;
1089
1090 // Use PTH?
1091 if (!TokenCache.empty())
Ted Kremenek3d145552009-01-28 20:49:33 +00001092 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001093
1094 // Create the Preprocessor.
1095 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1096 SourceMgr, HeaderInfo,
1097 PTHMgr.get()));
1098
1099 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1100 // That argument is used as the IdentifierInfoLookup argument to
1101 // IdentifierTable's ctor.
1102 if (PTHMgr) {
1103 PTHMgr->setPreprocessor(PP.get());
1104 PP->setPTHManager(PTHMgr.take());
1105 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001106
Chris Lattner9d818a22008-04-19 23:25:44 +00001107 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001108 return NULL;
1109 }
1110
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001111 /// FIXME: PP can only handle one callback
1112 if (ProgAction != PrintPreprocessedInput) {
1113 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001114 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001115 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001116 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001117 return NULL;
1118 }
1119 }
1120
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001121 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001122 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001123 }
1124};
1125}
Chris Lattner4b009652007-07-25 00:24:17 +00001126
Chris Lattner4b009652007-07-25 00:24:17 +00001127//===----------------------------------------------------------------------===//
1128// Basic Parser driver
1129//===----------------------------------------------------------------------===//
1130
Chris Lattner9d818a22008-04-19 23:25:44 +00001131static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001132 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001133 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001134
1135 // Parsing the specified input file.
1136 P.ParseTranslationUnit();
1137 delete PA;
1138}
1139
1140//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001141// Code generation options
1142//===----------------------------------------------------------------------===//
1143
1144static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001145OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001146
1147// It might be nice to add bounds to the CommandLine library directly.
1148struct OptLevelParser : public llvm::cl::parser<unsigned> {
1149 bool parse(llvm::cl::Option &O, const char *ArgName,
1150 const std::string &Arg, unsigned &Val) {
1151 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1152 return true;
1153 // FIXME: Support -O4.
1154 if (Val > 3)
1155 return O.error(": '" + Arg + "' invalid optimization level!");
1156 return false;
1157 }
1158};
1159static llvm::cl::opt<unsigned, false, OptLevelParser>
1160OptLevel("O", llvm::cl::Prefix,
1161 llvm::cl::desc("Optimization level"),
1162 llvm::cl::init(0));
1163
Daniel Dunbar9101a632009-02-17 19:47:34 +00001164static llvm::cl::opt<std::string>
1165TargetCPU("mcpu",
1166 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1167
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001168static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001169 Opts.OptimizeSize = OptSize;
Daniel Dunbard725b162008-10-29 07:56:11 +00001170 if (OptSize) {
1171 // -Os implies -O2
1172 // FIXME: Diagnose conflicting options.
1173 Opts.OptimizationLevel = 2;
1174 } else {
1175 Opts.OptimizationLevel = OptLevel;
1176 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001177
1178 // FIXME: There are llvm-gcc options to control these selectively.
1179 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1180 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Daniel Dunbar6670e332009-02-15 20:00:15 +00001181 Opts.SimplifyLibCalls = !Freestanding;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001182
1183#ifdef NDEBUG
1184 Opts.VerifyModule = 0;
1185#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001186
1187 Opts.CPU = TargetCPU;
1188 Opts.Features.insert(Opts.Features.end(),
1189 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001190
1191 // Handle -ftime-report.
1192 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001193}
1194
1195//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001196// Main driver
1197//===----------------------------------------------------------------------===//
1198
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001199/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1200/// action. These consumers can operate on both ASTs that are freshly
1201/// parsed from source files as well as those deserialized from Bitcode.
Chris Lattner7f902922009-02-18 01:20:05 +00001202static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001203 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001204 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001205 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001206 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001207 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001208 default:
1209 return NULL;
1210
1211 case ASTPrint:
1212 return CreateASTPrinter();
1213
1214 case ASTDump:
1215 return CreateASTDumper();
1216
1217 case ASTView:
1218 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001219
Chris Lattner7f902922009-02-18 01:20:05 +00001220 case PrintDeclContext:
1221 return CreateDeclContextPrinter();
1222
1223 case EmitHTML:
1224 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001225
Chris Lattner7f902922009-02-18 01:20:05 +00001226 case InheritanceView:
1227 return CreateInheritanceViewer(InheritanceViewCls);
1228
1229 case TestSerialization:
1230 return CreateSerializationTest(Diag, FileMgr);
1231
1232 case EmitAssembly:
1233 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001234 case EmitBC:
1235 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001236 BackendAction Act;
1237 if (ProgAction == EmitAssembly)
1238 Act = Backend_EmitAssembly;
1239 else if (ProgAction == EmitLLVM)
1240 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001241 else if (ProgAction == EmitLLVMOnly)
1242 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001243 else
1244 Act = Backend_EmitBC;
1245
1246 CompileOptions Opts;
1247 InitializeCompileOptions(Opts);
1248 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
1249 InFile, OutputFile, GenerateDebugInfo);
1250 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001251
Chris Lattner7f902922009-02-18 01:20:05 +00001252 case SerializeAST:
1253 // FIXME: Allow user to tailor where the file is written.
1254 return CreateASTSerializer(InFile, OutputFile, Diag);
1255
1256 case RewriteObjC:
1257 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001258
Chris Lattner7f902922009-02-18 01:20:05 +00001259 case RewriteBlocks:
1260 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1261
1262 case RunAnalysis:
1263 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001264 }
1265}
1266
Chris Lattner4b009652007-07-25 00:24:17 +00001267/// ProcessInputFile - Process a single input file with the specified state.
1268///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001269static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001270 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001271 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001272 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001273
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001274 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001275 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001276 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1277 PP.getFileManager(), PP.getLangOptions(),
1278 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001279
1280 if (!Consumer) {
1281 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001282 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001283 return;
1284 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001285
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001286 break;
1287
Chris Lattneraf669fb2008-10-12 05:03:36 +00001288 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001289 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001290 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001291 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001292 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001293 RawLex.SetKeepWhitespaceMode(true);
1294
1295 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001296 RawLex.LexFromRawLexer(RawTok);
1297 while (RawTok.isNot(tok::eof)) {
1298 PP.DumpToken(RawTok, true);
1299 fprintf(stderr, "\n");
1300 RawLex.LexFromRawLexer(RawTok);
1301 }
1302 ClearSourceMgr = true;
1303 break;
1304 }
Chris Lattner4b009652007-07-25 00:24:17 +00001305 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001306 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001307 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001308 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001309 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001310 do {
1311 PP.Lex(Tok);
1312 PP.DumpToken(Tok, true);
1313 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001314 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001315 ClearSourceMgr = true;
1316 break;
1317 }
1318 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001319 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001320 Token Tok;
1321 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001322 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001323 do {
1324 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001325 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001326 ClearSourceMgr = true;
1327 break;
1328 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001329
1330 case GeneratePCH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001331 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001332 CacheTokens(PP, OutputFile);
1333 ClearSourceMgr = true;
1334 break;
1335 }
Chris Lattner4b009652007-07-25 00:24:17 +00001336
Chris Lattnerefe33382009-02-18 01:51:21 +00001337 case PrintPreprocessedInput: { // -E mode.
1338 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001339 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001340 ClearSourceMgr = true;
1341 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001342 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001343
Chris Lattnerefe33382009-02-18 01:51:21 +00001344 case ParseNoop: { // -parse-noop
1345 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001346 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001347 ClearSourceMgr = true;
1348 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001349 }
Chris Lattner4b009652007-07-25 00:24:17 +00001350
Chris Lattnerefe33382009-02-18 01:51:21 +00001351 case ParsePrintCallbacks: {
1352 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001353 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001354 ClearSourceMgr = true;
1355 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001356 }
1357
1358 case ParseSyntaxOnly: { // -fsyntax-only
1359 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001360 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001361 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001362 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001363
1364 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001365 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001366 ClearSourceMgr = true;
1367 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001368
Chris Lattnerefe33382009-02-18 01:51:21 +00001369 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001370 DoRewriteTest(PP, InFile, OutputFile);
1371 ClearSourceMgr = true;
1372 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001373 }
Chris Lattnerefe33382009-02-18 01:51:21 +00001374 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001375
1376 if (Consumer) {
1377 TranslationUnit *TU = 0;
1378 if (DisableFree) {
1379 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1380 PP.getSourceManager(),
1381 PP.getTargetInfo(),
1382 PP.getIdentifierTable(),
1383 PP.getSelectorTable(),
1384 /* FreeMemory = */ false);
1385 TU = new TranslationUnit(*Context);
1386 }
1387 ParseAST(PP, Consumer.get(), TU, Stats);
1388 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001389
1390 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001391 if (CheckDiagnostics(PP))
1392 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001393
Chris Lattner4b009652007-07-25 00:24:17 +00001394 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001395 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001396 PP.PrintStats();
1397 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001398 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001399 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001400 fprintf(stderr, "\n");
1401 }
1402
1403 // For a multi-file compilation, some things are ok with nuking the source
1404 // manager tables, other require stable fileid/macroid's across multiple
1405 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001406 if (ClearSourceMgr)
1407 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001408
1409 if (DisableFree)
1410 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001411}
1412
Ted Kremenek80d53372007-12-12 23:41:08 +00001413static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1414 FileManager& FileMgr) {
1415
1416 if (VerifyDiagnostics) {
1417 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1418 exit (1);
1419 }
1420
1421 llvm::sys::Path Filename(InFile);
1422
1423 if (!Filename.isValid()) {
1424 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1425 exit (1);
1426 }
1427
Ted Kremenek863b01f2008-04-23 16:25:39 +00001428 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001429
1430 if (!TU) {
1431 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1432 InFile.c_str());
1433 exit (1);
1434 }
1435
Ted Kremenekab749372007-12-19 19:27:38 +00001436 // Observe that we use the source file name stored in the deserialized
1437 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001438 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001439 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001440 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001441
Ted Kremenek80d53372007-12-12 23:41:08 +00001442 if (!Consumer) {
1443 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1444 exit (1);
1445 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001446
Ted Kremenek863b01f2008-04-23 16:25:39 +00001447 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001448
Chris Lattner8d72ee02008-02-06 01:42:25 +00001449 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001450 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1451 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001452}
1453
1454
Chris Lattner4b009652007-07-25 00:24:17 +00001455static llvm::cl::list<std::string>
1456InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1457
Ted Kremenek80d53372007-12-12 23:41:08 +00001458static bool isSerializedFile(const std::string& InFile) {
1459 if (InFile.size() < 4)
1460 return false;
1461
1462 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00001463 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00001464}
1465
Chris Lattner4b009652007-07-25 00:24:17 +00001466
1467int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001468 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001469 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001470 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001471 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001472
Chris Lattnerefe33382009-02-18 01:51:21 +00001473 if (TimeReport)
1474 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1475
Chris Lattner4b009652007-07-25 00:24:17 +00001476 // If no input was specified, read from stdin.
1477 if (InputFilenames.empty())
1478 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001479
Chris Lattner4b009652007-07-25 00:24:17 +00001480 // Create a file manager object to provide access to and cache the filesystem.
1481 FileManager FileMgr;
1482
Ted Kremenekb240e822007-12-11 23:28:38 +00001483 // Create the diagnostic client for reporting errors or for
1484 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001485 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001486
Ted Kremenek5c341732008-08-07 17:49:57 +00001487 if (!VerifyDiagnostics) {
1488 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001489 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1490 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001491 !NoCaretDiagnostics,
1492 !NoShowLocation);
Ted Kremenek5c341732008-08-07 17:49:57 +00001493 } else {
1494 // When checking diagnostics, just buffer them up.
1495 TextDiagClient = new TextDiagnosticBuffer();
1496
1497 if (InputFilenames.size() != 1) {
1498 fprintf(stderr,
1499 "-verify only works on single input files for now.\n");
1500 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001501 }
1502 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001503
Chris Lattner4b009652007-07-25 00:24:17 +00001504 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001505 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1506 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001507 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001508 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001509
Chris Lattner45a56e02007-12-05 23:24:17 +00001510 // -I- is a deprecated GCC feature, scan for it and reject it.
1511 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1512 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001513 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001514 I_dirs.erase(I_dirs.begin()+i);
1515 --i;
1516 }
1517 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001518
1519 // Get information about the target being compiled for.
1520 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001521 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1522
Chris Lattner2c77d852008-03-14 06:12:05 +00001523 if (Target == 0) {
1524 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1525 Triple.c_str());
1526 fprintf(stderr, "Please use -triple or -arch.\n");
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001527 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001528 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001529
Daniel Dunbar9c321102009-01-20 23:17:32 +00001530 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001531 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001532
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001533 llvm::OwningPtr<SourceManager> SourceMgr;
1534
Chris Lattner4b009652007-07-25 00:24:17 +00001535 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001536 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001537
Ted Kremenek5c341732008-08-07 17:49:57 +00001538 if (isSerializedFile(InFile)) {
1539 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001540 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00001541 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001542 }
Chris Lattner2b989562009-03-04 21:40:56 +00001543
1544 /// Create a SourceManager object. This tracks and owns all the file
1545 /// buffers allocated to a translation unit.
1546 if (!SourceMgr)
1547 SourceMgr.reset(new SourceManager());
1548 else
1549 SourceMgr->clearIDTables();
1550
1551 // Initialize language options, inferring file types from input filenames.
1552 LangOptions LangInfo;
1553 InitializeBaseLanguage();
1554 LangKind LK = GetLanguage(InFile);
1555 bool PCH = InitializeLangOptions(LangInfo, LK);
1556 InitializeGCMode(LangInfo);
1557 InitializeLanguageStandard(LangInfo, LK, Target.get());
1558
1559 // Process the -I options and set them in the HeaderInfo.
1560 HeaderSearch HeaderInfo(FileMgr);
1561
1562 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1563
1564 // Set up the preprocessor with these options.
1565 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1566 *SourceMgr.get(), HeaderInfo);
1567
1568 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1569
1570 if (!PP)
1571 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001572
Chris Lattner2b989562009-03-04 21:40:56 +00001573 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1574 // always reset to using TextDiagClient.
1575 llvm::OwningPtr<DiagnosticClient> TmpClient;
1576
1577 if (!HTMLDiag.empty()) {
1578 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1579 &PPFactory));
1580 Diags.setClient(TmpClient.get());
Ted Kremenek80d53372007-12-12 23:41:08 +00001581 }
Chris Lattner2b989562009-03-04 21:40:56 +00001582 else
1583 Diags.setClient(TextDiagClient);
1584
1585 // Process the source file.
1586 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1587
1588 HeaderInfo.ClearFileInfo();
Chris Lattner4b009652007-07-25 00:24:17 +00001589 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001590
Mike Stump91d01352009-01-28 02:43:35 +00001591 if (Verbose)
1592 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1593 " hosted on " LLVM_HOSTTRIPLE "\n");
1594
Ted Kremenekec6c5252008-08-07 18:13:12 +00001595 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001596 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1597 (NumDiagnostics == 1 ? "" : "s"));
1598
1599 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001600 FileMgr.PrintStats();
1601 fprintf(stderr, "\n");
1602 }
1603
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001604 // If verifying diagnostics and we reached here, all is well.
1605 if (VerifyDiagnostics)
1606 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001607
1608 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001609
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001610 // Managed static deconstruction. Useful for making things like
1611 // -time-passes usable.
1612 llvm::llvm_shutdown();
1613
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001614 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001615}