blob: 767ae141488210146a67248383648fac06095403 [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"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000026#include "clang/Frontend/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"
Chris Lattnere116ccf2009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000036#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000037#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000038#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000039#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000040#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000041#include "clang/AST/ASTContext.h"
42#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000043#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000044#include "clang/Parse/Parser.h"
45#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000046#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047#include "clang/Basic/FileManager.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000050#include "clang/Basic/Version.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000051#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000052#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000053#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000054#include "llvm/ADT/StringMap.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000055#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000056#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000057#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000058#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000059#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000060#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000061#include "llvm/Support/PrettyStackTrace.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000062#include "llvm/Support/Streams.h"
Chris Lattner47099742009-02-18 01:51:21 +000063#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000064#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000065#include "llvm/System/Path.h"
Douglas Gregor44cf08e2009-05-03 03:52:38 +000066#include "llvm/System/Process.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000067#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000068#include "llvm/System/Signals.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000069#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000070#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000071# include <sys/types.h>
72#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000073
Reid Spencer5f016e22007-07-11 17:01:13 +000074using namespace clang;
75
76//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000077// Source Location Parser
78//===----------------------------------------------------------------------===//
79
80/// \brief A source location that has been parsed on the command line.
81struct ParsedSourceLocation {
82 std::string FileName;
83 unsigned Line;
84 unsigned Column;
85
86 /// \brief Try to resolve the file name of a parsed source location.
87 ///
88 /// \returns true if there was an error, false otherwise.
89 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
90};
91
92bool
93ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
94 RequestedSourceLocation &Result) {
95 const FileEntry *File = FileMgr.getFile(FileName);
96 if (!File)
97 return true;
98
99 Result.File = File;
100 Result.Line = Line;
101 Result.Column = Column;
102 return false;
103}
104
105namespace llvm {
106 namespace cl {
107 /// \brief Command-line option parser that parses source locations.
108 ///
109 /// Source locations are of the form filename:line:column.
110 template<>
111 class parser<ParsedSourceLocation>
112 : public basic_parser<ParsedSourceLocation> {
113 public:
114 bool parse(Option &O, const char *ArgName,
115 const std::string &ArgValue,
116 ParsedSourceLocation &Val);
117 };
118
119 bool
120 parser<ParsedSourceLocation>::
121 parse(Option &O, const char *ArgName, const std::string &ArgValue,
122 ParsedSourceLocation &Val) {
123 using namespace clang;
124
125 const char *ExpectedFormat
126 = "source location must be of the form filename:line:column";
127 std::string::size_type SecondColon = ArgValue.rfind(':');
128 if (SecondColon == std::string::npos) {
129 std::fprintf(stderr, "%s\n", ExpectedFormat);
130 return true;
131 }
132 char *EndPtr;
133 long Column
134 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
135 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
136 std::fprintf(stderr, "%s\n", ExpectedFormat);
137 return true;
138 }
139
140 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
141 if (SecondColon == std::string::npos) {
142 std::fprintf(stderr, "%s\n", ExpectedFormat);
143 return true;
144 }
145 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
146 if (EndPtr != ArgValue.c_str() + SecondColon) {
147 std::fprintf(stderr, "%s\n", ExpectedFormat);
148 return true;
149 }
150
151 Val.FileName = ArgValue.substr(0, FirstColon);
152 Val.Line = Line;
153 Val.Column = Column;
154 return false;
155 }
156 }
157}
158
159//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000160// Global options.
161//===----------------------------------------------------------------------===//
162
Chris Lattner47099742009-02-18 01:51:21 +0000163/// ClangFrontendTimer - The front-end activities should charge time to it with
164/// TimeRegion. The -ftime-report option controls whether this will do
165/// anything.
166llvm::Timer *ClangFrontendTimer = 0;
167
Daniel Dunbard3db4012008-10-16 16:54:18 +0000168static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000169
Reid Spencer5f016e22007-07-11 17:01:13 +0000170static llvm::cl::opt<bool>
171Verbose("v", llvm::cl::desc("Enable verbose output"));
172static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +0000173Stats("print-stats",
174 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000175static llvm::cl::opt<bool>
176DisableFree("disable-free",
177 llvm::cl::desc("Disable freeing of memory on exit"),
178 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000179static llvm::cl::opt<bool>
180EmptyInputOnly("empty-input-only",
181 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000182
183enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000184 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000185 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000186 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000187 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000188 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000189 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000190 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000192 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +0000193 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000194 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000195 ASTPrint, // Parse ASTs and print them.
196 ASTDump, // Parse ASTs and dump them.
Douglas Gregor609e72f2009-04-26 02:02:08 +0000197 ASTDumpFull, // Parse ASTs and dump them, including the
198 // contents of a PCH file.
Chris Lattner3b427b32007-10-11 00:18:28 +0000199 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000200 PrintDeclContext, // Print DeclContext and their Decls.
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 ParsePrintCallbacks, // Parse and print each callback.
202 ParseSyntaxOnly, // Parse and perform semantic analysis.
203 ParseNoop, // Parse with noop callbacks.
204 RunPreprocessorOnly, // Just lex, no output.
205 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000206 DumpTokens, // Dump out preprocessed tokens.
207 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000208 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000209 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000210 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000211 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000212};
213
214static llvm::cl::opt<ProgActions>
215ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
216 llvm::cl::init(ParseSyntaxOnly),
217 llvm::cl::values(
218 clEnumValN(RunPreprocessorOnly, "Eonly",
219 "Just run preprocessor, no output (for timings)"),
220 clEnumValN(PrintPreprocessedInput, "E",
221 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000222 clEnumValN(DumpRawTokens, "dump-raw-tokens",
223 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000224 clEnumValN(RunAnalysis, "analyze",
225 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000226 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000227 "Run preprocessor, dump internal rep of tokens"),
228 clEnumValN(ParseNoop, "parse-noop",
229 "Run parser with noop callbacks (for timings)"),
230 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
231 "Run parser and perform semantic analysis"),
232 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
233 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000234 clEnumValN(EmitHTML, "emit-html",
235 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000236 clEnumValN(ASTPrint, "ast-print",
237 "Build ASTs and then pretty-print them"),
238 clEnumValN(ASTDump, "ast-dump",
239 "Build ASTs and then debug dump them"),
Douglas Gregor609e72f2009-04-26 02:02:08 +0000240 clEnumValN(ASTDumpFull, "ast-dump-full",
241 "Build ASTs and then debug dump them, including PCH"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000242 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000243 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000244 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000245 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000246 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000247 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000248 clEnumValN(GeneratePCH, "emit-pch",
249 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000250 clEnumValN(EmitAssembly, "S",
251 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000253 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000254 clEnumValN(EmitBC, "emit-llvm-bc",
255 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000256 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
257 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000258 clEnumValN(RewriteTest, "rewrite-test",
259 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000260 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000261 "Rewrite ObjC into C (code rewriter example)"),
262 clEnumValN(RewriteMacros, "rewrite-macros",
263 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000264 clEnumValN(RewriteBlocks, "rewrite-blocks",
265 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000266 clEnumValN(FixIt, "fixit",
267 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 clEnumValEnd));
269
Ted Kremenekccc76472007-12-19 19:47:59 +0000270
271static llvm::cl::opt<std::string>
272OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000273 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000274 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000275
Ted Kremenekc2e72992008-12-02 19:57:31 +0000276
277//===----------------------------------------------------------------------===//
278// PTH.
279//===----------------------------------------------------------------------===//
280
281static llvm::cl::opt<std::string>
282TokenCache("token-cache", llvm::cl::value_desc("path"),
283 llvm::cl::desc("Use specified token cache file"));
284
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000285//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000286// Diagnostic Options
287//===----------------------------------------------------------------------===//
288
Ted Kremenek41193e42007-09-26 19:42:19 +0000289static llvm::cl::opt<bool>
290VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000291 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000292
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000293static llvm::cl::opt<std::string>
294HTMLDiag("html-diags",
295 llvm::cl::desc("Generate HTML to report diagnostics"),
296 llvm::cl::value_desc("HTML directory"));
297
Nico Weberfd54ebc2008-08-05 23:33:20 +0000298static llvm::cl::opt<bool>
299NoShowColumn("fno-show-column",
300 llvm::cl::desc("Do not include column number on diagnostics"));
301
302static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000303NoShowLocation("fno-show-source-location",
304 llvm::cl::desc("Do not include source location information with"
305 " diagnostics"));
306
307static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000308NoCaretDiagnostics("fno-caret-diagnostics",
309 llvm::cl::desc("Do not include source line and caret with"
310 " diagnostics"));
311
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000312static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000313NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
314 llvm::cl::desc("Do not include fixit information in"
315 " diagnostics"));
316
317static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000318PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
319 llvm::cl::desc("Print source range spans in numeric form"));
320
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000321static llvm::cl::opt<bool>
322PrintDiagnosticOption("fdiagnostics-show-option",
323 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000324
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000325static llvm::cl::opt<unsigned>
326MessageLength("fmessage-length",
327 llvm::cl::desc("Format message diagnostics so that they fit "
328 "within N columns or fewer, when possible."),
329 llvm::cl::value_desc("N"));
330
Reid Spencer5f016e22007-07-11 17:01:13 +0000331//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000332// C++ Visualization.
333//===----------------------------------------------------------------------===//
334
335static llvm::cl::opt<std::string>
336InheritanceViewCls("cxx-inheritance-view",
337 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000338 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000339
340//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000341// Builtin Options
342//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000343
344static llvm::cl::opt<bool>
345TimeReport("ftime-report",
346 llvm::cl::desc("Print the amount of time each "
347 "phase of compilation takes"));
348
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000349static llvm::cl::opt<bool>
350Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000351 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000352 "freestanding environment"));
353
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000354static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000355AllowBuiltins("fbuiltin", llvm::cl::init(true),
356 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000357
358
359static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000360MathErrno("fmath-errno", llvm::cl::init(true),
361 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000362
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000363//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000364// Language Options
365//===----------------------------------------------------------------------===//
366
367enum LangKind {
368 langkind_unspecified,
369 langkind_c,
370 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000371 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 langkind_cxx,
373 langkind_cxx_cpp,
374 langkind_objc,
375 langkind_objc_cpp,
376 langkind_objcxx,
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000377 langkind_objcxx_cpp
Reid Spencer5f016e22007-07-11 17:01:13 +0000378};
379
Reid Spencer5f016e22007-07-11 17:01:13 +0000380static llvm::cl::opt<LangKind>
381BaseLang("x", llvm::cl::desc("Base language to compile"),
382 llvm::cl::init(langkind_unspecified),
383 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
384 clEnumValN(langkind_cxx, "c++", "C++"),
385 clEnumValN(langkind_objc, "objective-c", "Objective C"),
386 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000387 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000389 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
390 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000392 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
394 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000395 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000397 clEnumValN(langkind_c, "c-header",
398 "C header"),
399 clEnumValN(langkind_objc, "objective-c-header",
400 "Objective-C header"),
401 clEnumValN(langkind_cxx, "c++-header",
402 "C++ header"),
403 clEnumValN(langkind_objcxx, "objective-c++-header",
404 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 clEnumValEnd));
406
407static llvm::cl::opt<bool>
408LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
409 llvm::cl::Hidden);
410static llvm::cl::opt<bool>
411LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
412 llvm::cl::Hidden);
413
Chris Lattner2c78b872009-04-14 23:22:57 +0000414static llvm::cl::opt<bool>
415ObjCExclusiveGC("fobjc-gc-only",
416 llvm::cl::desc("Use GC exclusively for Objective-C related "
417 "memory management"));
418
419static llvm::cl::opt<bool>
420ObjCEnableGC("fobjc-gc",
421 llvm::cl::desc("Enable Objective-C garbage collection"));
422
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000423static llvm::cl::opt<bool>
424ObjCEnableGCBitmapPrint("print-ivar-layout",
425 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
426
Chris Lattner2c78b872009-04-14 23:22:57 +0000427static llvm::cl::opt<LangOptions::VisibilityMode>
428SymbolVisibility("fvisibility",
429 llvm::cl::desc("Set the default symbol visibility:"),
430 llvm::cl::init(LangOptions::Default),
431 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
432 "Use default symbol visibility"),
433 clEnumValN(LangOptions::Hidden, "hidden",
434 "Use hidden symbol visibility"),
435 clEnumValN(LangOptions::Protected,"protected",
436 "Use protected symbol visibility"),
437 clEnumValEnd));
438
439static llvm::cl::opt<bool>
440OverflowChecking("ftrapv",
441 llvm::cl::desc("Trap on integer overflow"),
442 llvm::cl::init(false));
443
444
Ted Kremenek8904f152007-12-05 23:49:08 +0000445/// InitializeBaseLanguage - Handle the -x foo options.
446static void InitializeBaseLanguage() {
447 if (LangObjC)
448 BaseLang = langkind_objc;
449 else if (LangObjCXX)
450 BaseLang = langkind_objcxx;
451}
452
453static LangKind GetLanguage(const std::string &Filename) {
454 if (BaseLang != langkind_unspecified)
455 return BaseLang;
456
457 std::string::size_type DotPos = Filename.rfind('.');
458
459 if (DotPos == std::string::npos) {
460 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000461 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000462 }
463
Ted Kremenek8904f152007-12-05 23:49:08 +0000464 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
465 // C header: .h
466 // C++ header: .hh or .H;
467 // assembler no preprocessing: .s
468 // assembler: .S
469 if (Ext == "c")
470 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000471 else if (Ext == "S" ||
472 // If the compiler is run on a .s file, preprocess it as .S
473 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000474 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000475 else if (Ext == "i")
476 return langkind_c_cpp;
477 else if (Ext == "ii")
478 return langkind_cxx_cpp;
479 else if (Ext == "m")
480 return langkind_objc;
481 else if (Ext == "mi")
482 return langkind_objc_cpp;
483 else if (Ext == "mm" || Ext == "M")
484 return langkind_objcxx;
485 else if (Ext == "mii")
486 return langkind_objcxx_cpp;
487 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
488 Ext == "c++" || Ext == "cp" || Ext == "cxx")
489 return langkind_cxx;
490 else
491 return langkind_c;
492}
493
494
Ted Kremenek85888962008-10-21 00:54:44 +0000495static void InitializeCOptions(LangOptions &Options) {
496 // Do nothing.
497}
498
499static void InitializeObjCOptions(LangOptions &Options) {
500 Options.ObjC1 = Options.ObjC2 = 1;
501}
502
503
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000504static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 // FIXME: implement -fpreprocessed mode.
506 bool NoPreprocess = false;
507
Ted Kremenek8904f152007-12-05 23:49:08 +0000508 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000510 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000511 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000512 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 case langkind_c_cpp:
514 NoPreprocess = true;
515 // FALLTHROUGH
516 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000517 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000518 break;
519 case langkind_cxx_cpp:
520 NoPreprocess = true;
521 // FALLTHROUGH
522 case langkind_cxx:
523 Options.CPlusPlus = 1;
524 break;
525 case langkind_objc_cpp:
526 NoPreprocess = true;
527 // FALLTHROUGH
528 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000529 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 break;
531 case langkind_objcxx_cpp:
532 NoPreprocess = true;
533 // FALLTHROUGH
534 case langkind_objcxx:
535 Options.ObjC1 = Options.ObjC2 = 1;
536 Options.CPlusPlus = 1;
537 break;
538 }
Chris Lattner2c78b872009-04-14 23:22:57 +0000539
540 if (ObjCExclusiveGC)
541 Options.setGCMode(LangOptions::GCOnly);
542 else if (ObjCEnableGC)
543 Options.setGCMode(LangOptions::HybridGC);
544
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000545 if (ObjCEnableGCBitmapPrint)
546 Options.ObjCGCBitmapPrint = 1;
547
Chris Lattner2c78b872009-04-14 23:22:57 +0000548 Options.setVisibilityMode(SymbolVisibility);
549 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000550}
551
552/// LangStds - Language standards we support.
553enum LangStds {
554 lang_unspecified,
555 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000556 lang_gnu_START,
557 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000558 lang_cxx98, lang_gnucxx98,
559 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000560};
561
562static llvm::cl::opt<LangStds>
563LangStd("std", llvm::cl::desc("Language standard to compile for"),
564 llvm::cl::init(lang_unspecified),
565 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
566 clEnumValN(lang_c89, "c90", "ISO C 1990"),
567 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
568 clEnumValN(lang_c94, "iso9899:199409",
569 "ISO C 1990 with amendment 1"),
570 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000571 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000573 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000575 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000577 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 clEnumValN(lang_gnu99, "gnu9x",
579 "ISO C 1999 with GNU extensions"),
580 clEnumValN(lang_cxx98, "c++98",
581 "ISO C++ 1998 with amendments"),
582 clEnumValN(lang_gnucxx98, "gnu++98",
583 "ISO C++ 1998 with amendments and GNU "
584 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000585 clEnumValN(lang_cxx0x, "c++0x",
586 "Upcoming ISO C++ 200x with amendments"),
587 clEnumValN(lang_gnucxx0x, "gnu++0x",
588 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000589 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000590 clEnumValEnd));
591
592static llvm::cl::opt<bool>
593NoOperatorNames("fno-operator-names",
594 llvm::cl::desc("Do not treat C++ operator name keywords as "
595 "synonyms for operators"));
596
Anders Carlssonee98ac52007-10-15 02:50:23 +0000597static llvm::cl::opt<bool>
598PascalStrings("fpascal-strings",
599 llvm::cl::desc("Recognize and construct Pascal-style "
600 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000601
602static llvm::cl::opt<bool>
603MSExtensions("fms-extensions",
604 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000605 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000606
607static llvm::cl::opt<bool>
608WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000609 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000610
611static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000612NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000613 llvm::cl::desc("Disallow implicit conversions between "
614 "vectors with a different number of "
615 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000616
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000617static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000618EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000619
620static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000621EnableHeinousExtensions("fheinous-gnu-extensions",
622 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
623 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
624
625static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000626ObjCNonFragileABI("fobjc-nonfragile-abi",
627 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000628
Daniel Dunbard6884a02009-05-04 05:16:21 +0000629
630static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000631EmitAllDecls("femit-all-decls",
632 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000633
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000634static llvm::cl::opt<bool>
635Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000636 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000637
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000638static llvm::cl::opt<bool>
639GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000640 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000641 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000642
643static llvm::cl::opt<bool>
644NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000645 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000646 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000647
Ted Kremenekea644d82008-09-03 21:22:16 +0000648
649
650static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000651Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000652
Douglas Gregor26dce442009-03-10 00:06:19 +0000653static llvm::cl::opt<unsigned>
654TemplateDepth("ftemplate-depth", llvm::cl::init(99),
655 llvm::cl::desc("Maximum depth of recursive template "
656 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000657static llvm::cl::opt<bool>
658DollarsInIdents("fdollars-in-identifiers",
659 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000660
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000661
662static llvm::cl::opt<bool>
663OptSize("Os", llvm::cl::desc("Optimize for size"));
664
665static llvm::cl::opt<bool>
666NoCommon("fno-common",
667 llvm::cl::desc("Compile common globals like normal definitions"),
668 llvm::cl::ValueDisallowed);
669
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000670static llvm::cl::opt<std::string>
671MainFileName("main-file-name",
672 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000673
Anders Carlssona33d9b42009-05-13 19:49:53 +0000674// FIXME: Also add an "-fno-access-control" option.
675static llvm::cl::opt<bool>
676AccessControl("faccess-control",
677 llvm::cl::desc("Enable C++ access control"));
678
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000679// It might be nice to add bounds to the CommandLine library directly.
680struct OptLevelParser : public llvm::cl::parser<unsigned> {
681 bool parse(llvm::cl::Option &O, const char *ArgName,
682 const std::string &Arg, unsigned &Val) {
683 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
684 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000685 if (Val > 3)
686 return O.error(": '" + Arg + "' invalid optimization level!");
687 return false;
688 }
689};
690static llvm::cl::opt<unsigned, false, OptLevelParser>
691OptLevel("O", llvm::cl::Prefix,
692 llvm::cl::desc("Optimization level"),
693 llvm::cl::init(0));
694
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000695static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000696PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
697
698static llvm::cl::opt<bool>
699StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000700
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000701static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000702 TargetInfo *Target,
703 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000704 // Allow the target to set the default the langauge options as it sees fit.
705 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000706
707 // Pass the map of target features to the target for validation and
708 // processing.
709 Target->HandleTargetFeatures(Features);
Chris Lattner16167a62009-03-02 22:11:07 +0000710
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 if (LangStd == lang_unspecified) {
712 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000713 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000714 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000716 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 case langkind_c_cpp:
718 case langkind_objc:
719 case langkind_objc_cpp:
720 LangStd = lang_gnu99;
721 break;
722 case langkind_cxx:
723 case langkind_cxx_cpp:
724 case langkind_objcxx:
725 case langkind_objcxx_cpp:
726 LangStd = lang_gnucxx98;
727 break;
728 }
729 }
730
731 switch (LangStd) {
732 default: assert(0 && "Unknown language standard!");
733
734 // Fall through from newer standards to older ones. This isn't really right.
735 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000736 case lang_gnucxx0x:
737 case lang_cxx0x:
738 Options.CPlusPlus0x = 1;
739 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 case lang_gnucxx98:
741 case lang_cxx98:
742 Options.CPlusPlus = 1;
743 Options.CXXOperatorNames = !NoOperatorNames;
744 // FALL THROUGH.
745 case lang_gnu99:
746 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 Options.C99 = 1;
748 Options.HexFloats = 1;
749 // FALL THROUGH.
750 case lang_gnu89:
751 Options.BCPLComment = 1; // Only for C99/C++.
752 // FALL THROUGH.
753 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000754 Options.Digraphs = 1; // C94, C99, C++.
755 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 case lang_c89:
757 break;
758 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000759
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000760 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
761 Options.GNUMode = LangStd >= lang_gnu_START;
762
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000763 if (Options.CPlusPlus) {
764 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000765 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000766 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000767
Chris Lattnerd658b562008-04-05 06:32:51 +0000768 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
769 Options.ImplicitInt = 1;
770 else
771 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000772
Daniel Dunbard573d262009-04-07 22:13:21 +0000773 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
774 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000775 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000776 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000777 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000778
Chris Lattner802db9b2008-12-05 00:10:44 +0000779 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
780 // even if they are normally on for the target. In GNU modes (e.g.
781 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000782 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000783 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000784 Options.Blocks = 0;
785
Chris Lattner01638a62009-04-19 07:06:52 +0000786 // Default to not accepting '$' in identifiers when preprocessing assembler,
787 // but do accept when preprocessing C. FIXME: these defaults are right for
788 // darwin, are they right everywhere?
789 Options.DollarIdents = LK != langkind_asm_cpp;
790 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000791 Options.DollarIdents = DollarsInIdents;
792
Chris Lattnerae0ee032008-12-04 23:20:07 +0000793 if (PascalStrings.getPosition())
794 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000795 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000796 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000797 if (NoLaxVectorConversions.getPosition())
798 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000799 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000800 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000801 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000802
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000803 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000804 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000805 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000806 Options.Freestanding = Options.NoBuiltin = 1;
807
Chris Lattner810f6d52009-03-13 17:38:01 +0000808 if (EnableHeinousExtensions)
809 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000810
Anders Carlssona33d9b42009-05-13 19:49:53 +0000811 if (AccessControl)
812 Options.AccessControl = 1;
813
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000814 Options.MathErrno = MathErrno;
815
Douglas Gregor26dce442009-03-10 00:06:19 +0000816 Options.InstantiationDepth = TemplateDepth;
817
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000818 // Override the default runtime if the user requested it.
819 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000820 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000821 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000822 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000823
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000824 if (ObjCNonFragileABI)
825 Options.ObjCNonFragileABI = 1;
Daniel Dunbard6884a02009-05-04 05:16:21 +0000826
Daniel Dunbard604c402009-02-04 21:19:06 +0000827 if (EmitAllDecls)
828 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000829
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000830 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
831 // support.
832 Options.OptimizeSize = 0;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000833
834 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000835 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000836 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000837
838 assert(PICLevel <= 2 && "Invalid value for -pic-level");
839 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000840
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000841 Options.GNUInline = !Options.C99;
Chris Lattner5aeb9e72009-05-06 04:38:30 +0000842 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000843 Options.NoInline = !OptSize && !OptLevel;
844
845 Options.Static = StaticDefine;
846
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000847 if (MainFileName.getPosition())
848 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000849}
850
851//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000852// Target Triple Processing.
853//===----------------------------------------------------------------------===//
854
855static llvm::cl::opt<std::string>
856TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000857 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000858
Chris Lattner42e67372008-03-05 01:18:20 +0000859static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000860Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000861
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000862static llvm::cl::opt<std::string>
863MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000864 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000865
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000866// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
867// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000868
869// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000870static void HandleMacOSVersionMin(std::string &Triple) {
871 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
872 if (DarwinDashIdx == std::string::npos) {
873 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000874 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000875 exit(1);
876 }
877 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
878
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000879 // Remove the number.
880 Triple.resize(DarwinNumIdx);
881
882 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
883 bool MacOSVersionMinIsInvalid = false;
884 int VersionNum = 0;
885 if (MacOSVersionMin.size() < 4 ||
886 MacOSVersionMin.substr(0, 3) != "10." ||
887 !isdigit(MacOSVersionMin[3])) {
888 MacOSVersionMinIsInvalid = true;
889 } else {
890 const char *Start = MacOSVersionMin.c_str()+3;
891 char *End = 0;
892 VersionNum = (int)strtol(Start, &End, 10);
893
Chris Lattner079f2c462008-09-30 20:30:12 +0000894 // The version number must be in the range 0-9.
895 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
896
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000897 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
898 Triple += llvm::itostr(VersionNum+4);
899
Chris Lattner079f2c462008-09-30 20:30:12 +0000900 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
901 // Add the period piece (.7) to the end of the triple. This gives us
902 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000903 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000904 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
905 MacOSVersionMinIsInvalid = true;
906 }
907 }
908
909 if (MacOSVersionMinIsInvalid) {
910 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000911 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000912 MacOSVersionMin.c_str());
913 exit(1);
914 }
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000915 else if (VersionNum <= 4 &&
916 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
917 fprintf(stderr,
918 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
919 MacOSVersionMin.c_str());
920 exit(1);
921 }
922
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000923}
924
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000925static llvm::cl::opt<std::string>
926IPhoneOSVersionMin("miphoneos-version-min",
927 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
928
929// If -miphoneos-version-min=2.2 is specified, change the triple from being
930// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
931// 9 as the default major Darwin number, and encode the iPhone OS version
932// number in the minor version and revision.
933
934// FIXME: We should have the driver do this instead.
935static void HandleIPhoneOSVersionMin(std::string &Triple) {
936 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
937 if (DarwinDashIdx == std::string::npos) {
938 fprintf(stderr,
939 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
940 exit(1);
941 }
942 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
943
944 // Remove the number.
945 Triple.resize(DarwinNumIdx);
946
947 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
948 bool IPhoneOSVersionMinIsInvalid = false;
949 int VersionNum = 0;
950 if (IPhoneOSVersionMin.size() < 3 ||
951 !isdigit(IPhoneOSVersionMin[0])) {
952 IPhoneOSVersionMinIsInvalid = true;
953 } else {
954 const char *Start = IPhoneOSVersionMin.c_str();
955 char *End = 0;
956 VersionNum = (int)strtol(Start, &End, 10);
957
958 // The version number must be in the range 0-9.
959 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
960
961 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
962 Triple += "9." + llvm::itostr(VersionNum);
963
964 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
965 // Add the period piece (.2) to the end of the triple. This gives us
966 // something like ...-darwin9.2.2
967 Triple += End;
968 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
969 IPhoneOSVersionMinIsInvalid = true;
970 }
971 }
972
973 if (IPhoneOSVersionMinIsInvalid) {
974 fprintf(stderr,
975 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
976 IPhoneOSVersionMin.c_str());
977 exit(1);
978 }
979}
980
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000981/// CreateTargetTriple - Process the various options that affect the target
982/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000983static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000984 // Initialize base triple. If a -triple option has been specified, use
985 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000986 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000987 if (Triple.empty())
988 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +0000989
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000990 // If -arch foo was specified, remove the architecture from the triple we have
991 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000992
993 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000994 if (!Arch.empty()) {
995 // Decompose the base triple into "arch" and suffix.
996 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000997
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000998 if (FirstDashIdx == std::string::npos) {
999 fprintf(stderr,
1000 "Malformed target triple: \"%s\" ('-' could not be found).\n",
1001 Triple.c_str());
1002 exit(1);
1003 }
Chris Lattner37e217c2009-03-24 16:18:41 +00001004
1005 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1006 if (Arch == "ppc")
1007 Arch = "powerpc";
1008 else if (Arch == "ppc64")
1009 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +00001010
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001011 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1012 }
1013
1014 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1015 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +00001016 if (!MacOSVersionMin.empty())
1017 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +00001018 else if (!IPhoneOSVersionMin.empty())
1019 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenekae360762007-12-03 22:06:55 +00001020
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001021 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +00001022}
1023
1024//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +00001025// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +00001026//===----------------------------------------------------------------------===//
1027
Douglas Gregore1d918e2009-04-10 23:10:45 +00001028static bool InitializeSourceManager(Preprocessor &PP,
1029 const std::string &InFile) {
1030 // Figure out where to get and map in the main file.
1031 SourceManager &SourceMgr = PP.getSourceManager();
1032 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001033
1034 if (EmptyInputOnly) {
1035 const char *EmptyStr = "";
1036 llvm::MemoryBuffer *SB =
1037 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1038 SourceMgr.createMainFileIDForMemBuffer(SB);
1039 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001040 const FileEntry *File = FileMgr.getFile(InFile);
1041 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1042 if (SourceMgr.getMainFileID().isInvalid()) {
1043 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1044 << InFile.c_str();
1045 return true;
1046 }
1047 } else {
1048 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1049
1050 // If stdin was empty, SB is null. Cons up an empty memory
1051 // buffer now.
1052 if (!SB) {
1053 const char *EmptyStr = "";
1054 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1055 }
1056
1057 SourceMgr.createMainFileIDForMemBuffer(SB);
1058 if (SourceMgr.getMainFileID().isInvalid()) {
1059 PP.getDiagnostics().Report(FullSourceLoc(),
1060 diag::err_fe_error_reading_stdin);
1061 return true;
1062 }
1063 }
1064
1065 return false;
1066}
1067
Chris Lattneraa391972008-04-19 23:09:31 +00001068
Chris Lattnere116ccf2009-04-21 05:40:52 +00001069//===----------------------------------------------------------------------===//
1070// Preprocessor Initialization
1071//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001072
Chris Lattnere116ccf2009-04-21 05:40:52 +00001073// FIXME: Preprocessor builtins to support.
1074// -A... - Play with #assertions
1075// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001076
Chris Lattnere116ccf2009-04-21 05:40:52 +00001077static llvm::cl::list<std::string>
1078D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1079 llvm::cl::desc("Predefine the specified macro"));
1080static llvm::cl::list<std::string>
1081U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1082 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001083
Chris Lattnere116ccf2009-04-21 05:40:52 +00001084static llvm::cl::list<std::string>
1085ImplicitIncludes("include", llvm::cl::value_desc("file"),
1086 llvm::cl::desc("Include file before parsing"));
1087static llvm::cl::list<std::string>
1088ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1089 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001090
Chris Lattnere116ccf2009-04-21 05:40:52 +00001091static llvm::cl::opt<std::string>
1092ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1093 llvm::cl::desc("Include precompiled header file"));
1094
1095static llvm::cl::opt<std::string>
1096ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1097 llvm::cl::desc("Include file before parsing"));
1098
Reid Spencer5f016e22007-07-11 17:01:13 +00001099
1100//===----------------------------------------------------------------------===//
1101// Preprocessor include path information.
1102//===----------------------------------------------------------------------===//
1103
1104// This tool exports a large number of command line options to control how the
1105// preprocessor searches for header files. At root, however, the Preprocessor
1106// object takes a very simple interface: a list of directories to search for
1107//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001108// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001109// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001110//
Reid Spencer5f016e22007-07-11 17:01:13 +00001111
1112static llvm::cl::opt<bool>
1113nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1114
1115// Various command line options. These four add directories to each chain.
1116static llvm::cl::list<std::string>
1117F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1118 llvm::cl::desc("Add directory to framework include search path"));
1119static llvm::cl::list<std::string>
1120I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1121 llvm::cl::desc("Add directory to include search path"));
1122static llvm::cl::list<std::string>
1123idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1124 llvm::cl::desc("Add directory to AFTER include search path"));
1125static llvm::cl::list<std::string>
1126iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1127 llvm::cl::desc("Add directory to QUOTE include search path"));
1128static llvm::cl::list<std::string>
1129isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1130 llvm::cl::desc("Add directory to SYSTEM include search path"));
1131
1132// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1133static llvm::cl::list<std::string>
1134iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1135 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1136static llvm::cl::list<std::string>
1137iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1138 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1139static llvm::cl::list<std::string>
1140iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1141 llvm::cl::Prefix,
1142 llvm::cl::desc("Set directory to include search path with prefix"));
1143
Chris Lattner0c946412007-08-26 17:47:35 +00001144static llvm::cl::opt<std::string>
1145isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1146 llvm::cl::desc("Set the system root directory (usually /)"));
1147
Reid Spencer5f016e22007-07-11 17:01:13 +00001148// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001149
Reid Spencer5f016e22007-07-11 17:01:13 +00001150/// InitializeIncludePaths - Process the -I options and set them in the
1151/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001152void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1153 FileManager &FM, const LangOptions &Lang) {
1154 InitHeaderSearch Init(Headers, Verbose, isysroot);
1155
Ted Kremenekf3721112008-05-31 00:27:00 +00001156 // Handle -I... and -F... options, walking the lists in parallel.
1157 unsigned Iidx = 0, Fidx = 0;
1158 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1159 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001160 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001161 ++Iidx;
1162 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001163 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001164 ++Fidx;
1165 }
1166 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001167
Ted Kremenekf3721112008-05-31 00:27:00 +00001168 // Consume what's left from whatever list was longer.
1169 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001170 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001171 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001172 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001173
1174 // Handle -idirafter... options.
1175 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001176 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1177 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001178
1179 // Handle -iquote... options.
1180 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001181 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001182
1183 // Handle -isystem... options.
1184 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001185 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001186
1187 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1188 // parallel, processing the values in order of occurance to get the right
1189 // prefixes.
1190 {
1191 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1192 unsigned iprefix_idx = 0;
1193 unsigned iwithprefix_idx = 0;
1194 unsigned iwithprefixbefore_idx = 0;
1195 bool iprefix_done = iprefix_vals.empty();
1196 bool iwithprefix_done = iwithprefix_vals.empty();
1197 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1198 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1199 if (!iprefix_done &&
1200 (iwithprefix_done ||
1201 iprefix_vals.getPosition(iprefix_idx) <
1202 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1203 (iwithprefixbefore_done ||
1204 iprefix_vals.getPosition(iprefix_idx) <
1205 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1206 Prefix = iprefix_vals[iprefix_idx];
1207 ++iprefix_idx;
1208 iprefix_done = iprefix_idx == iprefix_vals.size();
1209 } else if (!iwithprefix_done &&
1210 (iwithprefixbefore_done ||
1211 iwithprefix_vals.getPosition(iwithprefix_idx) <
1212 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001213 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1214 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 ++iwithprefix_idx;
1216 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1217 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001218 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1219 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 ++iwithprefixbefore_idx;
1221 iwithprefixbefore_done =
1222 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1223 }
1224 }
1225 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001226
Nico Weber0fca0222008-08-22 09:25:22 +00001227 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001228
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001229 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001230 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001231 llvm::sys::Path::GetMainExecutable(Argv0,
1232 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001233 if (!MainExecutablePath.isEmpty()) {
1234 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1235 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001236
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001237 // Get foo/lib/clang/<version>/include
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001238 MainExecutablePath.appendComponent("lib");
1239 MainExecutablePath.appendComponent("clang");
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001240 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001241 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001242
1243 // We pass true to ignore sysroot so that we *always* look for clang headers
1244 // relative to our executable, never relative to -isysroot.
1245 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1246 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001247 }
1248
Nico Weber0fca0222008-08-22 09:25:22 +00001249 if (!nostdinc)
1250 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001251
1252 // Now that we have collected all of the include paths, merge them all
1253 // together and tell the preprocessor about them.
1254
Nico Weber0fca0222008-08-22 09:25:22 +00001255 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001256}
1257
Chris Lattnere116ccf2009-04-21 05:40:52 +00001258void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1259{
1260 // Add macros from the command line.
1261 unsigned d = 0, D = D_macros.size();
1262 unsigned u = 0, U = U_macros.size();
1263 while (d < D || u < U) {
1264 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1265 InitOpts.addMacroDef(D_macros[d++]);
1266 else
1267 InitOpts.addMacroUndef(U_macros[u++]);
1268 }
1269
1270 // If -imacros are specified, include them now. These are processed before
1271 // any -include directives.
1272 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1273 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1274
Douglas Gregorb64c1932009-05-12 01:31:05 +00001275 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1276 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001277 // We want to add these paths to the predefines buffer in order, make a
1278 // temporary vector to sort by their occurrence.
1279 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1280
1281 if (!ImplicitIncludePTH.empty())
1282 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1283 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001284 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1285 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1286 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001287 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1288 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1289 &ImplicitIncludes[i]));
1290 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1291
1292
1293 // Now that they are ordered by position, add to the predefines buffer.
1294 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1295 std::string *Ptr = OrderedPaths[i].second;
1296 if (!ImplicitIncludes.empty() &&
1297 Ptr >= &ImplicitIncludes[0] &&
1298 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1299 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001300 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001301 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001302 } else {
1303 // We end up here when we're producing preprocessed output and
1304 // we loaded a PCH file. In this case, just include the header
1305 // file that was used to build the precompiled header.
1306 assert(Ptr == &ImplicitIncludePCH);
1307 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1308 if (!OriginalFile.empty()) {
1309 InitOpts.addInclude(OriginalFile, false);
1310 ImplicitIncludePCH.clear();
1311 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001312 }
1313 }
1314 }
1315}
1316
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001317//===----------------------------------------------------------------------===//
1318// Driver PreprocessorFactory - For lazily generating preprocessors ...
1319//===----------------------------------------------------------------------===//
1320
1321namespace {
1322class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1323 Diagnostic &Diags;
1324 const LangOptions &LangInfo;
1325 TargetInfo &Target;
1326 SourceManager &SourceMgr;
1327 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001328
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001329public:
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001330 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001331 TargetInfo &target, SourceManager &SM,
1332 HeaderSearch &Headers)
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001333 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001334 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek339b9c22008-04-17 22:31:54 +00001335
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001336
1337 virtual ~DriverPreprocessorFactory() {}
1338
1339 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001340 llvm::OwningPtr<PTHManager> PTHMgr;
1341
Ted Kremenek748d5d62009-03-20 00:26:38 +00001342 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1343 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1344 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001345 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001346 }
1347
Ted Kremenek72b1b152009-01-15 18:47:46 +00001348 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001349 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1350 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001351 PTHMgr.reset(PTHManager::Create(x, &Diags,
1352 TokenCache.empty() ? Diagnostic::Error
1353 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001354 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001355
Ted Kremenek22f0d092009-03-22 06:42:39 +00001356 if (Diags.hasErrorOccurred())
1357 exit(1);
1358
Ted Kremenek72b1b152009-01-15 18:47:46 +00001359 // Create the Preprocessor.
1360 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1361 SourceMgr, HeaderInfo,
1362 PTHMgr.get()));
1363
1364 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1365 // That argument is used as the IdentifierInfoLookup argument to
1366 // IdentifierTable's ctor.
1367 if (PTHMgr) {
1368 PTHMgr->setPreprocessor(PP.get());
1369 PP->setPTHManager(PTHMgr.take());
1370 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001371
Chris Lattnere116ccf2009-04-21 05:40:52 +00001372 PreprocessorInitOptions InitOpts;
1373 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001374 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001375 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001376
Daniel Dunbar0a70c642009-05-03 09:35:25 +00001377 std::string ErrStr;
1378 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1379 if (!DFG && !ErrStr.empty()) {
1380 fprintf(stderr, "%s", ErrStr.c_str());
1381 return 0;
Daniel Dunbar750c3582008-10-24 22:12:41 +00001382 }
1383
Douglas Gregore1d918e2009-04-10 23:10:45 +00001384 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001385 }
1386};
1387}
Reid Spencer5f016e22007-07-11 17:01:13 +00001388
Reid Spencer5f016e22007-07-11 17:01:13 +00001389//===----------------------------------------------------------------------===//
1390// Basic Parser driver
1391//===----------------------------------------------------------------------===//
1392
Chris Lattner51574ea2008-04-19 23:25:44 +00001393static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001395 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001396
1397 // Parsing the specified input file.
1398 P.ParseTranslationUnit();
1399 delete PA;
1400}
1401
1402//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001403// Code generation options
1404//===----------------------------------------------------------------------===//
1405
1406static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001407GenerateDebugInfo("g",
1408 llvm::cl::desc("Generate source level debug information"));
1409
Daniel Dunbara034ba82009-02-17 19:47:34 +00001410static llvm::cl::opt<std::string>
1411TargetCPU("mcpu",
1412 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1413
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001414static llvm::cl::list<std::string>
1415TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1416
1417/// ComputeTargetFeatures - Recompute the target feature list to only
1418/// be the list of things that are enabled, based on the target cpu
1419/// and feature list.
1420static void ComputeFeatureMap(TargetInfo *Target,
1421 llvm::StringMap<bool> &Features) {
1422 assert(Features.empty() && "invalid map");
1423
1424 // Initialize the feature map based on the target.
1425 Target->getDefaultFeatures(TargetCPU, Features);
1426
1427 // Apply the user specified deltas.
1428 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1429 ie = TargetFeatures.end(); it != ie; ++it) {
1430 const char *Name = it->c_str();
1431
1432 // FIXME: Don't handle errors like this.
1433 if (Name[0] != '-' && Name[0] != '+') {
1434 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1435 Name);
1436 exit(1);
1437 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001438 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1439 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1440 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001441 exit(1);
1442 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001443 }
1444}
1445
Chris Lattner7afae712009-03-16 18:41:18 +00001446static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001447 const LangOptions &LangOpts,
1448 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001449 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001450 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001451 if (OptSize) {
1452 // -Os implies -O2
1453 // FIXME: Diagnose conflicting options.
1454 Opts.OptimizationLevel = 2;
1455 } else {
1456 Opts.OptimizationLevel = OptLevel;
1457 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001458
1459 // FIXME: There are llvm-gcc options to control these selectively.
1460 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1461 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001462 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001463
1464#ifdef NDEBUG
1465 Opts.VerifyModule = 0;
1466#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001467
1468 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001469 Opts.Features.clear();
1470 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1471 ie = Features.end(); it != ie; ++it) {
1472 // FIXME: If we are completely confident that we have the right
1473 // set, we only need to pass the minuses.
1474 std::string Name(it->second ? "+" : "-");
1475 Name += it->first();
1476 Opts.Features.push_back(Name);
1477 }
Chris Lattner44502662009-02-18 01:23:44 +00001478
Chris Lattnerbd360642009-03-26 05:00:52 +00001479 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1480
Chris Lattner44502662009-02-18 01:23:44 +00001481 // Handle -ftime-report.
1482 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001483}
1484
1485//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001486// Fix-It Options
1487//===----------------------------------------------------------------------===//
1488static llvm::cl::list<ParsedSourceLocation>
1489FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1490 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1491
1492//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001493// ObjC Rewriter Options
1494//===----------------------------------------------------------------------===//
1495static llvm::cl::opt<bool>
1496SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1497 llvm::cl::desc("Silence ObjC rewriting warnings"));
1498
1499//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001500// -dump-build-information Stuff
1501//===----------------------------------------------------------------------===//
1502
1503static llvm::cl::opt<std::string>
1504DumpBuildInformation("dump-build-information",
1505 llvm::cl::value_desc("filename"),
1506 llvm::cl::desc("output a dump of some build information to a file"));
1507
1508static llvm::raw_ostream *BuildLogFile = 0;
1509
1510/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1511/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1512namespace {
1513class LoggingDiagnosticClient : public DiagnosticClient {
1514 llvm::OwningPtr<DiagnosticClient> Chain1;
1515 llvm::OwningPtr<DiagnosticClient> Chain2;
1516public:
1517
1518 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1519 // Output diags both where requested...
1520 Chain1.reset(Normal);
1521 // .. and to our log file.
1522 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1523 !NoShowColumn,
1524 !NoCaretDiagnostics,
1525 !NoShowLocation,
1526 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001527 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001528 !NoDiagnosticsFixIt,
1529 MessageLength));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001530 }
1531
1532 virtual void setLangOptions(const LangOptions *LO) {
1533 Chain1->setLangOptions(LO);
1534 Chain2->setLangOptions(LO);
1535 }
1536
1537 virtual bool IncludeInDiagnosticCounts() const {
1538 return Chain1->IncludeInDiagnosticCounts();
1539 }
1540
1541 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1542 const DiagnosticInfo &Info) {
1543 Chain1->HandleDiagnostic(DiagLevel, Info);
1544 Chain2->HandleDiagnostic(DiagLevel, Info);
1545 }
1546};
1547} // end anonymous namespace.
1548
1549static void SetUpBuildDumpLog(unsigned argc, char **argv,
1550 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1551
1552 std::string ErrorInfo;
1553 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1554 ErrorInfo);
1555
1556 if (!ErrorInfo.empty()) {
1557 llvm::errs() << "error opening -dump-build-information file '"
1558 << DumpBuildInformation << "', option ignored!\n";
1559 delete BuildLogFile;
1560 BuildLogFile = 0;
1561 DumpBuildInformation = "";
1562 return;
1563 }
1564
1565 (*BuildLogFile) << "clang-cc command line arguments: ";
1566 for (unsigned i = 0; i != argc; ++i)
1567 (*BuildLogFile) << argv[i] << ' ';
1568 (*BuildLogFile) << '\n';
1569
1570 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1571 // the diagnostic producers and the normal receiver.
1572 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1573}
1574
1575
1576
1577//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001578// Main driver
1579//===----------------------------------------------------------------------===//
1580
Eli Friedman66d6f042009-05-18 22:20:00 +00001581static llvm::raw_ostream* ComputeOutFile(const std::string& InFile,
1582 const char* Extension,
1583 bool Binary,
1584 llvm::sys::Path& OutPath) {
1585 llvm::raw_ostream* Ret;
1586 bool UseStdout = false;
1587 std::string OutFile;
1588 if (OutputFile == "-" || (OutputFile.empty() && InFile == "-")) {
1589 UseStdout = true;
1590 } else if (!OutputFile.empty()) {
1591 OutFile = OutputFile;
1592 } else if (Extension) {
1593 llvm::sys::Path Path(InFile);
1594 Path.eraseSuffix();
1595 Path.appendSuffix(Extension);
1596 OutFile = Path.toString();
1597 } else {
1598 UseStdout = true;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001599 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001600
Eli Friedman66d6f042009-05-18 22:20:00 +00001601 if (UseStdout) {
1602 Ret = new llvm::raw_stdout_ostream();
1603 if (Binary)
1604 llvm::sys::Program::ChangeStdoutToBinary();
1605 } else {
1606 std::string Error;
1607 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Binary, Error);
1608 if (!Error.empty()) {
1609 // FIXME: Don't fail this way.
1610 llvm::cerr << "ERROR: " << Error << "\n";
1611 ::exit(1);
1612 }
1613 OutPath = OutFile;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001614 }
Eli Friedman66d6f042009-05-18 22:20:00 +00001615
1616 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001617}
1618
Reid Spencer5f016e22007-07-11 17:01:13 +00001619/// ProcessInputFile - Process a single input file with the specified state.
1620///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001621static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001622 const std::string &InFile, ProgActions PA,
1623 const llvm::StringMap<bool> &Features) {
Eli Friedman66d6f042009-05-18 22:20:00 +00001624 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001625 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001626 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001627 FixItRewriter *FixItRewrite = 0;
Douglas Gregorf807fe02009-04-14 16:27:31 +00001628 bool CompleteTranslationUnit = true;
Eli Friedman66d6f042009-05-18 22:20:00 +00001629 llvm::sys::Path OutPath;
Douglas Gregor558cb562009-04-02 01:08:08 +00001630
Ted Kremenek85888962008-10-21 00:54:44 +00001631 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 default:
Eli Friedman66d6f042009-05-18 22:20:00 +00001633 fprintf(stderr, "Unexpected program action!\n");
1634 HadErrors = true;
1635 return;
1636
1637 case ASTPrint:
1638 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1639 Consumer.reset(CreateASTPrinter(OS.get()));
1640 break;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001641
Eli Friedman66d6f042009-05-18 22:20:00 +00001642 case ASTDump:
1643 Consumer.reset(CreateASTDumper(false));
1644 break;
1645
1646 case ASTDumpFull:
1647 Consumer.reset(CreateASTDumper(true));
1648 break;
1649
1650 case ASTView:
1651 Consumer.reset(CreateASTViewer());
1652 break;
1653
1654 case PrintDeclContext:
1655 Consumer.reset(CreateDeclContextPrinter());
1656 break;
1657
1658 case EmitHTML:
1659 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1660 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1661 break;
1662
1663 case InheritanceView:
1664 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1665 break;
1666
1667 case EmitAssembly:
1668 case EmitLLVM:
1669 case EmitBC:
1670 case EmitLLVMOnly: {
1671 BackendAction Act;
1672 if (ProgAction == EmitAssembly) {
1673 Act = Backend_EmitAssembly;
1674 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1675 } else if (ProgAction == EmitLLVM) {
1676 Act = Backend_EmitLL;
1677 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1678 } else if (ProgAction == EmitLLVMOnly) {
1679 Act = Backend_EmitNothing;
1680 } else {
1681 Act = Backend_EmitBC;
1682 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001683 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001684
Eli Friedman66d6f042009-05-18 22:20:00 +00001685 CompileOptions Opts;
1686 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1687 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1688 PP.getLangOptions(), Opts, InFile,
1689 OS.get()));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001690 break;
Eli Friedman66d6f042009-05-18 22:20:00 +00001691 }
1692
1693 case GeneratePCH:
1694 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1695 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
1696 CompleteTranslationUnit = false;
1697 break;
1698
1699 case RewriteObjC:
1700 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedmanbce831b2009-05-18 22:29:17 +00001701 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001702 PP.getLangOptions(),
1703 SilenceRewriteMacroWarning));
Eli Friedman66d6f042009-05-18 22:20:00 +00001704 break;
1705
1706 case RewriteBlocks:
1707 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1708 PP.getLangOptions()));
1709 break;
1710
1711 case RunAnalysis:
1712 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
1713 PP.getLangOptions(), OutputFile));
1714 break;
1715
Chris Lattnerc106c102008-10-12 05:03:36 +00001716 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001717 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001718 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001719 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001720 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001721 RawLex.SetKeepWhitespaceMode(true);
1722
1723 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001724 RawLex.LexFromRawLexer(RawTok);
1725 while (RawTok.isNot(tok::eof)) {
1726 PP.DumpToken(RawTok, true);
1727 fprintf(stderr, "\n");
1728 RawLex.LexFromRawLexer(RawTok);
1729 }
1730 ClearSourceMgr = true;
1731 break;
1732 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001733 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001734 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001735 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001736 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001737 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 do {
1739 PP.Lex(Tok);
1740 PP.DumpToken(Tok, true);
1741 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001742 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001743 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 break;
1745 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001746 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 break;
Ted Kremenek85888962008-10-21 00:54:44 +00001748
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001749 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001750 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001751 CacheTokens(PP, OutputFile);
1752 ClearSourceMgr = true;
1753 break;
1754 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001755
Chris Lattnercc7dea82009-04-27 22:02:30 +00001756 case PrintPreprocessedInput:
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001758
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001759 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 break;
1761
Chris Lattner47099742009-02-18 01:51:21 +00001762 case ParsePrintCallbacks: {
1763 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001764 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001765 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 break;
Chris Lattner47099742009-02-18 01:51:21 +00001767 }
1768
1769 case ParseSyntaxOnly: { // -fsyntax-only
1770 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001771 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001772 break;
Chris Lattner47099742009-02-18 01:51:21 +00001773 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001774
1775 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001776 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001777 ClearSourceMgr = true;
1778 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001779
Chris Lattner47099742009-02-18 01:51:21 +00001780 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001781 DoRewriteTest(PP, InFile, OutputFile);
1782 ClearSourceMgr = true;
1783 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001784 }
Douglas Gregor558cb562009-04-02 01:08:08 +00001785
1786 case FixIt:
1787 llvm::TimeRegion Timer(ClangFrontendTimer);
1788 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001789 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001790 PP.getSourceManager(),
1791 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001792 break;
Chris Lattner47099742009-02-18 01:51:21 +00001793 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001794
Chris Lattner1aee61a2009-04-27 21:25:27 +00001795 if (FixItAtLocations.size() > 0) {
1796 // Even without the "-fixit" flag, with may have some specific
1797 // locations where the user has requested fixes. Process those
1798 // locations now.
1799 if (!FixItRewrite)
1800 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1801 PP.getSourceManager(),
1802 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001803
Chris Lattner1aee61a2009-04-27 21:25:27 +00001804 bool AddedFixitLocation = false;
1805 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1806 Idx != Last; ++Idx) {
1807 RequestedSourceLocation Requested;
1808 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1809 Requested)) {
1810 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1811 FixItAtLocations[Idx].FileName.c_str());
1812 } else {
1813 FixItRewrite->addFixItLocation(Requested);
1814 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001815 }
1816 }
1817
Chris Lattner1aee61a2009-04-27 21:25:27 +00001818 if (!AddedFixitLocation) {
1819 // All of the fix-it locations were bad. Don't fix anything.
1820 delete FixItRewrite;
1821 FixItRewrite = 0;
1822 }
1823 }
1824
1825 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001826 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001827 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1828 PP.getSourceManager(),
1829 PP.getTargetInfo(),
1830 PP.getIdentifierTable(),
1831 PP.getSelectorTable(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001832 /* FreeMemory = */ !DisableFree,
1833 /* size_reserve = */0,
1834 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattnercc7dea82009-04-27 22:02:30 +00001835 llvm::OwningPtr<PCHReader> Reader;
1836 llvm::OwningPtr<ExternalASTSource> Source;
1837
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001838 if (!ImplicitIncludePCH.empty()) {
Chris Lattnercc7dea82009-04-27 22:02:30 +00001839 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1840
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001841 // The user has asked us to include a precompiled header. Load
1842 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001843 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1844 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00001845 // Set the predefines buffer as suggested by the PCH
1846 // reader. Typically, the predefines buffer will be empty.
1847 PP.setPredefines(Reader->getSuggestedPredefines());
1848
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001849 // Attach the PCH reader to the AST context as an external AST
1850 // source, so that declarations will be deserialized from the
1851 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00001852 if (ContextOwner) {
1853 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001854 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00001855 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001856 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001857 }
1858
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001859 case PCHReader::Failure:
1860 // Unrecoverable failure: don't even try to process the input
1861 // file.
1862 return;
1863
1864 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001865 // No suitable PCH file could be found. Return an error.
1866 return;
1867
1868#if 0
1869 // FIXME: We can recover from failed attempts to load PCH
1870 // files. This code will do so, if we ever want to enable it.
1871
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001872 // We delayed the initialization of builtins in the hope of
1873 // loading the PCH file. Since the PCH file could not be
1874 // loaded, initialize builtins now.
1875 if (ContextOwner)
1876 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001877#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001878 }
1879
1880 // Finish preprocessor initialization. We do this now (rather
1881 // than earlier) because this initialization creates new source
1882 // location entries in the source manager, which must come after
1883 // the source location entries for the PCH file.
1884 if (InitializeSourceManager(PP, InFile))
1885 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00001886 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001887
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001888
1889 // If we have an ASTConsumer, run the parser with it.
1890 if (Consumer)
1891 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
1892 CompleteTranslationUnit);
1893
1894 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
1895 llvm::TimeRegion Timer(ClangFrontendTimer);
1896 Token Tok;
1897 // Start parsing the specified input file.
1898 PP.EnterMainSourceFile();
1899 do {
1900 PP.Lex(Tok);
1901 } while (Tok.isNot(tok::eof));
1902 ClearSourceMgr = true;
1903 } else if (PA == ParseNoop) { // -parse-noop
1904 llvm::TimeRegion Timer(ClangFrontendTimer);
1905 ParseFile(PP, new MinimalAction(PP));
1906 ClearSourceMgr = true;
Chris Lattnercc7dea82009-04-27 22:02:30 +00001907 } else if (PA == PrintPreprocessedInput){ // -E mode.
1908 llvm::TimeRegion Timer(ClangFrontendTimer);
1909 DoPrintPreprocessedInput(PP, OutputFile);
1910 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001911 }
1912
Chris Lattner1aee61a2009-04-27 21:25:27 +00001913 if (FixItRewrite)
1914 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1915
1916 // If in -disable-free mode, don't deallocate ASTContext.
1917 if (DisableFree)
1918 ContextOwner.take();
1919 else
1920 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00001921
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001922 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001923 if (CheckDiagnostics(PP))
1924 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001925
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001927 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001928 PP.PrintStats();
1929 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001930 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001931 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001932 fprintf(stderr, "\n");
1933 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001934
1935 // For a multi-file compilation, some things are ok with nuking the source
1936 // manager tables, other require stable fileid/macroid's across multiple
1937 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001938 if (ClearSourceMgr)
1939 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001940
1941 if (DisableFree)
1942 Consumer.take();
Eli Friedman66d6f042009-05-18 22:20:00 +00001943 else
1944 Consumer.reset();
1945
1946 // Always delete the output stream because we don't want to leak file
1947 // handles. Also, we don't want to try to erase an open file.
1948 OS.reset();
1949
1950 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
1951 !OutPath.isEmpty()) {
1952 // If we had errors, try to erase the output file.
1953 OutPath.eraseFromDisk();
1954 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001955}
1956
1957static llvm::cl::list<std::string>
1958InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1959
Reid Spencer5f016e22007-07-11 17:01:13 +00001960int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001962 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001963 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001964 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001965
Chris Lattner47099742009-02-18 01:51:21 +00001966 if (TimeReport)
1967 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1968
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 // If no input was specified, read from stdin.
1970 if (InputFilenames.empty())
1971 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00001972
Ted Kremenek31e703b2007-12-11 23:28:38 +00001973 // Create the diagnostic client for reporting errors or for
1974 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00001975 llvm::OwningPtr<DiagnosticClient> DiagClient;
1976 if (VerifyDiagnostics) {
1977 // When checking diagnostics, just buffer them up.
1978 DiagClient.reset(new TextDiagnosticBuffer());
1979 if (InputFilenames.size() != 1) {
1980 fprintf(stderr, "-verify only works on single input files for now.\n");
1981 return 1;
1982 }
1983 if (!HTMLDiag.empty()) {
1984 fprintf(stderr, "-verify and -html-diags don't work together\n");
1985 return 1;
1986 }
1987 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001988 // Print diagnostics to stderr by default.
Douglas Gregor68a0d782009-05-02 00:03:46 +00001989
1990 // If -fmessage-length=N was not specified, determine whether this
1991 // is a terminal and, if so, implicitly define -fmessage-length
1992 // appropriately.
1993 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregor67187ce2009-05-11 18:06:49 +00001994 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor68a0d782009-05-02 00:03:46 +00001995
Chris Lattner409d4e72009-04-17 20:40:01 +00001996 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00001997 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001998 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001999 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00002000 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00002001 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00002002 !NoDiagnosticsFixIt,
2003 MessageLength));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002004 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00002005 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002007
2008 if (!DumpBuildInformation.empty()) {
2009 if (!HTMLDiag.empty()) {
2010 fprintf(stderr,
2011 "-dump-build-information and -html-diags don't work together\n");
2012 return 1;
2013 }
2014
2015 SetUpBuildDumpLog(argc, argv, DiagClient);
2016 }
2017
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002018
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002020 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00002021 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002022 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002023
Chris Lattner4f037832007-12-05 23:24:17 +00002024 // -I- is a deprecated GCC feature, scan for it and reject it.
2025 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2026 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00002027 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00002028 I_dirs.erase(I_dirs.begin()+i);
2029 --i;
2030 }
2031 }
Chris Lattner11215192008-03-14 06:12:05 +00002032
2033 // Get information about the target being compiled for.
2034 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00002035 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2036
Chris Lattner11215192008-03-14 06:12:05 +00002037 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00002038 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2039 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002040 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002041 }
Chris Lattner4f037832007-12-05 23:24:17 +00002042
Daniel Dunbard4270232009-01-20 23:17:32 +00002043 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002044 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002045
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00002046 llvm::OwningPtr<SourceManager> SourceMgr;
2047
Chris Lattner2c78b872009-04-14 23:22:57 +00002048 // Create a file manager object to provide access to and cache the filesystem.
2049 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002050
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002051 // Compute the feature set, unfortunately this effects the language!
2052 llvm::StringMap<bool> Features;
2053 ComputeFeatureMap(Target.get(), Features);
2054
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002056 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00002057
Chris Lattnerf63aea32009-03-04 21:40:56 +00002058 /// Create a SourceManager object. This tracks and owns all the file
2059 /// buffers allocated to a translation unit.
2060 if (!SourceMgr)
2061 SourceMgr.reset(new SourceManager());
2062 else
2063 SourceMgr->clearIDTables();
2064
2065 // Initialize language options, inferring file types from input filenames.
2066 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002067 DiagClient->setLangOptions(&LangInfo);
Chris Lattner2c78b872009-04-14 23:22:57 +00002068
Chris Lattnerf63aea32009-03-04 21:40:56 +00002069 InitializeBaseLanguage();
2070 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002071 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002072 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002073
2074 // Process the -I options and set them in the HeaderInfo.
2075 HeaderSearch HeaderInfo(FileMgr);
2076
Chris Lattner2c78b872009-04-14 23:22:57 +00002077
Chris Lattnerf63aea32009-03-04 21:40:56 +00002078 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2079
2080 // Set up the preprocessor with these options.
Eli Friedmanf086e3b2009-05-18 07:39:39 +00002081 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattnerf63aea32009-03-04 21:40:56 +00002082 *SourceMgr.get(), HeaderInfo);
2083
2084 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2085
2086 if (!PP)
2087 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002088
Douglas Gregore1d918e2009-04-10 23:10:45 +00002089 if (ImplicitIncludePCH.empty() &&
2090 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregor14f79002009-04-10 03:52:48 +00002091 continue;
2092
Chris Lattner409d4e72009-04-17 20:40:01 +00002093 if (!HTMLDiag.empty())
2094 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002095
2096 // Process the source file.
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002097 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002098
Chris Lattner40469652009-04-17 20:16:08 +00002099 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002100 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002101 }
Chris Lattner11215192008-03-14 06:12:05 +00002102
Mike Stump007f2a92009-01-28 02:43:35 +00002103 if (Verbose)
2104 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2105 " hosted on " LLVM_HOSTTRIPLE "\n");
2106
Mike Stumpfc0fed32009-04-28 01:19:10 +00002107 if (!NoCaretDiagnostics)
2108 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2109 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2110 (NumDiagnostics == 1 ? "" : "s"));
Reid Spencer5f016e22007-07-11 17:01:13 +00002111
2112 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 FileMgr.PrintStats();
2114 fprintf(stderr, "\n");
2115 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002116
2117 delete ClangFrontendTimer;
2118 delete BuildLogFile;
Reid Spencer5f016e22007-07-11 17:01:13 +00002119
Daniel Dunbar276373d2008-10-27 22:10:13 +00002120 // If verifying diagnostics and we reached here, all is well.
2121 if (VerifyDiagnostics)
2122 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00002123
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002124 // Managed static deconstruction. Useful for making things like
2125 // -time-passes usable.
2126 llvm::llvm_shutdown();
2127
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002128 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002129}