blob: 58538067bc4eecadc7e0b17ce97b053f588be26a [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"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000029#include "clang/Frontend/InitHeaderSearch.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000030#include "clang/Frontend/PathDiagnosticClients.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000031#include "clang/Frontend/TextDiagnosticBuffer.h"
32#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000033#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000034#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000035#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000036#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000037#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000038#include "clang/AST/ASTContext.h"
39#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000040#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041#include "clang/Parse/Parser.h"
42#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000043#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000044#include "clang/Basic/FileManager.h"
45#include "clang/Basic/SourceManager.h"
46#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000047#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000048#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000049#include "llvm/ADT/StringExtras.h"
50#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000051#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000052#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000053#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000054#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000055#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000056#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000057#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000058#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000059#include "llvm/System/Signals.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000060using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// Global options.
64//===----------------------------------------------------------------------===//
65
Chris Lattner47099742009-02-18 01:51:21 +000066/// ClangFrontendTimer - The front-end activities should charge time to it with
67/// TimeRegion. The -ftime-report option controls whether this will do
68/// anything.
69llvm::Timer *ClangFrontendTimer = 0;
70
Daniel Dunbard3db4012008-10-16 16:54:18 +000071static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +000072
Reid Spencer5f016e22007-07-11 17:01:13 +000073static llvm::cl::opt<bool>
74Verbose("v", llvm::cl::desc("Enable verbose output"));
75static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000076Stats("print-stats",
77 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000078static llvm::cl::opt<bool>
79DisableFree("disable-free",
80 llvm::cl::desc("Disable freeing of memory on exit"),
81 llvm::cl::init(false));
Reid Spencer5f016e22007-07-11 17:01:13 +000082
83enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000084 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000085 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000086 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000087 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +000088 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000089 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000090 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000091 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +000092 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000093 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000094 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000095 ASTPrint, // Parse ASTs and print them.
96 ASTDump, // Parse ASTs and dump them.
97 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +000098 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000099 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 ParsePrintCallbacks, // Parse and print each callback.
101 ParseSyntaxOnly, // Parse and perform semantic analysis.
102 ParseNoop, // Parse with noop callbacks.
103 RunPreprocessorOnly, // Just lex, no output.
104 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000105 DumpTokens, // Dump out preprocessed tokens.
106 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000107 RunAnalysis, // Run one or more source code analyses.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000108 GeneratePCH, // Generate precompiled header.
109 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000110};
111
112static llvm::cl::opt<ProgActions>
113ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
114 llvm::cl::init(ParseSyntaxOnly),
115 llvm::cl::values(
116 clEnumValN(RunPreprocessorOnly, "Eonly",
117 "Just run preprocessor, no output (for timings)"),
118 clEnumValN(PrintPreprocessedInput, "E",
119 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000120 clEnumValN(DumpRawTokens, "dump-raw-tokens",
121 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000122 clEnumValN(RunAnalysis, "analyze",
123 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000124 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 "Run preprocessor, dump internal rep of tokens"),
126 clEnumValN(ParseNoop, "parse-noop",
127 "Run parser with noop callbacks (for timings)"),
128 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
129 "Run parser and perform semantic analysis"),
130 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
131 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000132 clEnumValN(EmitHTML, "emit-html",
133 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000134 clEnumValN(ASTPrint, "ast-print",
135 "Build ASTs and then pretty-print them"),
136 clEnumValN(ASTDump, "ast-dump",
137 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000138 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000139 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000140 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000141 "Print DeclContexts and their Decls"),
142 clEnumValN(GeneratePCH, "emit-pth",
143 "Generate pre-tokenized header file"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000144 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000145 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000146 clEnumValN(EmitAssembly, "S",
147 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000148 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000149 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000150 clEnumValN(EmitBC, "emit-llvm-bc",
151 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000152 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
153 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000154 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000155 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000156 clEnumValN(RewriteTest, "rewrite-test",
157 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000158 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000159 "Rewrite ObjC into C (code rewriter example)"),
160 clEnumValN(RewriteMacros, "rewrite-macros",
161 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000162 clEnumValN(RewriteBlocks, "rewrite-blocks",
163 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 clEnumValEnd));
165
Ted Kremenekccc76472007-12-19 19:47:59 +0000166
167static llvm::cl::opt<std::string>
168OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000169 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000170 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000171
Ted Kremenekc2e72992008-12-02 19:57:31 +0000172
173//===----------------------------------------------------------------------===//
174// PTH.
175//===----------------------------------------------------------------------===//
176
177static llvm::cl::opt<std::string>
178TokenCache("token-cache", llvm::cl::value_desc("path"),
179 llvm::cl::desc("Use specified token cache file"));
180
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000181//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000182// Diagnostic Options
183//===----------------------------------------------------------------------===//
184
Ted Kremenek41193e42007-09-26 19:42:19 +0000185static llvm::cl::opt<bool>
186VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000187 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000188
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000189static llvm::cl::opt<std::string>
190HTMLDiag("html-diags",
191 llvm::cl::desc("Generate HTML to report diagnostics"),
192 llvm::cl::value_desc("HTML directory"));
193
Nico Weberfd54ebc2008-08-05 23:33:20 +0000194static llvm::cl::opt<bool>
195NoShowColumn("fno-show-column",
196 llvm::cl::desc("Do not include column number on diagnostics"));
197
198static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000199NoShowLocation("fno-show-source-location",
200 llvm::cl::desc("Do not include source location information with"
201 " diagnostics"));
202
203static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000204NoCaretDiagnostics("fno-caret-diagnostics",
205 llvm::cl::desc("Do not include source line and caret with"
206 " diagnostics"));
207
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000208static llvm::cl::opt<bool>
209PrintSourceRangeInfo("fprint-source-range-info",
210 llvm::cl::desc("Print source range spans in numeric form"));
211
Nico Weberfd54ebc2008-08-05 23:33:20 +0000212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000214// C++ Visualization.
215//===----------------------------------------------------------------------===//
216
217static llvm::cl::opt<std::string>
218InheritanceViewCls("cxx-inheritance-view",
219 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000220 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000221
222//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000223// Builtin Options
224//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000225
226static llvm::cl::opt<bool>
227TimeReport("ftime-report",
228 llvm::cl::desc("Print the amount of time each "
229 "phase of compilation takes"));
230
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000231static llvm::cl::opt<bool>
232Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000233 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000234 "freestanding environment"));
235
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000236static llvm::cl::opt<bool>
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000237AllowBuiltins("fbuiltin",
238 llvm::cl::desc("Disable implicit builtin knowledge of functions"),
239 llvm::cl::init(true), llvm::cl::AllowInverse);
Chris Lattner7644f072009-03-13 22:38:49 +0000240
241
242static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000243MathErrno("fmath-errno",
Chris Lattner5ea9d1b2009-02-17 00:30:31 +0000244 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner5bef8dd2009-02-17 00:35:09 +0000245 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000246
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000247//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000248// Language Options
249//===----------------------------------------------------------------------===//
250
251enum LangKind {
252 langkind_unspecified,
253 langkind_c,
254 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000255 langkind_asm_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000256 langkind_c_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 langkind_cxx,
258 langkind_cxx_cpp,
Chris Lattnerc76d8072009-02-06 06:19:20 +0000259 langkind_cxx_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 langkind_objc,
261 langkind_objc_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000262 langkind_objc_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 langkind_objcxx,
Ted Kremenekf8901912009-01-09 00:38:08 +0000264 langkind_objcxx_cpp,
265 langkind_objcxx_pch
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++"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000285 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek85888962008-10-21 00:54:44 +0000286 "Precompiled C header"),
287 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekf8901912009-01-09 00:38:08 +0000288 "Precompiled Objective-C header"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000289 clEnumValN(langkind_cxx_pch, "c++-header",
290 "Precompiled C++ header"),
Ted Kremenekf8901912009-01-09 00:38:08 +0000291 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
292 "Precompiled 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
361static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // FIXME: implement -fpreprocessed mode.
363 bool NoPreprocess = false;
Ted Kremenek85888962008-10-21 00:54:44 +0000364 bool PCH = false;
Ted Kremenekf8901912009-01-09 00:38:08 +0000365
366 // Test for 'PCH'.
367 switch (LK) {
Chris Lattnerc76d8072009-02-06 06:19:20 +0000368 default:
369 break;
370 case langkind_c_pch:
371 LK = langkind_c;
372 PCH = true;
373 break;
374 case langkind_objc_pch:
375 LK = langkind_objc;
376 PCH = true;
377 break;
378 case langkind_cxx_pch:
379 LK = langkind_cxx;
380 PCH = true;
381 break;
382 case langkind_objcxx_pch:
383 LK = langkind_objcxx;
384 PCH = true;
385 break;
Ted Kremenekf8901912009-01-09 00:38:08 +0000386 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000387
Ted Kremenek8904f152007-12-05 23:49:08 +0000388 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000390 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000391 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000392 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 case langkind_c_cpp:
394 NoPreprocess = true;
395 // FALLTHROUGH
396 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000397 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 break;
399 case langkind_cxx_cpp:
400 NoPreprocess = true;
401 // FALLTHROUGH
402 case langkind_cxx:
403 Options.CPlusPlus = 1;
404 break;
405 case langkind_objc_cpp:
406 NoPreprocess = true;
407 // FALLTHROUGH
408 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000409 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 break;
411 case langkind_objcxx_cpp:
412 NoPreprocess = true;
413 // FALLTHROUGH
414 case langkind_objcxx:
415 Options.ObjC1 = Options.ObjC2 = 1;
416 Options.CPlusPlus = 1;
417 break;
418 }
Ted Kremenek85888962008-10-21 00:54:44 +0000419
420 return PCH;
Reid Spencer5f016e22007-07-11 17:01:13 +0000421}
422
423/// LangStds - Language standards we support.
424enum LangStds {
425 lang_unspecified,
426 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000427 lang_gnu_START,
428 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000429 lang_cxx98, lang_gnucxx98,
430 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000431};
432
433static llvm::cl::opt<LangStds>
434LangStd("std", llvm::cl::desc("Language standard to compile for"),
435 llvm::cl::init(lang_unspecified),
436 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
437 clEnumValN(lang_c89, "c90", "ISO C 1990"),
438 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
439 clEnumValN(lang_c94, "iso9899:199409",
440 "ISO C 1990 with amendment 1"),
441 clEnumValN(lang_c99, "c99", "ISO C 1999"),
442// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
443 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
444// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
445 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000446 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000447 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000448 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 clEnumValN(lang_gnu99, "gnu9x",
450 "ISO C 1999 with GNU extensions"),
451 clEnumValN(lang_cxx98, "c++98",
452 "ISO C++ 1998 with amendments"),
453 clEnumValN(lang_gnucxx98, "gnu++98",
454 "ISO C++ 1998 with amendments and GNU "
455 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000456 clEnumValN(lang_cxx0x, "c++0x",
457 "Upcoming ISO C++ 200x with amendments"),
458 clEnumValN(lang_gnucxx0x, "gnu++0x",
459 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000460 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 clEnumValEnd));
462
463static llvm::cl::opt<bool>
464NoOperatorNames("fno-operator-names",
465 llvm::cl::desc("Do not treat C++ operator name keywords as "
466 "synonyms for operators"));
467
Anders Carlssonee98ac52007-10-15 02:50:23 +0000468static llvm::cl::opt<bool>
469PascalStrings("fpascal-strings",
470 llvm::cl::desc("Recognize and construct Pascal-style "
471 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000472
473static llvm::cl::opt<bool>
474MSExtensions("fms-extensions",
475 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000476 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000477
478static llvm::cl::opt<bool>
479WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000480 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000481
482static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000483NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000484 llvm::cl::desc("Disallow implicit conversions between "
485 "vectors with a different number of "
486 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000487
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000488static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000489EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
490 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
491 llvm::cl::ZeroOrMore);
492
493static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000494EnableHeinousExtensions("fheinous-gnu-extensions",
495 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
496 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
497
498static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000499ObjCNonFragileABI("fobjc-nonfragile-abi",
500 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000501
Daniel Dunbard604c402009-02-04 21:19:06 +0000502static llvm::cl::opt<bool>
503EmitAllDecls("femit-all-decls",
504 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000505
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000506// FIXME: This (and all GCC -f options) really come in -f... and
507// -fno-... forms, and additionally support automagic behavior when
508// they are not defined. For example, -fexceptions defaults to on or
509// off depending on the language. We should support this behavior in
510// some form (perhaps just add a facility for distinguishing when an
511// has its default value from when it has been set to its default
512// value).
513static llvm::cl::opt<bool>
514Exceptions("fexceptions",
515 llvm::cl::desc("Enable support for exception handling."));
516
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000517static llvm::cl::opt<bool>
518GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000519 llvm::cl::desc("Generate output compatible with the standard GNU "
520 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000521
522static llvm::cl::opt<bool>
523NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000524 llvm::cl::desc("Generate output compatible with the NeXT "
525 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000526
Ted Kremenekea644d82008-09-03 21:22:16 +0000527
528
529static llvm::cl::opt<bool>
530Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
531
532static llvm::cl::opt<bool>
533Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
534
Chris Lattner16167a62009-03-02 22:11:07 +0000535static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000536TargetFeatures("mattr", llvm::cl::CommaSeparated,
537 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
538
Douglas Gregor26dce442009-03-10 00:06:19 +0000539static llvm::cl::opt<unsigned>
540TemplateDepth("ftemplate-depth", llvm::cl::init(99),
541 llvm::cl::desc("Maximum depth of recursive template "
542 "instantiation"));
Chris Lattner16167a62009-03-02 22:11:07 +0000543
Reid Spencer5f016e22007-07-11 17:01:13 +0000544// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000545// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000546static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
547 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000548 // Allow the target to set the default the langauge options as it sees fit.
549 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000550
Chris Lattner6328cc32009-03-03 19:56:18 +0000551 // If there are any -mattr options, pass them to the target for validation and
552 // processing. The driver should have already consolidated all the
553 // target-feature settings and passed them to us in the -mattr list. The
554 // -mattr list is treated by the code generator as a diff against the -mcpu
555 // setting, but the driver should pass all enabled options as "+" settings.
556 // This means that the target should only look at + settings.
557 if (!TargetFeatures.empty()
558 // FIXME: The driver is not quite yet ready for this.
559 && 0) {
Chris Lattner16167a62009-03-02 22:11:07 +0000560 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000561 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
562 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000563 if (Opt != -1) {
564 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000565 fprintf(stderr, "invalid feature '%s'\n",
566 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000567 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000568 fprintf(stderr, "feature '%s': %s\n",
569 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000570 exit(1);
571 }
572 }
573
Ted Kremenekea644d82008-09-03 21:22:16 +0000574 if (Ansi) // "The -ansi option is equivalent to -std=c89."
575 LangStd = lang_c89;
576
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 if (LangStd == lang_unspecified) {
578 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000579 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000580 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000582 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 case langkind_c_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000584 case langkind_c_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000585 case langkind_objc:
586 case langkind_objc_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000587 case langkind_objc_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000588 LangStd = lang_gnu99;
589 break;
590 case langkind_cxx:
591 case langkind_cxx_cpp:
Ted Kremenekab56c5d2009-03-19 18:21:42 +0000592 case langkind_cxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 case langkind_objcxx:
594 case langkind_objcxx_cpp:
Ted Kremenekf8901912009-01-09 00:38:08 +0000595 case langkind_objcxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000596 LangStd = lang_gnucxx98;
597 break;
598 }
599 }
600
601 switch (LangStd) {
602 default: assert(0 && "Unknown language standard!");
603
604 // Fall through from newer standards to older ones. This isn't really right.
605 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000606 case lang_gnucxx0x:
607 case lang_cxx0x:
608 Options.CPlusPlus0x = 1;
609 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000610 case lang_gnucxx98:
611 case lang_cxx98:
612 Options.CPlusPlus = 1;
613 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000614 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 // FALL THROUGH.
616 case lang_gnu99:
617 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000618 Options.C99 = 1;
619 Options.HexFloats = 1;
620 // FALL THROUGH.
621 case lang_gnu89:
622 Options.BCPLComment = 1; // Only for C99/C++.
623 // FALL THROUGH.
624 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000625 Options.Digraphs = 1; // C94, C99, C++.
626 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000627 case lang_c89:
628 break;
629 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000630
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000631 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
632 Options.GNUMode = LangStd >= lang_gnu_START;
633
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000634 if (Options.CPlusPlus) {
635 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000636 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000637 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000638
Chris Lattnerd658b562008-04-05 06:32:51 +0000639 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
640 Options.ImplicitInt = 1;
641 else
642 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000643
644 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
645 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000646 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000647 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000648 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000649
Chris Lattner802db9b2008-12-05 00:10:44 +0000650 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
651 // even if they are normally on for the target. In GNU modes (e.g.
652 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000653 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000654 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000655 Options.Blocks = 0;
656
Daniel Dunbar85c49102009-03-15 00:11:28 +0000657 // Never accept '$' in identifiers when preprocessing assembler.
658 if (LK != langkind_asm_cpp)
659 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000660 if (PascalStrings.getPosition())
661 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000662 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000663 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000664 if (NoLaxVectorConversions.getPosition())
665 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000666 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000667 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000668 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000669
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000670 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000671 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000672 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000673 Options.Freestanding = Options.NoBuiltin = 1;
674
Chris Lattner810f6d52009-03-13 17:38:01 +0000675 if (EnableHeinousExtensions)
676 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000677
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000678 Options.MathErrno = MathErrno;
679
Douglas Gregor26dce442009-03-10 00:06:19 +0000680 Options.InstantiationDepth = TemplateDepth;
681
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000682 // Override the default runtime if the user requested it.
683 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000684 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000685 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000686 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000687
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000688 if (ObjCNonFragileABI)
689 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000690
691 if (EmitAllDecls)
692 Options.EmitAllDecls = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000693}
694
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000695static llvm::cl::opt<bool>
696ObjCExclusiveGC("fobjc-gc-only",
697 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000698 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000699
700static llvm::cl::opt<bool>
701ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000702 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000703
704void InitializeGCMode(LangOptions &Options) {
705 if (ObjCExclusiveGC)
706 Options.setGCMode(LangOptions::GCOnly);
707 else if (ObjCEnableGC)
708 Options.setGCMode(LangOptions::HybridGC);
709}
710
Reid Spencer5f016e22007-07-11 17:01:13 +0000711//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000712// Target Triple Processing.
713//===----------------------------------------------------------------------===//
714
715static llvm::cl::opt<std::string>
716TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000717 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000718
Chris Lattner42e67372008-03-05 01:18:20 +0000719static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000720Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000721
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000722static llvm::cl::opt<std::string>
723MacOSVersionMin("mmacosx-version-min",
724 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
725
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000726// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
727// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000728
729// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000730static void HandleMacOSVersionMin(std::string &Triple) {
731 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
732 if (DarwinDashIdx == std::string::npos) {
733 fprintf(stderr,
734 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
735 exit(1);
736 }
737 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
738
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000739 // Remove the number.
740 Triple.resize(DarwinNumIdx);
741
742 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
743 bool MacOSVersionMinIsInvalid = false;
744 int VersionNum = 0;
745 if (MacOSVersionMin.size() < 4 ||
746 MacOSVersionMin.substr(0, 3) != "10." ||
747 !isdigit(MacOSVersionMin[3])) {
748 MacOSVersionMinIsInvalid = true;
749 } else {
750 const char *Start = MacOSVersionMin.c_str()+3;
751 char *End = 0;
752 VersionNum = (int)strtol(Start, &End, 10);
753
Chris Lattner079f2c462008-09-30 20:30:12 +0000754 // The version number must be in the range 0-9.
755 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
756
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000757 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
758 Triple += llvm::itostr(VersionNum+4);
759
Chris Lattner079f2c462008-09-30 20:30:12 +0000760 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
761 // Add the period piece (.7) to the end of the triple. This gives us
762 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000763 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000764 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
765 MacOSVersionMinIsInvalid = true;
766 }
767 }
768
769 if (MacOSVersionMinIsInvalid) {
770 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000771 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000772 MacOSVersionMin.c_str());
773 exit(1);
774 }
775}
776
777/// CreateTargetTriple - Process the various options that affect the target
778/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000779static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000780 // Initialize base triple. If a -triple option has been specified, use
781 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000782 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000783 if (Triple.empty())
784 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +0000785
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000786 // If -arch foo was specified, remove the architecture from the triple we have
787 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000788
789 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000790 if (!Arch.empty()) {
791 // Decompose the base triple into "arch" and suffix.
792 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000793
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000794 if (FirstDashIdx == std::string::npos) {
795 fprintf(stderr,
796 "Malformed target triple: \"%s\" ('-' could not be found).\n",
797 Triple.c_str());
798 exit(1);
799 }
Chris Lattner37e217c2009-03-24 16:18:41 +0000800
801 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
802 if (Arch == "ppc")
803 Arch = "powerpc";
804 else if (Arch == "ppc64")
805 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +0000806
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000807 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
808 }
809
810 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
811 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000812 if (!MacOSVersionMin.empty())
813 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000814
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000815 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000816}
817
818//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000819// Preprocessor Initialization
820//===----------------------------------------------------------------------===//
821
822// FIXME: Preprocessor builtins to support.
823// -A... - Play with #assertions
824// -undef - Undefine all predefined macros
825
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000826// FIXME: -imacros
827
Reid Spencer5f016e22007-07-11 17:01:13 +0000828static llvm::cl::list<std::string>
829D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
830 llvm::cl::desc("Predefine the specified macro"));
831static llvm::cl::list<std::string>
832U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
833 llvm::cl::desc("Undefine the specified macro"));
834
Chris Lattner64299f82008-01-10 01:53:41 +0000835static llvm::cl::list<std::string>
836ImplicitIncludes("include", llvm::cl::value_desc("file"),
837 llvm::cl::desc("Include file before parsing"));
838
Ted Kremenek748d5d62009-03-20 00:26:38 +0000839static llvm::cl::opt<std::string>
840ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
841 llvm::cl::desc("Include file before parsing"));
842
Reid Spencer5f016e22007-07-11 17:01:13 +0000843// Append a #define line to Buf for Macro. Macro should be of the form XXX,
844// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
845// "#define XXX Y z W". To get a #define with no value, use "XXX=".
846static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
847 const char *Command = "#define ") {
848 Buf.insert(Buf.end(), Command, Command+strlen(Command));
849 if (const char *Equal = strchr(Macro, '=')) {
850 // Turn the = into ' '.
851 Buf.insert(Buf.end(), Macro, Equal);
852 Buf.push_back(' ');
853 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
854 } else {
855 // Push "macroname 1".
856 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
857 Buf.push_back(' ');
858 Buf.push_back('1');
859 }
860 Buf.push_back('\n');
861}
862
Chris Lattner64299f82008-01-10 01:53:41 +0000863/// AddImplicitInclude - Add an implicit #include of the specified file to the
864/// predefines buffer.
865static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
866 const char *Inc = "#include \"";
867 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
868 Buf.insert(Buf.end(), File.begin(), File.end());
869 Buf.push_back('"');
870 Buf.push_back('\n');
871}
872
Ted Kremenek748d5d62009-03-20 00:26:38 +0000873/// AddImplicitIncludePTH - Add an implicit #include using the original file
874/// used to generate a PTH cache.
875static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
876 PTHManager *P = PP.getPTHManager();
877 assert(P && "No PTHManager.");
878 const char *OriginalFile = P->getOriginalSourceFile();
879
880 if (!OriginalFile) {
881 assert(!ImplicitIncludePTH.empty());
882 fprintf(stderr, "error: PTH file '%s' does not designate an original "
883 "source header file for -include-pth\n",
884 ImplicitIncludePTH.c_str());
885 exit (1);
886 }
887
888 AddImplicitInclude(Buf, OriginalFile);
889}
Reid Spencer5f016e22007-07-11 17:01:13 +0000890
Chris Lattner53b0dab2007-10-09 22:10:18 +0000891/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000892/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000893///
Chris Lattner51574ea2008-04-19 23:25:44 +0000894static bool InitializePreprocessor(Preprocessor &PP,
895 bool InitializeSourceMgr,
896 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000897 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000898
Chris Lattner53b0dab2007-10-09 22:10:18 +0000899 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000900 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000901
902 if (InitializeSourceMgr) {
903 if (InFile != "-") {
904 const FileEntry *File = FileMgr.getFile(InFile);
905 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +0000906 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000907 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
908 << InFile.c_str();
Chris Lattner51574ea2008-04-19 23:25:44 +0000909 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000910 }
911 } else {
912 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar56743882009-03-21 17:56:30 +0000913
914 // If stdin was empty, SB is null. Cons up an empty memory
915 // buffer now.
916 if (!SB) {
917 const char *EmptyStr = "";
918 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
919 }
920
921 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000922 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000923 PP.getDiagnostics().Report(FullSourceLoc(),
924 diag::err_fe_error_reading_stdin);
Chris Lattner51574ea2008-04-19 23:25:44 +0000925 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000926 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000927 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000929
Chris Lattneraa391972008-04-19 23:09:31 +0000930 std::vector<char> PredefineBuffer;
931
Reid Spencer5f016e22007-07-11 17:01:13 +0000932 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000933 unsigned d = 0, D = D_macros.size();
934 unsigned u = 0, U = U_macros.size();
935 while (d < D || u < U) {
936 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
937 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
938 else
939 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
940 }
941
Chris Lattner64299f82008-01-10 01:53:41 +0000942 // FIXME: Read any files specified by -imacros.
943
Ted Kremenek748d5d62009-03-20 00:26:38 +0000944 // Add implicit #includes from -include and -include-pth.
945 bool handledPTH = ImplicitIncludePTH.empty();
946 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc53b60a2009-03-20 00:40:03 +0000947 if (!handledPTH &&
948 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek748d5d62009-03-20 00:26:38 +0000949 AddImplicitIncludePTH(PredefineBuffer, PP);
950 handledPTH = true;
951 }
952
Chris Lattner64299f82008-01-10 01:53:41 +0000953 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek748d5d62009-03-20 00:26:38 +0000954 }
955 if (!handledPTH && !ImplicitIncludePTH.empty())
956 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000957
Chris Lattneraa391972008-04-19 23:09:31 +0000958 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000959 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000960 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000961
962 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000963 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000964}
965
966//===----------------------------------------------------------------------===//
967// Preprocessor include path information.
968//===----------------------------------------------------------------------===//
969
970// This tool exports a large number of command line options to control how the
971// preprocessor searches for header files. At root, however, the Preprocessor
972// object takes a very simple interface: a list of directories to search for
973//
974// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000975// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000976//
Reid Spencer5f016e22007-07-11 17:01:13 +0000977
978static llvm::cl::opt<bool>
979nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
980
981// Various command line options. These four add directories to each chain.
982static llvm::cl::list<std::string>
983F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
984 llvm::cl::desc("Add directory to framework include search path"));
985static llvm::cl::list<std::string>
986I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
987 llvm::cl::desc("Add directory to include search path"));
988static llvm::cl::list<std::string>
989idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
990 llvm::cl::desc("Add directory to AFTER include search path"));
991static llvm::cl::list<std::string>
992iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
993 llvm::cl::desc("Add directory to QUOTE include search path"));
994static llvm::cl::list<std::string>
995isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
996 llvm::cl::desc("Add directory to SYSTEM include search path"));
997
998// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
999static llvm::cl::list<std::string>
1000iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1001 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1002static llvm::cl::list<std::string>
1003iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1004 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1005static llvm::cl::list<std::string>
1006iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1007 llvm::cl::Prefix,
1008 llvm::cl::desc("Set directory to include search path with prefix"));
1009
Chris Lattner0c946412007-08-26 17:47:35 +00001010static llvm::cl::opt<std::string>
1011isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1012 llvm::cl::desc("Set the system root directory (usually /)"));
1013
Reid Spencer5f016e22007-07-11 17:01:13 +00001014// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001015
Reid Spencer5f016e22007-07-11 17:01:13 +00001016/// InitializeIncludePaths - Process the -I options and set them in the
1017/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001018void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1019 FileManager &FM, const LangOptions &Lang) {
1020 InitHeaderSearch Init(Headers, Verbose, isysroot);
1021
Ted Kremenekf3721112008-05-31 00:27:00 +00001022 // Handle -I... and -F... options, walking the lists in parallel.
1023 unsigned Iidx = 0, Fidx = 0;
1024 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1025 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001026 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001027 ++Iidx;
1028 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001029 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001030 ++Fidx;
1031 }
1032 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001033
Ted Kremenekf3721112008-05-31 00:27:00 +00001034 // Consume what's left from whatever list was longer.
1035 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001036 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001037 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001038 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001039
1040 // Handle -idirafter... options.
1041 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001042 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1043 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001044
1045 // Handle -iquote... options.
1046 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001047 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001048
1049 // Handle -isystem... options.
1050 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001051 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001052
1053 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1054 // parallel, processing the values in order of occurance to get the right
1055 // prefixes.
1056 {
1057 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1058 unsigned iprefix_idx = 0;
1059 unsigned iwithprefix_idx = 0;
1060 unsigned iwithprefixbefore_idx = 0;
1061 bool iprefix_done = iprefix_vals.empty();
1062 bool iwithprefix_done = iwithprefix_vals.empty();
1063 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1064 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1065 if (!iprefix_done &&
1066 (iwithprefix_done ||
1067 iprefix_vals.getPosition(iprefix_idx) <
1068 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1069 (iwithprefixbefore_done ||
1070 iprefix_vals.getPosition(iprefix_idx) <
1071 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1072 Prefix = iprefix_vals[iprefix_idx];
1073 ++iprefix_idx;
1074 iprefix_done = iprefix_idx == iprefix_vals.size();
1075 } else if (!iwithprefix_done &&
1076 (iwithprefixbefore_done ||
1077 iwithprefix_vals.getPosition(iwithprefix_idx) <
1078 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001079 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1080 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001081 ++iwithprefix_idx;
1082 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1083 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001084 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1085 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 ++iwithprefixbefore_idx;
1087 iwithprefixbefore_done =
1088 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1089 }
1090 }
1091 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001092
Nico Weber0fca0222008-08-22 09:25:22 +00001093 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001094
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001095 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001096 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001097 llvm::sys::Path::GetMainExecutable(Argv0,
1098 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001099 if (!MainExecutablePath.isEmpty()) {
1100 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1101 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001102
1103 // Get foo/lib/clang/1.0/include
1104 //
1105 // FIXME: Don't embed version here.
1106 MainExecutablePath.appendComponent("lib");
1107 MainExecutablePath.appendComponent("clang");
1108 MainExecutablePath.appendComponent("1.0");
1109 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001110
1111 // We pass true to ignore sysroot so that we *always* look for clang headers
1112 // relative to our executable, never relative to -isysroot.
1113 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1114 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001115 }
1116
Nico Weber0fca0222008-08-22 09:25:22 +00001117 if (!nostdinc)
1118 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001119
1120 // Now that we have collected all of the include paths, merge them all
1121 // together and tell the preprocessor about them.
1122
Nico Weber0fca0222008-08-22 09:25:22 +00001123 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001124}
1125
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001126//===----------------------------------------------------------------------===//
1127// Driver PreprocessorFactory - For lazily generating preprocessors ...
1128//===----------------------------------------------------------------------===//
1129
1130namespace {
1131class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001132 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001133 Diagnostic &Diags;
1134 const LangOptions &LangInfo;
1135 TargetInfo &Target;
1136 SourceManager &SourceMgr;
1137 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001138 bool InitializeSourceMgr;
1139
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001140public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001141 DriverPreprocessorFactory(const std::string &infile,
1142 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001143 TargetInfo &target, SourceManager &SM,
1144 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001145 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1146 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1147
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001148
1149 virtual ~DriverPreprocessorFactory() {}
1150
1151 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001152 llvm::OwningPtr<PTHManager> PTHMgr;
1153
Ted Kremenek748d5d62009-03-20 00:26:38 +00001154 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1155 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1156 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001157 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001158 }
1159
Ted Kremenek72b1b152009-01-15 18:47:46 +00001160 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001161 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1162 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001163 PTHMgr.reset(PTHManager::Create(x, &Diags,
1164 TokenCache.empty() ? Diagnostic::Error
1165 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001166 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001167
Ted Kremenek22f0d092009-03-22 06:42:39 +00001168 if (Diags.hasErrorOccurred())
1169 exit(1);
1170
Ted Kremenek72b1b152009-01-15 18:47:46 +00001171 // Create the Preprocessor.
1172 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1173 SourceMgr, HeaderInfo,
1174 PTHMgr.get()));
1175
1176 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1177 // That argument is used as the IdentifierInfoLookup argument to
1178 // IdentifierTable's ctor.
1179 if (PTHMgr) {
1180 PTHMgr->setPreprocessor(PP.get());
1181 PP->setPTHManager(PTHMgr.take());
1182 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001183
Chris Lattner51574ea2008-04-19 23:25:44 +00001184 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001185 return NULL;
1186 }
1187
Daniel Dunbar750c3582008-10-24 22:12:41 +00001188 /// FIXME: PP can only handle one callback
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001189 if (ProgAction != PrintPreprocessedInput) {
1190 std::string ErrStr;
1191 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1192 if (!DFG && !ErrStr.empty()) {
1193 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar750c3582008-10-24 22:12:41 +00001194 return NULL;
1195 }
1196 }
1197
Ted Kremenek339b9c22008-04-17 22:31:54 +00001198 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001199 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001200 }
1201};
1202}
Reid Spencer5f016e22007-07-11 17:01:13 +00001203
Reid Spencer5f016e22007-07-11 17:01:13 +00001204//===----------------------------------------------------------------------===//
1205// Basic Parser driver
1206//===----------------------------------------------------------------------===//
1207
Chris Lattner51574ea2008-04-19 23:25:44 +00001208static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001209 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001210 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001211
1212 // Parsing the specified input file.
1213 P.ParseTranslationUnit();
1214 delete PA;
1215}
1216
1217//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001218// Code generation options
1219//===----------------------------------------------------------------------===//
1220
1221static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001222GenerateDebugInfo("g",
1223 llvm::cl::desc("Generate source level debug information"));
1224
1225static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00001226OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbar70f92432008-10-23 05:50:47 +00001227
Chris Lattnerbd360642009-03-26 05:00:52 +00001228static llvm::cl::opt<bool>
1229NoCommon("fno-common",
Mike Stump1c9b7422009-03-27 20:15:22 +00001230 llvm::cl::desc("Compile common globals like normal definitions"),
Chris Lattner925a7042009-03-28 02:12:08 +00001231 llvm::cl::ValueDisallowed);
Chris Lattnerbd360642009-03-26 05:00:52 +00001232
Daniel Dunbar70f92432008-10-23 05:50:47 +00001233// It might be nice to add bounds to the CommandLine library directly.
1234struct OptLevelParser : public llvm::cl::parser<unsigned> {
1235 bool parse(llvm::cl::Option &O, const char *ArgName,
1236 const std::string &Arg, unsigned &Val) {
1237 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1238 return true;
1239 // FIXME: Support -O4.
1240 if (Val > 3)
1241 return O.error(": '" + Arg + "' invalid optimization level!");
1242 return false;
1243 }
1244};
1245static llvm::cl::opt<unsigned, false, OptLevelParser>
1246OptLevel("O", llvm::cl::Prefix,
1247 llvm::cl::desc("Optimization level"),
1248 llvm::cl::init(0));
1249
Daniel Dunbara034ba82009-02-17 19:47:34 +00001250static llvm::cl::opt<std::string>
1251TargetCPU("mcpu",
1252 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1253
Chris Lattner7afae712009-03-16 18:41:18 +00001254static void InitializeCompileOptions(CompileOptions &Opts,
1255 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001256 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001257 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001258 if (OptSize) {
1259 // -Os implies -O2
1260 // FIXME: Diagnose conflicting options.
1261 Opts.OptimizationLevel = 2;
1262 } else {
1263 Opts.OptimizationLevel = OptLevel;
1264 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001265
1266 // FIXME: There are llvm-gcc options to control these selectively.
1267 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1268 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001269 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001270
1271#ifdef NDEBUG
1272 Opts.VerifyModule = 0;
1273#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001274
1275 Opts.CPU = TargetCPU;
1276 Opts.Features.insert(Opts.Features.end(),
1277 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001278
Chris Lattnerbd360642009-03-26 05:00:52 +00001279 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1280
Chris Lattner44502662009-02-18 01:23:44 +00001281 // Handle -ftime-report.
1282 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001283}
1284
1285//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001286// Main driver
1287//===----------------------------------------------------------------------===//
1288
Ted Kremenekdb094a22007-12-05 18:27:04 +00001289/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001290/// action. These consumers can operate on both ASTs that are freshly
1291/// parsed from source files as well as those deserialized from Bitcode.
1292/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001293static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001294 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001295 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001296 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001297 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001298 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001299 default:
1300 return NULL;
1301
1302 case ASTPrint:
1303 return CreateASTPrinter();
1304
1305 case ASTDump:
1306 return CreateASTDumper();
1307
1308 case ASTView:
1309 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001310
Chris Lattner8a5c8092009-02-18 01:20:05 +00001311 case PrintDeclContext:
1312 return CreateDeclContextPrinter();
1313
1314 case EmitHTML:
1315 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001316
Chris Lattner8a5c8092009-02-18 01:20:05 +00001317 case InheritanceView:
1318 return CreateInheritanceViewer(InheritanceViewCls);
1319
1320 case TestSerialization:
1321 return CreateSerializationTest(Diag, FileMgr);
1322
1323 case EmitAssembly:
1324 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001325 case EmitBC:
1326 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001327 BackendAction Act;
1328 if (ProgAction == EmitAssembly)
1329 Act = Backend_EmitAssembly;
1330 else if (ProgAction == EmitLLVM)
1331 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001332 else if (ProgAction == EmitLLVMOnly)
1333 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001334 else
1335 Act = Backend_EmitBC;
1336
1337 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001338 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001339 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001340 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001341 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001342
Chris Lattner8a5c8092009-02-18 01:20:05 +00001343 case SerializeAST:
1344 // FIXME: Allow user to tailor where the file is written.
1345 return CreateASTSerializer(InFile, OutputFile, Diag);
1346
1347 case RewriteObjC:
1348 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001349
Chris Lattner8a5c8092009-02-18 01:20:05 +00001350 case RewriteBlocks:
1351 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1352
1353 case RunAnalysis:
1354 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001355 }
1356}
1357
Reid Spencer5f016e22007-07-11 17:01:13 +00001358/// ProcessInputFile - Process a single input file with the specified state.
1359///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001360static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001361 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001362 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001363 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001364
Ted Kremenek85888962008-10-21 00:54:44 +00001365 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001367 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1368 PP.getFileManager(), PP.getLangOptions(),
1369 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001370
1371 if (!Consumer) {
1372 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001373 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001374 return;
1375 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001376
Ted Kremenekdb094a22007-12-05 18:27:04 +00001377 break;
1378
Chris Lattnerc106c102008-10-12 05:03:36 +00001379 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001380 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001381 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001382 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001383 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001384 RawLex.SetKeepWhitespaceMode(true);
1385
1386 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001387 RawLex.LexFromRawLexer(RawTok);
1388 while (RawTok.isNot(tok::eof)) {
1389 PP.DumpToken(RawTok, true);
1390 fprintf(stderr, "\n");
1391 RawLex.LexFromRawLexer(RawTok);
1392 }
1393 ClearSourceMgr = true;
1394 break;
1395 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001397 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001398 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001399 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001400 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 do {
1402 PP.Lex(Tok);
1403 PP.DumpToken(Tok, true);
1404 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001405 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001406 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 break;
1408 }
1409 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001410 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001411 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001413 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 do {
1415 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001416 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001417 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 break;
1419 }
Ted Kremenek85888962008-10-21 00:54:44 +00001420
1421 case GeneratePCH: {
Chris Lattner47099742009-02-18 01:51:21 +00001422 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001423 CacheTokens(PP, OutputFile);
1424 ClearSourceMgr = true;
1425 break;
1426 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001427
Chris Lattner47099742009-02-18 01:51:21 +00001428 case PrintPreprocessedInput: { // -E mode.
1429 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001430 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001431 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 break;
Chris Lattner47099742009-02-18 01:51:21 +00001433 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001434
Chris Lattner47099742009-02-18 01:51:21 +00001435 case ParseNoop: { // -parse-noop
1436 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001437 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001438 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 break;
Chris Lattner47099742009-02-18 01:51:21 +00001440 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001441
Chris Lattner47099742009-02-18 01:51:21 +00001442 case ParsePrintCallbacks: {
1443 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001444 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001445 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001446 break;
Chris Lattner47099742009-02-18 01:51:21 +00001447 }
1448
1449 case ParseSyntaxOnly: { // -fsyntax-only
1450 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001451 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001452 break;
Chris Lattner47099742009-02-18 01:51:21 +00001453 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001454
1455 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001456 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001457 ClearSourceMgr = true;
1458 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001459
Chris Lattner47099742009-02-18 01:51:21 +00001460 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001461 DoRewriteTest(PP, InFile, OutputFile);
1462 ClearSourceMgr = true;
1463 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001464 }
Chris Lattner47099742009-02-18 01:51:21 +00001465 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001466
1467 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001468 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001469
1470 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1471 PP.getSourceManager(),
1472 PP.getTargetInfo(),
1473 PP.getIdentifierTable(),
1474 PP.getSelectorTable(),
1475 /* FreeMemory = */ !DisableFree));
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001476
1477
Chris Lattner3599dbe2009-03-28 04:13:34 +00001478 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001479
1480 // If in -disable-free mode, don't deallocate these when they go out of
1481 // scope.
Chris Lattner3599dbe2009-03-28 04:13:34 +00001482 if (DisableFree)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001483 ContextOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001484 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001485
1486 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001487 if (CheckDiagnostics(PP))
1488 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001489
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001491 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 PP.PrintStats();
1493 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001494 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001495 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001496 fprintf(stderr, "\n");
1497 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001498
1499 // For a multi-file compilation, some things are ok with nuking the source
1500 // manager tables, other require stable fileid/macroid's across multiple
1501 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001502 if (ClearSourceMgr)
1503 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001504
1505 if (DisableFree)
1506 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001507}
1508
Ted Kremenek20e97482007-12-12 23:41:08 +00001509static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1510 FileManager& FileMgr) {
1511
1512 if (VerifyDiagnostics) {
1513 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1514 exit (1);
1515 }
1516
1517 llvm::sys::Path Filename(InFile);
1518
1519 if (!Filename.isValid()) {
1520 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1521 exit (1);
1522 }
1523
Chris Lattner557c5b12009-03-28 04:27:18 +00001524 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner5f737cc2009-03-28 03:49:26 +00001525
1526 // Create the memory buffer that contains the contents of the file.
1527 llvm::OwningPtr<llvm::MemoryBuffer>
1528 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1529
1530 if (MBuffer)
Chris Lattner557c5b12009-03-28 04:27:18 +00001531 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001532
Chris Lattner557c5b12009-03-28 04:27:18 +00001533 if (!Ctx) {
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001534 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1535 InFile.c_str());
1536 exit (1);
1537 }
1538
Ted Kremenek63ea8632007-12-19 19:27:38 +00001539 // Observe that we use the source file name stored in the deserialized
1540 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001541 llvm::OwningPtr<ASTConsumer>
Chris Lattner557c5b12009-03-28 04:27:18 +00001542 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001543 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001544
Ted Kremenek20e97482007-12-12 23:41:08 +00001545 if (!Consumer) {
1546 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1547 exit (1);
1548 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001549
Chris Lattner557c5b12009-03-28 04:27:18 +00001550 Consumer->Initialize(*Ctx);
Nico Weber7bfaaae2008-08-10 19:59:06 +00001551
Chris Lattnere66b65c2008-02-06 01:42:25 +00001552 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattner557c5b12009-03-28 04:27:18 +00001553 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1554 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1555 I != E; ++I)
Chris Lattner682bf922009-03-29 16:50:03 +00001556 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek20e97482007-12-12 23:41:08 +00001557}
1558
1559
Reid Spencer5f016e22007-07-11 17:01:13 +00001560static llvm::cl::list<std::string>
1561InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1562
Ted Kremenek20e97482007-12-12 23:41:08 +00001563static bool isSerializedFile(const std::string& InFile) {
1564 if (InFile.size() < 4)
1565 return false;
1566
1567 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001568 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001569}
1570
Reid Spencer5f016e22007-07-11 17:01:13 +00001571
1572int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001574 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001575 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001576 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001577
Chris Lattner47099742009-02-18 01:51:21 +00001578 if (TimeReport)
1579 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1580
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 // If no input was specified, read from stdin.
1582 if (InputFilenames.empty())
1583 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001584
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 // Create a file manager object to provide access to and cache the filesystem.
1586 FileManager FileMgr;
1587
Ted Kremenek31e703b2007-12-11 23:28:38 +00001588 // Create the diagnostic client for reporting errors or for
1589 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001590 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001591
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001592 if (!VerifyDiagnostics) {
1593 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001594 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1595 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001596 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001597 !NoShowLocation,
1598 PrintSourceRangeInfo);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001599 } else {
1600 // When checking diagnostics, just buffer them up.
1601 TextDiagClient = new TextDiagnosticBuffer();
1602
1603 if (InputFilenames.size() != 1) {
1604 fprintf(stderr,
1605 "-verify only works on single input files for now.\n");
1606 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 }
1608 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001609
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001611 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1612 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001613 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001614 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001615
Chris Lattner4f037832007-12-05 23:24:17 +00001616 // -I- is a deprecated GCC feature, scan for it and reject it.
1617 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1618 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001619 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001620 I_dirs.erase(I_dirs.begin()+i);
1621 --i;
1622 }
1623 }
Chris Lattner11215192008-03-14 06:12:05 +00001624
1625 // Get information about the target being compiled for.
1626 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001627 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1628
Chris Lattner11215192008-03-14 06:12:05 +00001629 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001630 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1631 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001632 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001633 }
Chris Lattner4f037832007-12-05 23:24:17 +00001634
Daniel Dunbard4270232009-01-20 23:17:32 +00001635 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001636 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001637
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001638 llvm::OwningPtr<SourceManager> SourceMgr;
1639
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001641 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001642
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001643 if (isSerializedFile(InFile)) {
1644 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001645 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001646 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001647 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001648
1649 /// Create a SourceManager object. This tracks and owns all the file
1650 /// buffers allocated to a translation unit.
1651 if (!SourceMgr)
1652 SourceMgr.reset(new SourceManager());
1653 else
1654 SourceMgr->clearIDTables();
1655
1656 // Initialize language options, inferring file types from input filenames.
1657 LangOptions LangInfo;
1658 InitializeBaseLanguage();
1659 LangKind LK = GetLanguage(InFile);
1660 bool PCH = InitializeLangOptions(LangInfo, LK);
1661 InitializeGCMode(LangInfo);
1662 InitializeLanguageStandard(LangInfo, LK, Target.get());
1663
1664 // Process the -I options and set them in the HeaderInfo.
1665 HeaderSearch HeaderInfo(FileMgr);
1666
1667 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1668
1669 // Set up the preprocessor with these options.
1670 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1671 *SourceMgr.get(), HeaderInfo);
1672
1673 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1674
1675 if (!PP)
1676 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001677
Chris Lattnerf63aea32009-03-04 21:40:56 +00001678 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1679 // always reset to using TextDiagClient.
1680 llvm::OwningPtr<DiagnosticClient> TmpClient;
1681
1682 if (!HTMLDiag.empty()) {
1683 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1684 &PPFactory));
1685 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001686 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001687 else
1688 Diags.setClient(TextDiagClient);
1689
1690 // Process the source file.
1691 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1692
1693 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 }
Chris Lattner11215192008-03-14 06:12:05 +00001695
Mike Stump007f2a92009-01-28 02:43:35 +00001696 if (Verbose)
1697 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1698 " hosted on " LLVM_HOSTTRIPLE "\n");
1699
Ted Kremenek7a08e282008-08-07 18:13:12 +00001700 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001701 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1702 (NumDiagnostics == 1 ? "" : "s"));
1703
1704 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 FileMgr.PrintStats();
1706 fprintf(stderr, "\n");
1707 }
1708
Daniel Dunbar276373d2008-10-27 22:10:13 +00001709 // If verifying diagnostics and we reached here, all is well.
1710 if (VerifyDiagnostics)
1711 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001712
1713 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001714
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001715 // Managed static deconstruction. Useful for making things like
1716 // -time-passes usable.
1717 llvm::llvm_shutdown();
1718
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001719 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001720}