blob: 19f42b442c1734082685d05a4a6a06f5df65ebf2 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Ted Kremenekc2542b62009-03-31 18:58:14 +000025#include "clang-cc.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000031#include "clang/Frontend/PathDiagnosticClients.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000032#include "clang/Frontend/TextDiagnosticBuffer.h"
33#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000034#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000039#include "clang/AST/ASTContext.h"
40#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000041#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000042#include "clang/Parse/Parser.h"
43#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000044#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045#include "clang/Basic/FileManager.h"
46#include "clang/Basic/SourceManager.h"
47#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000048#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000049#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000050#include "llvm/ADT/StringExtras.h"
51#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000052#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000053#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000054#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000055#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000056#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000057#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000058#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000059#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000060#include "llvm/System/Signals.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000061using namespace clang;
62
63//===----------------------------------------------------------------------===//
64// Global options.
65//===----------------------------------------------------------------------===//
66
Chris Lattner47099742009-02-18 01:51:21 +000067/// ClangFrontendTimer - The front-end activities should charge time to it with
68/// TimeRegion. The -ftime-report option controls whether this will do
69/// anything.
70llvm::Timer *ClangFrontendTimer = 0;
71
Daniel Dunbard3db4012008-10-16 16:54:18 +000072static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +000073
Reid Spencer5f016e22007-07-11 17:01:13 +000074static llvm::cl::opt<bool>
75Verbose("v", llvm::cl::desc("Enable verbose output"));
76static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000077Stats("print-stats",
78 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000079static llvm::cl::opt<bool>
80DisableFree("disable-free",
81 llvm::cl::desc("Disable freeing of memory on exit"),
82 llvm::cl::init(false));
Reid Spencer5f016e22007-07-11 17:01:13 +000083
84enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000085 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000086 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000087 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000088 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +000089 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +000090 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000091 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000092 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000093 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +000094 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000095 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000096 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000097 ASTPrint, // Parse ASTs and print them.
98 ASTDump, // Parse ASTs and dump them.
99 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000100 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000101 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 ParsePrintCallbacks, // Parse and print each callback.
103 ParseSyntaxOnly, // Parse and perform semantic analysis.
104 ParseNoop, // Parse with noop callbacks.
105 RunPreprocessorOnly, // Just lex, no output.
106 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000107 DumpTokens, // Dump out preprocessed tokens.
108 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000109 RunAnalysis, // Run one or more source code analyses.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000110 GeneratePCH, // Generate precompiled header.
111 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000112};
113
114static llvm::cl::opt<ProgActions>
115ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
116 llvm::cl::init(ParseSyntaxOnly),
117 llvm::cl::values(
118 clEnumValN(RunPreprocessorOnly, "Eonly",
119 "Just run preprocessor, no output (for timings)"),
120 clEnumValN(PrintPreprocessedInput, "E",
121 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000122 clEnumValN(DumpRawTokens, "dump-raw-tokens",
123 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000124 clEnumValN(RunAnalysis, "analyze",
125 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000126 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 "Run preprocessor, dump internal rep of tokens"),
128 clEnumValN(ParseNoop, "parse-noop",
129 "Run parser with noop callbacks (for timings)"),
130 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
131 "Run parser and perform semantic analysis"),
132 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
133 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000134 clEnumValN(EmitHTML, "emit-html",
135 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000136 clEnumValN(ASTPrint, "ast-print",
137 "Build ASTs and then pretty-print them"),
138 clEnumValN(ASTDump, "ast-dump",
139 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000140 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000141 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000142 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000143 "Print DeclContexts and their Decls"),
144 clEnumValN(GeneratePCH, "emit-pth",
145 "Generate pre-tokenized header file"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000146 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000147 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000148 clEnumValN(EmitAssembly, "S",
149 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000151 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000152 clEnumValN(EmitBC, "emit-llvm-bc",
153 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000154 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
155 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000156 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000157 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000158 clEnumValN(RewriteTest, "rewrite-test",
159 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000160 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000161 "Rewrite ObjC into C (code rewriter example)"),
162 clEnumValN(RewriteMacros, "rewrite-macros",
163 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000164 clEnumValN(RewriteBlocks, "rewrite-blocks",
165 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000166 clEnumValN(FixIt, "fixit",
167 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000168 clEnumValEnd));
169
Ted Kremenekccc76472007-12-19 19:47:59 +0000170
171static llvm::cl::opt<std::string>
172OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000173 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000174 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000175
Ted Kremenekc2e72992008-12-02 19:57:31 +0000176
177//===----------------------------------------------------------------------===//
178// PTH.
179//===----------------------------------------------------------------------===//
180
181static llvm::cl::opt<std::string>
182TokenCache("token-cache", llvm::cl::value_desc("path"),
183 llvm::cl::desc("Use specified token cache file"));
184
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000185//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000186// Diagnostic Options
187//===----------------------------------------------------------------------===//
188
Ted Kremenek41193e42007-09-26 19:42:19 +0000189static llvm::cl::opt<bool>
190VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000191 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000192
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000193static llvm::cl::opt<std::string>
194HTMLDiag("html-diags",
195 llvm::cl::desc("Generate HTML to report diagnostics"),
196 llvm::cl::value_desc("HTML directory"));
197
Nico Weberfd54ebc2008-08-05 23:33:20 +0000198static llvm::cl::opt<bool>
199NoShowColumn("fno-show-column",
200 llvm::cl::desc("Do not include column number on diagnostics"));
201
202static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000203NoShowLocation("fno-show-source-location",
204 llvm::cl::desc("Do not include source location information with"
205 " diagnostics"));
206
207static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000208NoCaretDiagnostics("fno-caret-diagnostics",
209 llvm::cl::desc("Do not include source line and caret with"
210 " diagnostics"));
211
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000212static llvm::cl::opt<bool>
213PrintSourceRangeInfo("fprint-source-range-info",
214 llvm::cl::desc("Print source range spans in numeric form"));
215
Nico Weberfd54ebc2008-08-05 23:33:20 +0000216
Reid Spencer5f016e22007-07-11 17:01:13 +0000217//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000218// C++ Visualization.
219//===----------------------------------------------------------------------===//
220
221static llvm::cl::opt<std::string>
222InheritanceViewCls("cxx-inheritance-view",
223 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000224 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000225
226//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000227// Builtin Options
228//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000229
230static llvm::cl::opt<bool>
231TimeReport("ftime-report",
232 llvm::cl::desc("Print the amount of time each "
233 "phase of compilation takes"));
234
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000235static llvm::cl::opt<bool>
236Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000237 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000238 "freestanding environment"));
239
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000240static llvm::cl::opt<bool>
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000241AllowBuiltins("fbuiltin",
242 llvm::cl::desc("Disable implicit builtin knowledge of functions"),
243 llvm::cl::init(true), llvm::cl::AllowInverse);
Chris Lattner7644f072009-03-13 22:38:49 +0000244
245
246static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000247MathErrno("fmath-errno",
Chris Lattner5ea9d1b2009-02-17 00:30:31 +0000248 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner5bef8dd2009-02-17 00:35:09 +0000249 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000250
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000251//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000252// Language Options
253//===----------------------------------------------------------------------===//
254
255enum LangKind {
256 langkind_unspecified,
257 langkind_c,
258 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000259 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 langkind_cxx,
261 langkind_cxx_cpp,
262 langkind_objc,
263 langkind_objc_cpp,
264 langkind_objcxx,
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000265 langkind_objcxx_cpp
Reid Spencer5f016e22007-07-11 17:01:13 +0000266};
267
Reid Spencer5f016e22007-07-11 17:01:13 +0000268static llvm::cl::opt<LangKind>
269BaseLang("x", llvm::cl::desc("Base language to compile"),
270 llvm::cl::init(langkind_unspecified),
271 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
272 clEnumValN(langkind_cxx, "c++", "C++"),
273 clEnumValN(langkind_objc, "objective-c", "Objective C"),
274 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000275 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000277 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
278 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000280 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
282 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000283 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000285 clEnumValN(langkind_c, "c-header",
286 "C header"),
287 clEnumValN(langkind_objc, "objective-c-header",
288 "Objective-C header"),
289 clEnumValN(langkind_cxx, "c++-header",
290 "C++ header"),
291 clEnumValN(langkind_objcxx, "objective-c++-header",
292 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 clEnumValEnd));
294
295static llvm::cl::opt<bool>
296LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
297 llvm::cl::Hidden);
298static llvm::cl::opt<bool>
299LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
300 llvm::cl::Hidden);
301
Ted Kremenek8904f152007-12-05 23:49:08 +0000302/// InitializeBaseLanguage - Handle the -x foo options.
303static void InitializeBaseLanguage() {
304 if (LangObjC)
305 BaseLang = langkind_objc;
306 else if (LangObjCXX)
307 BaseLang = langkind_objcxx;
308}
309
310static LangKind GetLanguage(const std::string &Filename) {
311 if (BaseLang != langkind_unspecified)
312 return BaseLang;
313
314 std::string::size_type DotPos = Filename.rfind('.');
315
316 if (DotPos == std::string::npos) {
317 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000318 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 }
320
Ted Kremenek8904f152007-12-05 23:49:08 +0000321 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
322 // C header: .h
323 // C++ header: .hh or .H;
324 // assembler no preprocessing: .s
325 // assembler: .S
326 if (Ext == "c")
327 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000328 else if (Ext == "S" ||
329 // If the compiler is run on a .s file, preprocess it as .S
330 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000331 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000332 else if (Ext == "i")
333 return langkind_c_cpp;
334 else if (Ext == "ii")
335 return langkind_cxx_cpp;
336 else if (Ext == "m")
337 return langkind_objc;
338 else if (Ext == "mi")
339 return langkind_objc_cpp;
340 else if (Ext == "mm" || Ext == "M")
341 return langkind_objcxx;
342 else if (Ext == "mii")
343 return langkind_objcxx_cpp;
344 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
345 Ext == "c++" || Ext == "cp" || Ext == "cxx")
346 return langkind_cxx;
347 else
348 return langkind_c;
349}
350
351
Ted Kremenek85888962008-10-21 00:54:44 +0000352static void InitializeCOptions(LangOptions &Options) {
353 // Do nothing.
354}
355
356static void InitializeObjCOptions(LangOptions &Options) {
357 Options.ObjC1 = Options.ObjC2 = 1;
358}
359
360
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000361static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // FIXME: implement -fpreprocessed mode.
363 bool NoPreprocess = false;
364
Ted Kremenek8904f152007-12-05 23:49:08 +0000365 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000367 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000368 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000369 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 case langkind_c_cpp:
371 NoPreprocess = true;
372 // FALLTHROUGH
373 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000374 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 break;
376 case langkind_cxx_cpp:
377 NoPreprocess = true;
378 // FALLTHROUGH
379 case langkind_cxx:
380 Options.CPlusPlus = 1;
381 break;
382 case langkind_objc_cpp:
383 NoPreprocess = true;
384 // FALLTHROUGH
385 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000386 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 break;
388 case langkind_objcxx_cpp:
389 NoPreprocess = true;
390 // FALLTHROUGH
391 case langkind_objcxx:
392 Options.ObjC1 = Options.ObjC2 = 1;
393 Options.CPlusPlus = 1;
394 break;
395 }
396}
397
398/// LangStds - Language standards we support.
399enum LangStds {
400 lang_unspecified,
401 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000402 lang_gnu_START,
403 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000404 lang_cxx98, lang_gnucxx98,
405 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000406};
407
408static llvm::cl::opt<LangStds>
409LangStd("std", llvm::cl::desc("Language standard to compile for"),
410 llvm::cl::init(lang_unspecified),
411 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
412 clEnumValN(lang_c89, "c90", "ISO C 1990"),
413 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
414 clEnumValN(lang_c94, "iso9899:199409",
415 "ISO C 1990 with amendment 1"),
416 clEnumValN(lang_c99, "c99", "ISO C 1999"),
417// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
418 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
419// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
420 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000421 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000423 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 clEnumValN(lang_gnu99, "gnu9x",
425 "ISO C 1999 with GNU extensions"),
426 clEnumValN(lang_cxx98, "c++98",
427 "ISO C++ 1998 with amendments"),
428 clEnumValN(lang_gnucxx98, "gnu++98",
429 "ISO C++ 1998 with amendments and GNU "
430 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000431 clEnumValN(lang_cxx0x, "c++0x",
432 "Upcoming ISO C++ 200x with amendments"),
433 clEnumValN(lang_gnucxx0x, "gnu++0x",
434 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000435 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000436 clEnumValEnd));
437
438static llvm::cl::opt<bool>
439NoOperatorNames("fno-operator-names",
440 llvm::cl::desc("Do not treat C++ operator name keywords as "
441 "synonyms for operators"));
442
Anders Carlssonee98ac52007-10-15 02:50:23 +0000443static llvm::cl::opt<bool>
444PascalStrings("fpascal-strings",
445 llvm::cl::desc("Recognize and construct Pascal-style "
446 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000447
448static llvm::cl::opt<bool>
449MSExtensions("fms-extensions",
450 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000451 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000452
453static llvm::cl::opt<bool>
454WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000455 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000456
457static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000458NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000459 llvm::cl::desc("Disallow implicit conversions between "
460 "vectors with a different number of "
461 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000462
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000463static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000464EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
465 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
466 llvm::cl::ZeroOrMore);
467
468static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000469EnableHeinousExtensions("fheinous-gnu-extensions",
470 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
471 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
472
473static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000474ObjCNonFragileABI("fobjc-nonfragile-abi",
475 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000476
Daniel Dunbard604c402009-02-04 21:19:06 +0000477static llvm::cl::opt<bool>
478EmitAllDecls("femit-all-decls",
479 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000480
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000481// FIXME: This (and all GCC -f options) really come in -f... and
482// -fno-... forms, and additionally support automagic behavior when
483// they are not defined. For example, -fexceptions defaults to on or
484// off depending on the language. We should support this behavior in
485// some form (perhaps just add a facility for distinguishing when an
486// has its default value from when it has been set to its default
487// value).
488static llvm::cl::opt<bool>
489Exceptions("fexceptions",
490 llvm::cl::desc("Enable support for exception handling."));
491
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000492static llvm::cl::opt<bool>
493GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000494 llvm::cl::desc("Generate output compatible with the standard GNU "
495 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000496
497static llvm::cl::opt<bool>
498NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000499 llvm::cl::desc("Generate output compatible with the NeXT "
500 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000501
Ted Kremenekea644d82008-09-03 21:22:16 +0000502
503
504static llvm::cl::opt<bool>
505Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
506
507static llvm::cl::opt<bool>
508Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
509
Chris Lattner16167a62009-03-02 22:11:07 +0000510static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000511TargetFeatures("mattr", llvm::cl::CommaSeparated,
512 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
513
Douglas Gregor26dce442009-03-10 00:06:19 +0000514static llvm::cl::opt<unsigned>
515TemplateDepth("ftemplate-depth", llvm::cl::init(99),
516 llvm::cl::desc("Maximum depth of recursive template "
517 "instantiation"));
Chris Lattner16167a62009-03-02 22:11:07 +0000518
Reid Spencer5f016e22007-07-11 17:01:13 +0000519// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000520// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000521static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
522 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000523 // Allow the target to set the default the langauge options as it sees fit.
524 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000525
Chris Lattner6328cc32009-03-03 19:56:18 +0000526 // If there are any -mattr options, pass them to the target for validation and
527 // processing. The driver should have already consolidated all the
528 // target-feature settings and passed them to us in the -mattr list. The
529 // -mattr list is treated by the code generator as a diff against the -mcpu
530 // setting, but the driver should pass all enabled options as "+" settings.
531 // This means that the target should only look at + settings.
532 if (!TargetFeatures.empty()
533 // FIXME: The driver is not quite yet ready for this.
534 && 0) {
Chris Lattner16167a62009-03-02 22:11:07 +0000535 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000536 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
537 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000538 if (Opt != -1) {
539 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000540 fprintf(stderr, "invalid feature '%s'\n",
541 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000542 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000543 fprintf(stderr, "feature '%s': %s\n",
544 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000545 exit(1);
546 }
547 }
548
Ted Kremenekea644d82008-09-03 21:22:16 +0000549 if (Ansi) // "The -ansi option is equivalent to -std=c89."
550 LangStd = lang_c89;
551
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 if (LangStd == lang_unspecified) {
553 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000554 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000555 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000557 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 case langkind_c_cpp:
559 case langkind_objc:
560 case langkind_objc_cpp:
561 LangStd = lang_gnu99;
562 break;
563 case langkind_cxx:
564 case langkind_cxx_cpp:
565 case langkind_objcxx:
566 case langkind_objcxx_cpp:
567 LangStd = lang_gnucxx98;
568 break;
569 }
570 }
571
572 switch (LangStd) {
573 default: assert(0 && "Unknown language standard!");
574
575 // Fall through from newer standards to older ones. This isn't really right.
576 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000577 case lang_gnucxx0x:
578 case lang_cxx0x:
579 Options.CPlusPlus0x = 1;
580 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 case lang_gnucxx98:
582 case lang_cxx98:
583 Options.CPlusPlus = 1;
584 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000585 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 // FALL THROUGH.
587 case lang_gnu99:
588 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 Options.C99 = 1;
590 Options.HexFloats = 1;
591 // FALL THROUGH.
592 case lang_gnu89:
593 Options.BCPLComment = 1; // Only for C99/C++.
594 // FALL THROUGH.
595 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000596 Options.Digraphs = 1; // C94, C99, C++.
597 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 case lang_c89:
599 break;
600 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000601
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000602 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
603 Options.GNUMode = LangStd >= lang_gnu_START;
604
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000605 if (Options.CPlusPlus) {
606 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000607 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000608 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000609
Chris Lattnerd658b562008-04-05 06:32:51 +0000610 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
611 Options.ImplicitInt = 1;
612 else
613 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000614
615 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
616 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000617 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000618 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000619 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000620
Chris Lattner802db9b2008-12-05 00:10:44 +0000621 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
622 // even if they are normally on for the target. In GNU modes (e.g.
623 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000624 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000625 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000626 Options.Blocks = 0;
627
Daniel Dunbar85c49102009-03-15 00:11:28 +0000628 // Never accept '$' in identifiers when preprocessing assembler.
629 if (LK != langkind_asm_cpp)
630 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000631 if (PascalStrings.getPosition())
632 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000633 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000634 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000635 if (NoLaxVectorConversions.getPosition())
636 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000637 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000638 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000639 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000640
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000641 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000642 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000643 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000644 Options.Freestanding = Options.NoBuiltin = 1;
645
Chris Lattner810f6d52009-03-13 17:38:01 +0000646 if (EnableHeinousExtensions)
647 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000648
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000649 Options.MathErrno = MathErrno;
650
Douglas Gregor26dce442009-03-10 00:06:19 +0000651 Options.InstantiationDepth = TemplateDepth;
652
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000653 // Override the default runtime if the user requested it.
654 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000655 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000656 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000657 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000658
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000659 if (ObjCNonFragileABI)
660 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000661
662 if (EmitAllDecls)
663 Options.EmitAllDecls = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000664}
665
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000666static llvm::cl::opt<bool>
667ObjCExclusiveGC("fobjc-gc-only",
668 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000669 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000670
671static llvm::cl::opt<bool>
672ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000673 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000674
675void InitializeGCMode(LangOptions &Options) {
676 if (ObjCExclusiveGC)
677 Options.setGCMode(LangOptions::GCOnly);
678 else if (ObjCEnableGC)
679 Options.setGCMode(LangOptions::HybridGC);
680}
681
Mike Stump2add4732009-04-01 20:28:16 +0000682static llvm::cl::opt<bool>
683OverflowChecking("ftrapv",
Mike Stump035cf892009-04-02 18:15:54 +0000684 llvm::cl::desc("Trap on integer overflow"),
Mike Stump2add4732009-04-01 20:28:16 +0000685 llvm::cl::init(false));
686
687void InitializeOverflowChecking(LangOptions &Options) {
Mike Stump035cf892009-04-02 18:15:54 +0000688 Options.OverflowChecking = OverflowChecking;
Mike Stump2add4732009-04-01 20:28:16 +0000689}
Reid Spencer5f016e22007-07-11 17:01:13 +0000690//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000691// Target Triple Processing.
692//===----------------------------------------------------------------------===//
693
694static llvm::cl::opt<std::string>
695TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000696 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000697
Chris Lattner42e67372008-03-05 01:18:20 +0000698static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000699Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000700
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000701static llvm::cl::opt<std::string>
702MacOSVersionMin("mmacosx-version-min",
703 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
704
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000705// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
706// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000707
708// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000709static void HandleMacOSVersionMin(std::string &Triple) {
710 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
711 if (DarwinDashIdx == std::string::npos) {
712 fprintf(stderr,
713 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
714 exit(1);
715 }
716 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
717
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000718 // Remove the number.
719 Triple.resize(DarwinNumIdx);
720
721 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
722 bool MacOSVersionMinIsInvalid = false;
723 int VersionNum = 0;
724 if (MacOSVersionMin.size() < 4 ||
725 MacOSVersionMin.substr(0, 3) != "10." ||
726 !isdigit(MacOSVersionMin[3])) {
727 MacOSVersionMinIsInvalid = true;
728 } else {
729 const char *Start = MacOSVersionMin.c_str()+3;
730 char *End = 0;
731 VersionNum = (int)strtol(Start, &End, 10);
732
Chris Lattner079f2c462008-09-30 20:30:12 +0000733 // The version number must be in the range 0-9.
734 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
735
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000736 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
737 Triple += llvm::itostr(VersionNum+4);
738
Chris Lattner079f2c462008-09-30 20:30:12 +0000739 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
740 // Add the period piece (.7) to the end of the triple. This gives us
741 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000742 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000743 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
744 MacOSVersionMinIsInvalid = true;
745 }
746 }
747
748 if (MacOSVersionMinIsInvalid) {
749 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000750 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000751 MacOSVersionMin.c_str());
752 exit(1);
753 }
754}
755
756/// CreateTargetTriple - Process the various options that affect the target
757/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000758static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000759 // Initialize base triple. If a -triple option has been specified, use
760 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000761 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000762 if (Triple.empty())
763 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +0000764
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000765 // If -arch foo was specified, remove the architecture from the triple we have
766 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000767
768 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000769 if (!Arch.empty()) {
770 // Decompose the base triple into "arch" and suffix.
771 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000772
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000773 if (FirstDashIdx == std::string::npos) {
774 fprintf(stderr,
775 "Malformed target triple: \"%s\" ('-' could not be found).\n",
776 Triple.c_str());
777 exit(1);
778 }
Chris Lattner37e217c2009-03-24 16:18:41 +0000779
780 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
781 if (Arch == "ppc")
782 Arch = "powerpc";
783 else if (Arch == "ppc64")
784 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +0000785
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000786 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
787 }
788
789 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
790 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000791 if (!MacOSVersionMin.empty())
792 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000793
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000794 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000795}
796
797//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000798// Preprocessor Initialization
799//===----------------------------------------------------------------------===//
800
801// FIXME: Preprocessor builtins to support.
802// -A... - Play with #assertions
803// -undef - Undefine all predefined macros
804
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000805// FIXME: -imacros
806
Reid Spencer5f016e22007-07-11 17:01:13 +0000807static llvm::cl::list<std::string>
808D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
809 llvm::cl::desc("Predefine the specified macro"));
810static llvm::cl::list<std::string>
811U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
812 llvm::cl::desc("Undefine the specified macro"));
813
Chris Lattner64299f82008-01-10 01:53:41 +0000814static llvm::cl::list<std::string>
815ImplicitIncludes("include", llvm::cl::value_desc("file"),
816 llvm::cl::desc("Include file before parsing"));
817
Ted Kremenek748d5d62009-03-20 00:26:38 +0000818static llvm::cl::opt<std::string>
819ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
820 llvm::cl::desc("Include file before parsing"));
821
Reid Spencer5f016e22007-07-11 17:01:13 +0000822// Append a #define line to Buf for Macro. Macro should be of the form XXX,
823// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
824// "#define XXX Y z W". To get a #define with no value, use "XXX=".
825static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
826 const char *Command = "#define ") {
827 Buf.insert(Buf.end(), Command, Command+strlen(Command));
828 if (const char *Equal = strchr(Macro, '=')) {
829 // Turn the = into ' '.
830 Buf.insert(Buf.end(), Macro, Equal);
831 Buf.push_back(' ');
832 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
833 } else {
834 // Push "macroname 1".
835 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
836 Buf.push_back(' ');
837 Buf.push_back('1');
838 }
839 Buf.push_back('\n');
840}
841
Chris Lattner64299f82008-01-10 01:53:41 +0000842/// AddImplicitInclude - Add an implicit #include of the specified file to the
843/// predefines buffer.
844static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
845 const char *Inc = "#include \"";
846 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
847 Buf.insert(Buf.end(), File.begin(), File.end());
848 Buf.push_back('"');
849 Buf.push_back('\n');
850}
851
Ted Kremenek748d5d62009-03-20 00:26:38 +0000852/// AddImplicitIncludePTH - Add an implicit #include using the original file
853/// used to generate a PTH cache.
854static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
855 PTHManager *P = PP.getPTHManager();
856 assert(P && "No PTHManager.");
857 const char *OriginalFile = P->getOriginalSourceFile();
858
859 if (!OriginalFile) {
860 assert(!ImplicitIncludePTH.empty());
861 fprintf(stderr, "error: PTH file '%s' does not designate an original "
862 "source header file for -include-pth\n",
863 ImplicitIncludePTH.c_str());
864 exit (1);
865 }
866
867 AddImplicitInclude(Buf, OriginalFile);
868}
Reid Spencer5f016e22007-07-11 17:01:13 +0000869
Chris Lattner53b0dab2007-10-09 22:10:18 +0000870/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000871/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000872///
Chris Lattner51574ea2008-04-19 23:25:44 +0000873static bool InitializePreprocessor(Preprocessor &PP,
874 bool InitializeSourceMgr,
875 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000876 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000877
Chris Lattner53b0dab2007-10-09 22:10:18 +0000878 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000879 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000880
881 if (InitializeSourceMgr) {
882 if (InFile != "-") {
883 const FileEntry *File = FileMgr.getFile(InFile);
884 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +0000885 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000886 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
887 << InFile.c_str();
Chris Lattner51574ea2008-04-19 23:25:44 +0000888 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000889 }
890 } else {
891 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar56743882009-03-21 17:56:30 +0000892
893 // If stdin was empty, SB is null. Cons up an empty memory
894 // buffer now.
895 if (!SB) {
896 const char *EmptyStr = "";
897 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
898 }
899
900 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000901 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000902 PP.getDiagnostics().Report(FullSourceLoc(),
903 diag::err_fe_error_reading_stdin);
Chris Lattner51574ea2008-04-19 23:25:44 +0000904 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000905 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000906 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000908
Chris Lattneraa391972008-04-19 23:09:31 +0000909 std::vector<char> PredefineBuffer;
910
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000912 unsigned d = 0, D = D_macros.size();
913 unsigned u = 0, U = U_macros.size();
914 while (d < D || u < U) {
915 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
916 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
917 else
918 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
919 }
920
Chris Lattner64299f82008-01-10 01:53:41 +0000921 // FIXME: Read any files specified by -imacros.
922
Ted Kremenek748d5d62009-03-20 00:26:38 +0000923 // Add implicit #includes from -include and -include-pth.
924 bool handledPTH = ImplicitIncludePTH.empty();
925 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc53b60a2009-03-20 00:40:03 +0000926 if (!handledPTH &&
927 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek748d5d62009-03-20 00:26:38 +0000928 AddImplicitIncludePTH(PredefineBuffer, PP);
929 handledPTH = true;
930 }
931
Chris Lattner64299f82008-01-10 01:53:41 +0000932 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek748d5d62009-03-20 00:26:38 +0000933 }
934 if (!handledPTH && !ImplicitIncludePTH.empty())
935 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000936
Chris Lattneraa391972008-04-19 23:09:31 +0000937 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000938 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000939 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000940
941 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000942 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000943}
944
945//===----------------------------------------------------------------------===//
946// Preprocessor include path information.
947//===----------------------------------------------------------------------===//
948
949// This tool exports a large number of command line options to control how the
950// preprocessor searches for header files. At root, however, the Preprocessor
951// object takes a very simple interface: a list of directories to search for
952//
953// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000954// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000955//
Reid Spencer5f016e22007-07-11 17:01:13 +0000956
957static llvm::cl::opt<bool>
958nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
959
960// Various command line options. These four add directories to each chain.
961static llvm::cl::list<std::string>
962F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
963 llvm::cl::desc("Add directory to framework include search path"));
964static llvm::cl::list<std::string>
965I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
966 llvm::cl::desc("Add directory to include search path"));
967static llvm::cl::list<std::string>
968idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
969 llvm::cl::desc("Add directory to AFTER include search path"));
970static llvm::cl::list<std::string>
971iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
972 llvm::cl::desc("Add directory to QUOTE include search path"));
973static llvm::cl::list<std::string>
974isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
975 llvm::cl::desc("Add directory to SYSTEM include search path"));
976
977// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
978static llvm::cl::list<std::string>
979iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
980 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
981static llvm::cl::list<std::string>
982iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
983 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
984static llvm::cl::list<std::string>
985iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
986 llvm::cl::Prefix,
987 llvm::cl::desc("Set directory to include search path with prefix"));
988
Chris Lattner0c946412007-08-26 17:47:35 +0000989static llvm::cl::opt<std::string>
990isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
991 llvm::cl::desc("Set the system root directory (usually /)"));
992
Reid Spencer5f016e22007-07-11 17:01:13 +0000993// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +0000994
Reid Spencer5f016e22007-07-11 17:01:13 +0000995/// InitializeIncludePaths - Process the -I options and set them in the
996/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +0000997void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
998 FileManager &FM, const LangOptions &Lang) {
999 InitHeaderSearch Init(Headers, Verbose, isysroot);
1000
Ted Kremenekf3721112008-05-31 00:27:00 +00001001 // Handle -I... and -F... options, walking the lists in parallel.
1002 unsigned Iidx = 0, Fidx = 0;
1003 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1004 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001005 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001006 ++Iidx;
1007 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001008 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001009 ++Fidx;
1010 }
1011 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001012
Ted Kremenekf3721112008-05-31 00:27:00 +00001013 // Consume what's left from whatever list was longer.
1014 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001015 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001016 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001017 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001018
1019 // Handle -idirafter... options.
1020 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001021 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1022 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001023
1024 // Handle -iquote... options.
1025 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001026 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001027
1028 // Handle -isystem... options.
1029 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001030 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001031
1032 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1033 // parallel, processing the values in order of occurance to get the right
1034 // prefixes.
1035 {
1036 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1037 unsigned iprefix_idx = 0;
1038 unsigned iwithprefix_idx = 0;
1039 unsigned iwithprefixbefore_idx = 0;
1040 bool iprefix_done = iprefix_vals.empty();
1041 bool iwithprefix_done = iwithprefix_vals.empty();
1042 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1043 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1044 if (!iprefix_done &&
1045 (iwithprefix_done ||
1046 iprefix_vals.getPosition(iprefix_idx) <
1047 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1048 (iwithprefixbefore_done ||
1049 iprefix_vals.getPosition(iprefix_idx) <
1050 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1051 Prefix = iprefix_vals[iprefix_idx];
1052 ++iprefix_idx;
1053 iprefix_done = iprefix_idx == iprefix_vals.size();
1054 } else if (!iwithprefix_done &&
1055 (iwithprefixbefore_done ||
1056 iwithprefix_vals.getPosition(iwithprefix_idx) <
1057 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001058 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1059 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001060 ++iwithprefix_idx;
1061 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1062 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001063 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1064 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 ++iwithprefixbefore_idx;
1066 iwithprefixbefore_done =
1067 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1068 }
1069 }
1070 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001071
Nico Weber0fca0222008-08-22 09:25:22 +00001072 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001073
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001074 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001075 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001076 llvm::sys::Path::GetMainExecutable(Argv0,
1077 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001078 if (!MainExecutablePath.isEmpty()) {
1079 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1080 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001081
1082 // Get foo/lib/clang/1.0/include
1083 //
1084 // FIXME: Don't embed version here.
1085 MainExecutablePath.appendComponent("lib");
1086 MainExecutablePath.appendComponent("clang");
1087 MainExecutablePath.appendComponent("1.0");
1088 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001089
1090 // We pass true to ignore sysroot so that we *always* look for clang headers
1091 // relative to our executable, never relative to -isysroot.
1092 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1093 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001094 }
1095
Nico Weber0fca0222008-08-22 09:25:22 +00001096 if (!nostdinc)
1097 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001098
1099 // Now that we have collected all of the include paths, merge them all
1100 // together and tell the preprocessor about them.
1101
Nico Weber0fca0222008-08-22 09:25:22 +00001102 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001103}
1104
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001105//===----------------------------------------------------------------------===//
1106// Driver PreprocessorFactory - For lazily generating preprocessors ...
1107//===----------------------------------------------------------------------===//
1108
1109namespace {
1110class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001111 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001112 Diagnostic &Diags;
1113 const LangOptions &LangInfo;
1114 TargetInfo &Target;
1115 SourceManager &SourceMgr;
1116 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001117 bool InitializeSourceMgr;
1118
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001119public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001120 DriverPreprocessorFactory(const std::string &infile,
1121 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001122 TargetInfo &target, SourceManager &SM,
1123 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001124 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1125 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1126
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001127
1128 virtual ~DriverPreprocessorFactory() {}
1129
1130 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001131 llvm::OwningPtr<PTHManager> PTHMgr;
1132
Ted Kremenek748d5d62009-03-20 00:26:38 +00001133 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1134 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1135 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001136 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001137 }
1138
Ted Kremenek72b1b152009-01-15 18:47:46 +00001139 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001140 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1141 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001142 PTHMgr.reset(PTHManager::Create(x, &Diags,
1143 TokenCache.empty() ? Diagnostic::Error
1144 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001145 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001146
Ted Kremenek22f0d092009-03-22 06:42:39 +00001147 if (Diags.hasErrorOccurred())
1148 exit(1);
1149
Ted Kremenek72b1b152009-01-15 18:47:46 +00001150 // Create the Preprocessor.
1151 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1152 SourceMgr, HeaderInfo,
1153 PTHMgr.get()));
1154
1155 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1156 // That argument is used as the IdentifierInfoLookup argument to
1157 // IdentifierTable's ctor.
1158 if (PTHMgr) {
1159 PTHMgr->setPreprocessor(PP.get());
1160 PP->setPTHManager(PTHMgr.take());
1161 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001162
Chris Lattner51574ea2008-04-19 23:25:44 +00001163 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001164 return NULL;
1165 }
1166
Daniel Dunbar750c3582008-10-24 22:12:41 +00001167 /// FIXME: PP can only handle one callback
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001168 if (ProgAction != PrintPreprocessedInput) {
1169 std::string ErrStr;
1170 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1171 if (!DFG && !ErrStr.empty()) {
1172 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar750c3582008-10-24 22:12:41 +00001173 return NULL;
1174 }
1175 }
1176
Ted Kremenek339b9c22008-04-17 22:31:54 +00001177 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001178 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001179 }
1180};
1181}
Reid Spencer5f016e22007-07-11 17:01:13 +00001182
Reid Spencer5f016e22007-07-11 17:01:13 +00001183//===----------------------------------------------------------------------===//
1184// Basic Parser driver
1185//===----------------------------------------------------------------------===//
1186
Chris Lattner51574ea2008-04-19 23:25:44 +00001187static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001189 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001190
1191 // Parsing the specified input file.
1192 P.ParseTranslationUnit();
1193 delete PA;
1194}
1195
1196//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001197// Code generation options
1198//===----------------------------------------------------------------------===//
1199
1200static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001201GenerateDebugInfo("g",
1202 llvm::cl::desc("Generate source level debug information"));
1203
1204static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00001205OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbar70f92432008-10-23 05:50:47 +00001206
Chris Lattnerbd360642009-03-26 05:00:52 +00001207static llvm::cl::opt<bool>
1208NoCommon("fno-common",
Mike Stump1c9b7422009-03-27 20:15:22 +00001209 llvm::cl::desc("Compile common globals like normal definitions"),
Chris Lattner925a7042009-03-28 02:12:08 +00001210 llvm::cl::ValueDisallowed);
Chris Lattnerbd360642009-03-26 05:00:52 +00001211
Daniel Dunbar70f92432008-10-23 05:50:47 +00001212// It might be nice to add bounds to the CommandLine library directly.
1213struct OptLevelParser : public llvm::cl::parser<unsigned> {
1214 bool parse(llvm::cl::Option &O, const char *ArgName,
1215 const std::string &Arg, unsigned &Val) {
1216 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1217 return true;
1218 // FIXME: Support -O4.
1219 if (Val > 3)
1220 return O.error(": '" + Arg + "' invalid optimization level!");
1221 return false;
1222 }
1223};
1224static llvm::cl::opt<unsigned, false, OptLevelParser>
1225OptLevel("O", llvm::cl::Prefix,
1226 llvm::cl::desc("Optimization level"),
1227 llvm::cl::init(0));
1228
Daniel Dunbara034ba82009-02-17 19:47:34 +00001229static llvm::cl::opt<std::string>
1230TargetCPU("mcpu",
1231 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1232
Chris Lattner7afae712009-03-16 18:41:18 +00001233static void InitializeCompileOptions(CompileOptions &Opts,
1234 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001235 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001236 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001237 if (OptSize) {
1238 // -Os implies -O2
1239 // FIXME: Diagnose conflicting options.
1240 Opts.OptimizationLevel = 2;
1241 } else {
1242 Opts.OptimizationLevel = OptLevel;
1243 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001244
1245 // FIXME: There are llvm-gcc options to control these selectively.
1246 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1247 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001248 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001249
1250#ifdef NDEBUG
1251 Opts.VerifyModule = 0;
1252#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001253
1254 Opts.CPU = TargetCPU;
1255 Opts.Features.insert(Opts.Features.end(),
1256 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001257
Chris Lattnerbd360642009-03-26 05:00:52 +00001258 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1259
Chris Lattner44502662009-02-18 01:23:44 +00001260 // Handle -ftime-report.
1261 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001262}
1263
1264//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001265// Main driver
1266//===----------------------------------------------------------------------===//
1267
Ted Kremenekdb094a22007-12-05 18:27:04 +00001268/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001269/// action. These consumers can operate on both ASTs that are freshly
1270/// parsed from source files as well as those deserialized from Bitcode.
1271/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001272static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001273 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001274 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001275 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001276 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001277 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001278 default:
1279 return NULL;
1280
1281 case ASTPrint:
1282 return CreateASTPrinter();
1283
1284 case ASTDump:
1285 return CreateASTDumper();
1286
1287 case ASTView:
1288 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001289
Chris Lattner8a5c8092009-02-18 01:20:05 +00001290 case PrintDeclContext:
1291 return CreateDeclContextPrinter();
1292
1293 case EmitHTML:
1294 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001295
Chris Lattner8a5c8092009-02-18 01:20:05 +00001296 case InheritanceView:
1297 return CreateInheritanceViewer(InheritanceViewCls);
1298
1299 case TestSerialization:
1300 return CreateSerializationTest(Diag, FileMgr);
1301
1302 case EmitAssembly:
1303 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001304 case EmitBC:
1305 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001306 BackendAction Act;
1307 if (ProgAction == EmitAssembly)
1308 Act = Backend_EmitAssembly;
1309 else if (ProgAction == EmitLLVM)
1310 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001311 else if (ProgAction == EmitLLVMOnly)
1312 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001313 else
1314 Act = Backend_EmitBC;
1315
1316 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001317 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001318 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001319 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001320 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001321
Chris Lattner8a5c8092009-02-18 01:20:05 +00001322 case SerializeAST:
1323 // FIXME: Allow user to tailor where the file is written.
1324 return CreateASTSerializer(InFile, OutputFile, Diag);
1325
1326 case RewriteObjC:
1327 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001328
Chris Lattner8a5c8092009-02-18 01:20:05 +00001329 case RewriteBlocks:
1330 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1331
1332 case RunAnalysis:
1333 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001334 }
1335}
1336
Reid Spencer5f016e22007-07-11 17:01:13 +00001337/// ProcessInputFile - Process a single input file with the specified state.
1338///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001339static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001340 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001341 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001342 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001343 FixItRewriter *FixItRewrite = 0;
1344
Ted Kremenek85888962008-10-21 00:54:44 +00001345 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001347 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1348 PP.getFileManager(), PP.getLangOptions(),
1349 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001350
1351 if (!Consumer) {
1352 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001353 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001354 return;
1355 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001356
Ted Kremenekdb094a22007-12-05 18:27:04 +00001357 break;
1358
Chris Lattnerc106c102008-10-12 05:03:36 +00001359 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001360 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001361 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001362 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001363 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001364 RawLex.SetKeepWhitespaceMode(true);
1365
1366 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001367 RawLex.LexFromRawLexer(RawTok);
1368 while (RawTok.isNot(tok::eof)) {
1369 PP.DumpToken(RawTok, true);
1370 fprintf(stderr, "\n");
1371 RawLex.LexFromRawLexer(RawTok);
1372 }
1373 ClearSourceMgr = true;
1374 break;
1375 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001377 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001378 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001379 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001380 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 do {
1382 PP.Lex(Tok);
1383 PP.DumpToken(Tok, true);
1384 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001385 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001386 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 break;
1388 }
1389 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001390 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001391 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001393 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 do {
1395 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001396 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001397 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 break;
1399 }
Ted Kremenek85888962008-10-21 00:54:44 +00001400
1401 case GeneratePCH: {
Chris Lattner47099742009-02-18 01:51:21 +00001402 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001403 CacheTokens(PP, OutputFile);
1404 ClearSourceMgr = true;
1405 break;
1406 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001407
Chris Lattner47099742009-02-18 01:51:21 +00001408 case PrintPreprocessedInput: { // -E mode.
1409 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001410 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001411 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 break;
Chris Lattner47099742009-02-18 01:51:21 +00001413 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001414
Chris Lattner47099742009-02-18 01:51:21 +00001415 case ParseNoop: { // -parse-noop
1416 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001417 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001418 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 break;
Chris Lattner47099742009-02-18 01:51:21 +00001420 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001421
Chris Lattner47099742009-02-18 01:51:21 +00001422 case ParsePrintCallbacks: {
1423 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001424 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001425 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 break;
Chris Lattner47099742009-02-18 01:51:21 +00001427 }
1428
1429 case ParseSyntaxOnly: { // -fsyntax-only
1430 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001431 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001432 break;
Chris Lattner47099742009-02-18 01:51:21 +00001433 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001434
1435 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001436 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001437 ClearSourceMgr = true;
1438 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001439
Chris Lattner47099742009-02-18 01:51:21 +00001440 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001441 DoRewriteTest(PP, InFile, OutputFile);
1442 ClearSourceMgr = true;
1443 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001444 }
Douglas Gregor558cb562009-04-02 01:08:08 +00001445
1446 case FixIt:
1447 llvm::TimeRegion Timer(ClangFrontendTimer);
1448 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001449 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Douglas Gregor558cb562009-04-02 01:08:08 +00001450 PP.getSourceManager());
Douglas Gregor558cb562009-04-02 01:08:08 +00001451 break;
Chris Lattner47099742009-02-18 01:51:21 +00001452 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001453
1454 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001455 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001456
1457 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1458 PP.getSourceManager(),
1459 PP.getTargetInfo(),
1460 PP.getIdentifierTable(),
1461 PP.getSelectorTable(),
1462 /* FreeMemory = */ !DisableFree));
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001463
1464
Chris Lattner3599dbe2009-03-28 04:13:34 +00001465 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001466
Douglas Gregor558cb562009-04-02 01:08:08 +00001467 if (FixItRewrite)
1468 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1469
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001470 // If in -disable-free mode, don't deallocate these when they go out of
1471 // scope.
Chris Lattner3599dbe2009-03-28 04:13:34 +00001472 if (DisableFree)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001473 ContextOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001474 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001475
1476 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001477 if (CheckDiagnostics(PP))
1478 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001479
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001481 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 PP.PrintStats();
1483 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001484 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001485 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 fprintf(stderr, "\n");
1487 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001488
1489 // For a multi-file compilation, some things are ok with nuking the source
1490 // manager tables, other require stable fileid/macroid's across multiple
1491 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001492 if (ClearSourceMgr)
1493 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001494
1495 if (DisableFree)
1496 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001497}
1498
Ted Kremenek20e97482007-12-12 23:41:08 +00001499static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1500 FileManager& FileMgr) {
1501
1502 if (VerifyDiagnostics) {
1503 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1504 exit (1);
1505 }
1506
1507 llvm::sys::Path Filename(InFile);
1508
1509 if (!Filename.isValid()) {
1510 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1511 exit (1);
1512 }
1513
Chris Lattner557c5b12009-03-28 04:27:18 +00001514 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner5f737cc2009-03-28 03:49:26 +00001515
1516 // Create the memory buffer that contains the contents of the file.
1517 llvm::OwningPtr<llvm::MemoryBuffer>
1518 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1519
1520 if (MBuffer)
Chris Lattner557c5b12009-03-28 04:27:18 +00001521 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001522
Chris Lattner557c5b12009-03-28 04:27:18 +00001523 if (!Ctx) {
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001524 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1525 InFile.c_str());
1526 exit (1);
1527 }
1528
Ted Kremenek63ea8632007-12-19 19:27:38 +00001529 // Observe that we use the source file name stored in the deserialized
1530 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001531 llvm::OwningPtr<ASTConsumer>
Chris Lattner557c5b12009-03-28 04:27:18 +00001532 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001533 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001534
Ted Kremenek20e97482007-12-12 23:41:08 +00001535 if (!Consumer) {
1536 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1537 exit (1);
1538 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001539
Chris Lattner557c5b12009-03-28 04:27:18 +00001540 Consumer->Initialize(*Ctx);
Nico Weber7bfaaae2008-08-10 19:59:06 +00001541
Chris Lattnere66b65c2008-02-06 01:42:25 +00001542 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattner557c5b12009-03-28 04:27:18 +00001543 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1544 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1545 I != E; ++I)
Chris Lattner682bf922009-03-29 16:50:03 +00001546 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek20e97482007-12-12 23:41:08 +00001547}
1548
1549
Reid Spencer5f016e22007-07-11 17:01:13 +00001550static llvm::cl::list<std::string>
1551InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1552
Ted Kremenek20e97482007-12-12 23:41:08 +00001553static bool isSerializedFile(const std::string& InFile) {
1554 if (InFile.size() < 4)
1555 return false;
1556
1557 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001558 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001559}
1560
Reid Spencer5f016e22007-07-11 17:01:13 +00001561
1562int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001564 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001565 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001566 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001567
Chris Lattner47099742009-02-18 01:51:21 +00001568 if (TimeReport)
1569 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1570
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 // If no input was specified, read from stdin.
1572 if (InputFilenames.empty())
1573 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001574
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 // Create a file manager object to provide access to and cache the filesystem.
1576 FileManager FileMgr;
1577
Ted Kremenek31e703b2007-12-11 23:28:38 +00001578 // Create the diagnostic client for reporting errors or for
1579 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001580 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001581
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001582 if (!VerifyDiagnostics) {
1583 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001584 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1585 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001586 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001587 !NoShowLocation,
1588 PrintSourceRangeInfo);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001589 } else {
1590 // When checking diagnostics, just buffer them up.
1591 TextDiagClient = new TextDiagnosticBuffer();
1592
1593 if (InputFilenames.size() != 1) {
1594 fprintf(stderr,
1595 "-verify only works on single input files for now.\n");
1596 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 }
1598 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001599
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001601 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1602 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001603 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001604 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001605
Chris Lattner4f037832007-12-05 23:24:17 +00001606 // -I- is a deprecated GCC feature, scan for it and reject it.
1607 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1608 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001609 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001610 I_dirs.erase(I_dirs.begin()+i);
1611 --i;
1612 }
1613 }
Chris Lattner11215192008-03-14 06:12:05 +00001614
1615 // Get information about the target being compiled for.
1616 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001617 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1618
Chris Lattner11215192008-03-14 06:12:05 +00001619 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001620 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1621 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001622 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001623 }
Chris Lattner4f037832007-12-05 23:24:17 +00001624
Daniel Dunbard4270232009-01-20 23:17:32 +00001625 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001626 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001627
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001628 llvm::OwningPtr<SourceManager> SourceMgr;
1629
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001631 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001632
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001633 if (isSerializedFile(InFile)) {
1634 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001635 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001636 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001637 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001638
1639 /// Create a SourceManager object. This tracks and owns all the file
1640 /// buffers allocated to a translation unit.
1641 if (!SourceMgr)
1642 SourceMgr.reset(new SourceManager());
1643 else
1644 SourceMgr->clearIDTables();
1645
1646 // Initialize language options, inferring file types from input filenames.
1647 LangOptions LangInfo;
1648 InitializeBaseLanguage();
1649 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001650 InitializeLangOptions(LangInfo, LK);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001651 InitializeGCMode(LangInfo);
Mike Stump2add4732009-04-01 20:28:16 +00001652 InitializeOverflowChecking(LangInfo);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001653 InitializeLanguageStandard(LangInfo, LK, Target.get());
1654
1655 // Process the -I options and set them in the HeaderInfo.
1656 HeaderSearch HeaderInfo(FileMgr);
1657
1658 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1659
1660 // Set up the preprocessor with these options.
1661 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1662 *SourceMgr.get(), HeaderInfo);
1663
1664 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1665
1666 if (!PP)
1667 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001668
Chris Lattnerf63aea32009-03-04 21:40:56 +00001669 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1670 // always reset to using TextDiagClient.
1671 llvm::OwningPtr<DiagnosticClient> TmpClient;
1672
1673 if (!HTMLDiag.empty()) {
1674 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1675 &PPFactory));
1676 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001677 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001678 else
1679 Diags.setClient(TextDiagClient);
1680
1681 // Process the source file.
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001682 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001683
1684 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 }
Chris Lattner11215192008-03-14 06:12:05 +00001686
Mike Stump007f2a92009-01-28 02:43:35 +00001687 if (Verbose)
1688 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1689 " hosted on " LLVM_HOSTTRIPLE "\n");
1690
Ted Kremenek7a08e282008-08-07 18:13:12 +00001691 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1693 (NumDiagnostics == 1 ? "" : "s"));
1694
1695 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 FileMgr.PrintStats();
1697 fprintf(stderr, "\n");
1698 }
1699
Daniel Dunbar276373d2008-10-27 22:10:13 +00001700 // If verifying diagnostics and we reached here, all is well.
1701 if (VerifyDiagnostics)
1702 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001703
1704 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001705
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001706 // Managed static deconstruction. Useful for making things like
1707 // -time-passes usable.
1708 llvm::llvm_shutdown();
1709
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001710 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001711}