blob: cdb606cb81fdd29fe5e8c8fa82016461f474b18b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattner39fb14e2009-02-18 01:17:01 +000020// -Wfatal-errors
Chris Lattner4b009652007-07-25 00:24:17 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Ted Kremenek377a3192009-03-31 18:58:14 +000025#include "clang-cc.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor133d2552009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattner94269d72009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000036#include "clang/Analysis/PathDiagnostic.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000037#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000038#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000039#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000040#include "clang/AST/ASTConsumer.h"
Chris Lattnerfc318192009-03-28 04:31:31 +000041#include "clang/AST/ASTContext.h"
42#include "clang/AST/Decl.h"
Chris Lattnera17991f2009-03-29 16:50:03 +000043#include "clang/AST/DeclGroup.h"
Chris Lattner4b009652007-07-25 00:24:17 +000044#include "clang/Parse/Parser.h"
45#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000046#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000047#include "clang/Basic/FileManager.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/TargetInfo.h"
Daniel Dunbarae81a792009-05-06 04:07:06 +000050#include "clang/Basic/Version.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000051#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000052#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000053#include "llvm/ADT/StringExtras.h"
Daniel Dunbar07181d72009-05-06 03:16:41 +000054#include "llvm/ADT/StringMap.h"
Chris Lattner0e004a12009-04-08 18:24:34 +000055#include "llvm/ADT/STLExtras.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000056#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000057#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000058#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000059#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000060#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000061#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000062#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000063#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000064#include "llvm/System/Path.h"
Douglas Gregor3dd11e82009-05-03 03:52:38 +000065#include "llvm/System/Process.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000066#include "llvm/System/Signals.h"
Douglas Gregor24b48b02009-04-02 19:05:20 +000067#include <cstdlib>
Douglas Gregor3dd11e82009-05-03 03:52:38 +000068#if HAVE_SYS_TYPES_H
Douglas Gregor965a13c2009-05-02 00:03:46 +000069# include <sys/types.h>
Douglas Gregor3dd11e82009-05-03 03:52:38 +000070# include <sys/ioctl.h>
Douglas Gregor965a13c2009-05-02 00:03:46 +000071#endif
Douglas Gregor24b48b02009-04-02 19:05:20 +000072
Chris Lattner4b009652007-07-25 00:24:17 +000073using namespace clang;
74
75//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000076// Source Location Parser
77//===----------------------------------------------------------------------===//
78
79/// \brief A source location that has been parsed on the command line.
80struct ParsedSourceLocation {
81 std::string FileName;
82 unsigned Line;
83 unsigned Column;
84
85 /// \brief Try to resolve the file name of a parsed source location.
86 ///
87 /// \returns true if there was an error, false otherwise.
88 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
89};
90
91bool
92ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
93 RequestedSourceLocation &Result) {
94 const FileEntry *File = FileMgr.getFile(FileName);
95 if (!File)
96 return true;
97
98 Result.File = File;
99 Result.Line = Line;
100 Result.Column = Column;
101 return false;
102}
103
104namespace llvm {
105 namespace cl {
106 /// \brief Command-line option parser that parses source locations.
107 ///
108 /// Source locations are of the form filename:line:column.
109 template<>
110 class parser<ParsedSourceLocation>
111 : public basic_parser<ParsedSourceLocation> {
112 public:
113 bool parse(Option &O, const char *ArgName,
114 const std::string &ArgValue,
115 ParsedSourceLocation &Val);
116 };
117
118 bool
119 parser<ParsedSourceLocation>::
120 parse(Option &O, const char *ArgName, const std::string &ArgValue,
121 ParsedSourceLocation &Val) {
122 using namespace clang;
123
124 const char *ExpectedFormat
125 = "source location must be of the form filename:line:column";
126 std::string::size_type SecondColon = ArgValue.rfind(':');
127 if (SecondColon == std::string::npos) {
128 std::fprintf(stderr, "%s\n", ExpectedFormat);
129 return true;
130 }
131 char *EndPtr;
132 long Column
133 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
134 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
135 std::fprintf(stderr, "%s\n", ExpectedFormat);
136 return true;
137 }
138
139 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
140 if (SecondColon == std::string::npos) {
141 std::fprintf(stderr, "%s\n", ExpectedFormat);
142 return true;
143 }
144 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
145 if (EndPtr != ArgValue.c_str() + SecondColon) {
146 std::fprintf(stderr, "%s\n", ExpectedFormat);
147 return true;
148 }
149
150 Val.FileName = ArgValue.substr(0, FirstColon);
151 Val.Line = Line;
152 Val.Column = Column;
153 return false;
154 }
155 }
156}
157
158//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000159// Global options.
160//===----------------------------------------------------------------------===//
161
Chris Lattnerefe33382009-02-18 01:51:21 +0000162/// ClangFrontendTimer - The front-end activities should charge time to it with
163/// TimeRegion. The -ftime-report option controls whether this will do
164/// anything.
165llvm::Timer *ClangFrontendTimer = 0;
166
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000167static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000168
Chris Lattner4b009652007-07-25 00:24:17 +0000169static llvm::cl::opt<bool>
170Verbose("v", llvm::cl::desc("Enable verbose output"));
171static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000172Stats("print-stats",
173 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000174static llvm::cl::opt<bool>
175DisableFree("disable-free",
176 llvm::cl::desc("Disable freeing of memory on exit"),
177 llvm::cl::init(false));
Daniel Dunbarbb56def2009-04-27 21:19:07 +0000178static llvm::cl::opt<bool>
179EmptyInputOnly("empty-input-only",
180 llvm::cl::desc("Force running on an empty input file"));
Chris Lattner4b009652007-07-25 00:24:17 +0000181
182enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000183 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000184 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000185 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000186 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000187 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000188 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000189 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000190 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000191 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000192 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek24612ae2008-03-18 21:19:49 +0000193 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000194 ASTPrint, // Parse ASTs and print them.
195 ASTDump, // Parse ASTs and dump them.
Douglas Gregord7915fd2009-04-26 02:02:08 +0000196 ASTDumpFull, // Parse ASTs and dump them, including the
197 // contents of a PCH file.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000198 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000199 PrintDeclContext, // Print DeclContext and their Decls.
Chris Lattner4b009652007-07-25 00:24:17 +0000200 ParsePrintCallbacks, // Parse and print each callback.
201 ParseSyntaxOnly, // Parse and perform semantic analysis.
202 ParseNoop, // Parse with noop callbacks.
203 RunPreprocessorOnly, // Just lex, no output.
204 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000205 DumpTokens, // Dump out preprocessed tokens.
206 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000207 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000208 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000209 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000210 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000211};
212
213static llvm::cl::opt<ProgActions>
214ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
215 llvm::cl::init(ParseSyntaxOnly),
216 llvm::cl::values(
217 clEnumValN(RunPreprocessorOnly, "Eonly",
218 "Just run preprocessor, no output (for timings)"),
219 clEnumValN(PrintPreprocessedInput, "E",
220 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000221 clEnumValN(DumpRawTokens, "dump-raw-tokens",
222 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000223 clEnumValN(RunAnalysis, "analyze",
224 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000225 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000226 "Run preprocessor, dump internal rep of tokens"),
227 clEnumValN(ParseNoop, "parse-noop",
228 "Run parser with noop callbacks (for timings)"),
229 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
230 "Run parser and perform semantic analysis"),
231 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
232 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000233 clEnumValN(EmitHTML, "emit-html",
234 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000235 clEnumValN(ASTPrint, "ast-print",
236 "Build ASTs and then pretty-print them"),
237 clEnumValN(ASTDump, "ast-dump",
238 "Build ASTs and then debug dump them"),
Douglas Gregord7915fd2009-04-26 02:02:08 +0000239 clEnumValN(ASTDumpFull, "ast-dump-full",
240 "Build ASTs and then debug dump them, including PCH"),
Chris Lattner664dd082007-10-11 00:37:43 +0000241 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000242 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000243 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000244 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000245 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000246 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000247 clEnumValN(GeneratePCH, "emit-pch",
248 "Generate pre-compiled header file"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000249 clEnumValN(EmitAssembly, "S",
250 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000251 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000252 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000253 clEnumValN(EmitBC, "emit-llvm-bc",
254 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000255 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
256 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000257 clEnumValN(RewriteTest, "rewrite-test",
258 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000259 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000260 "Rewrite ObjC into C (code rewriter example)"),
261 clEnumValN(RewriteMacros, "rewrite-macros",
262 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000263 clEnumValN(RewriteBlocks, "rewrite-blocks",
264 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000265 clEnumValN(FixIt, "fixit",
266 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000267 clEnumValEnd));
268
Ted Kremenekd01eae62007-12-19 19:47:59 +0000269
270static llvm::cl::opt<std::string>
271OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000272 llvm::cl::value_desc("path"),
Douglas Gregor608ff622009-04-22 21:45:53 +0000273 llvm::cl::desc("Specify output file"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000274
Ted Kremenek57f25b22008-12-02 19:57:31 +0000275
276//===----------------------------------------------------------------------===//
277// PTH.
278//===----------------------------------------------------------------------===//
279
280static llvm::cl::opt<std::string>
281TokenCache("token-cache", llvm::cl::value_desc("path"),
282 llvm::cl::desc("Use specified token cache file"));
283
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000284//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000285// Diagnostic Options
286//===----------------------------------------------------------------------===//
287
Ted Kremenek10389cf2007-09-26 19:42:19 +0000288static llvm::cl::opt<bool>
289VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000290 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000291
Ted Kremenekfd75e312008-03-27 06:17:42 +0000292static llvm::cl::opt<std::string>
293HTMLDiag("html-diags",
294 llvm::cl::desc("Generate HTML to report diagnostics"),
295 llvm::cl::value_desc("HTML directory"));
296
Nico Weber0e13eaa2008-08-05 23:33:20 +0000297static llvm::cl::opt<bool>
298NoShowColumn("fno-show-column",
299 llvm::cl::desc("Do not include column number on diagnostics"));
300
301static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000302NoShowLocation("fno-show-source-location",
303 llvm::cl::desc("Do not include source location information with"
304 " diagnostics"));
305
306static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000307NoCaretDiagnostics("fno-caret-diagnostics",
308 llvm::cl::desc("Do not include source line and caret with"
309 " diagnostics"));
310
Chris Lattner695a4f52009-03-13 01:08:23 +0000311static llvm::cl::opt<bool>
Chris Lattner041bd732009-04-19 07:44:08 +0000312NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
313 llvm::cl::desc("Do not include fixit information in"
314 " diagnostics"));
315
316static llvm::cl::opt<bool>
Chris Lattner13bac9e2009-04-21 05:34:31 +0000317PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
318 llvm::cl::desc("Print source range spans in numeric form"));
319
320static llvm::cl::alias
321PrintSourceRangeInfo2("fprint-source-range-info",
322 llvm::cl::desc("Print source range spans in numeric form [deprecated]"),
323 llvm::cl::aliasopt(PrintSourceRangeInfo));
Chris Lattner695a4f52009-03-13 01:08:23 +0000324
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000325static llvm::cl::opt<bool>
326PrintDiagnosticOption("fdiagnostics-show-option",
327 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weber0e13eaa2008-08-05 23:33:20 +0000328
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000329static llvm::cl::opt<unsigned>
330MessageLength("fmessage-length",
331 llvm::cl::desc("Format message diagnostics so that they fit "
332 "within N columns or fewer, when possible."),
333 llvm::cl::value_desc("N"));
334
Chris Lattner4b009652007-07-25 00:24:17 +0000335//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000336// C++ Visualization.
337//===----------------------------------------------------------------------===//
338
339static llvm::cl::opt<std::string>
340InheritanceViewCls("cxx-inheritance-view",
341 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000342 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000343
344//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000345// Builtin Options
346//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000347
348static llvm::cl::opt<bool>
349TimeReport("ftime-report",
350 llvm::cl::desc("Print the amount of time each "
351 "phase of compilation takes"));
352
Douglas Gregor23d23262009-02-14 20:49:29 +0000353static llvm::cl::opt<bool>
354Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000355 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000356 "freestanding environment"));
357
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000358static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000359AllowBuiltins("fbuiltin", llvm::cl::init(true),
360 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000361
362
363static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000364MathErrno("fmath-errno", llvm::cl::init(true),
365 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000366
Douglas Gregor23d23262009-02-14 20:49:29 +0000367//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000368// Language Options
369//===----------------------------------------------------------------------===//
370
371enum LangKind {
372 langkind_unspecified,
373 langkind_c,
374 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000375 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000376 langkind_cxx,
377 langkind_cxx_cpp,
378 langkind_objc,
379 langkind_objc_cpp,
380 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000381 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000382};
383
Chris Lattner4b009652007-07-25 00:24:17 +0000384static llvm::cl::opt<LangKind>
385BaseLang("x", llvm::cl::desc("Base language to compile"),
386 llvm::cl::init(langkind_unspecified),
387 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
388 clEnumValN(langkind_cxx, "c++", "C++"),
389 clEnumValN(langkind_objc, "objective-c", "Objective C"),
390 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000391 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000392 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000393 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
394 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000395 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000396 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000397 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
398 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000399 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000400 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000401 clEnumValN(langkind_c, "c-header",
402 "C header"),
403 clEnumValN(langkind_objc, "objective-c-header",
404 "Objective-C header"),
405 clEnumValN(langkind_cxx, "c++-header",
406 "C++ header"),
407 clEnumValN(langkind_objcxx, "objective-c++-header",
408 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000409 clEnumValEnd));
410
411static llvm::cl::opt<bool>
412LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
413 llvm::cl::Hidden);
414static llvm::cl::opt<bool>
415LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
416 llvm::cl::Hidden);
417
Chris Lattnere1be6022009-04-14 23:22:57 +0000418static llvm::cl::opt<bool>
419ObjCExclusiveGC("fobjc-gc-only",
420 llvm::cl::desc("Use GC exclusively for Objective-C related "
421 "memory management"));
422
423static llvm::cl::opt<bool>
424ObjCEnableGC("fobjc-gc",
425 llvm::cl::desc("Enable Objective-C garbage collection"));
426
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000427static llvm::cl::opt<bool>
428ObjCEnableGCBitmapPrint("print-ivar-layout",
429 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
430
Chris Lattnere1be6022009-04-14 23:22:57 +0000431static llvm::cl::opt<LangOptions::VisibilityMode>
432SymbolVisibility("fvisibility",
433 llvm::cl::desc("Set the default symbol visibility:"),
434 llvm::cl::init(LangOptions::Default),
435 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
436 "Use default symbol visibility"),
437 clEnumValN(LangOptions::Hidden, "hidden",
438 "Use hidden symbol visibility"),
439 clEnumValN(LangOptions::Protected,"protected",
440 "Use protected symbol visibility"),
441 clEnumValEnd));
442
443static llvm::cl::opt<bool>
444OverflowChecking("ftrapv",
445 llvm::cl::desc("Trap on integer overflow"),
446 llvm::cl::init(false));
447
448
Ted Kremenek11ad8952007-12-05 23:49:08 +0000449/// InitializeBaseLanguage - Handle the -x foo options.
450static void InitializeBaseLanguage() {
451 if (LangObjC)
452 BaseLang = langkind_objc;
453 else if (LangObjCXX)
454 BaseLang = langkind_objcxx;
455}
456
457static LangKind GetLanguage(const std::string &Filename) {
458 if (BaseLang != langkind_unspecified)
459 return BaseLang;
460
461 std::string::size_type DotPos = Filename.rfind('.');
462
463 if (DotPos == std::string::npos) {
464 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000465 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000466 }
467
Ted Kremenek11ad8952007-12-05 23:49:08 +0000468 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
469 // C header: .h
470 // C++ header: .hh or .H;
471 // assembler no preprocessing: .s
472 // assembler: .S
473 if (Ext == "c")
474 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000475 else if (Ext == "S" ||
476 // If the compiler is run on a .s file, preprocess it as .S
477 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000478 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000479 else if (Ext == "i")
480 return langkind_c_cpp;
481 else if (Ext == "ii")
482 return langkind_cxx_cpp;
483 else if (Ext == "m")
484 return langkind_objc;
485 else if (Ext == "mi")
486 return langkind_objc_cpp;
487 else if (Ext == "mm" || Ext == "M")
488 return langkind_objcxx;
489 else if (Ext == "mii")
490 return langkind_objcxx_cpp;
491 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
492 Ext == "c++" || Ext == "cp" || Ext == "cxx")
493 return langkind_cxx;
494 else
495 return langkind_c;
496}
497
498
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000499static void InitializeCOptions(LangOptions &Options) {
500 // Do nothing.
501}
502
503static void InitializeObjCOptions(LangOptions &Options) {
504 Options.ObjC1 = Options.ObjC2 = 1;
505}
506
507
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000508static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000509 // FIXME: implement -fpreprocessed mode.
510 bool NoPreprocess = false;
511
Ted Kremenek11ad8952007-12-05 23:49:08 +0000512 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000513 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000514 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000515 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000516 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000517 case langkind_c_cpp:
518 NoPreprocess = true;
519 // FALLTHROUGH
520 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000521 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000522 break;
523 case langkind_cxx_cpp:
524 NoPreprocess = true;
525 // FALLTHROUGH
526 case langkind_cxx:
527 Options.CPlusPlus = 1;
528 break;
529 case langkind_objc_cpp:
530 NoPreprocess = true;
531 // FALLTHROUGH
532 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000533 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000534 break;
535 case langkind_objcxx_cpp:
536 NoPreprocess = true;
537 // FALLTHROUGH
538 case langkind_objcxx:
539 Options.ObjC1 = Options.ObjC2 = 1;
540 Options.CPlusPlus = 1;
541 break;
542 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000543
544 if (ObjCExclusiveGC)
545 Options.setGCMode(LangOptions::GCOnly);
546 else if (ObjCEnableGC)
547 Options.setGCMode(LangOptions::HybridGC);
548
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000549 if (ObjCEnableGCBitmapPrint)
550 Options.ObjCGCBitmapPrint = 1;
551
Chris Lattnere1be6022009-04-14 23:22:57 +0000552 Options.setVisibilityMode(SymbolVisibility);
553 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000554}
555
556/// LangStds - Language standards we support.
557enum LangStds {
558 lang_unspecified,
559 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000560 lang_gnu_START,
561 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000562 lang_cxx98, lang_gnucxx98,
563 lang_cxx0x, lang_gnucxx0x
564};
565
566static llvm::cl::opt<LangStds>
567LangStd("std", llvm::cl::desc("Language standard to compile for"),
568 llvm::cl::init(lang_unspecified),
569 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
570 clEnumValN(lang_c89, "c90", "ISO C 1990"),
571 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
572 clEnumValN(lang_c94, "iso9899:199409",
573 "ISO C 1990 with amendment 1"),
574 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000575 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000576 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000577 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000578 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000579 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000580 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000581 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000582 clEnumValN(lang_gnu99, "gnu9x",
583 "ISO C 1999 with GNU extensions"),
584 clEnumValN(lang_cxx98, "c++98",
585 "ISO C++ 1998 with amendments"),
586 clEnumValN(lang_gnucxx98, "gnu++98",
587 "ISO C++ 1998 with amendments and GNU "
588 "extensions (default for C++)"),
589 clEnumValN(lang_cxx0x, "c++0x",
590 "Upcoming ISO C++ 200x with amendments"),
591 clEnumValN(lang_gnucxx0x, "gnu++0x",
592 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000593 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000594 clEnumValEnd));
595
596static llvm::cl::opt<bool>
597NoOperatorNames("fno-operator-names",
598 llvm::cl::desc("Do not treat C++ operator name keywords as "
599 "synonyms for operators"));
600
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000601static llvm::cl::opt<bool>
602PascalStrings("fpascal-strings",
603 llvm::cl::desc("Recognize and construct Pascal-style "
604 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000605
606static llvm::cl::opt<bool>
607MSExtensions("fms-extensions",
608 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000609 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000610
611static llvm::cl::opt<bool>
612WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000613 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000614
615static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000616NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000617 llvm::cl::desc("Disallow implicit conversions between "
618 "vectors with a different number of "
619 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000620
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000621static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000622EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000623
624static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000625EnableHeinousExtensions("fheinous-gnu-extensions",
626 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
627 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
628
629static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000630ObjCNonFragileABI("fobjc-nonfragile-abi",
631 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000632
Daniel Dunbar5523e862009-05-04 05:16:21 +0000633
634static llvm::cl::opt<bool>
635ObjCTightLayout("fobjc-tight-layout",
636 llvm::cl::desc("enable tight objective-c interface layout"));
637
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000638static llvm::cl::opt<bool>
639EmitAllDecls("femit-all-decls",
640 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000641
Daniel Dunbar91692d92008-08-11 17:36:14 +0000642static llvm::cl::opt<bool>
643Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000644 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000645
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000646static llvm::cl::opt<bool>
647GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000648 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000649 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000650
651static llvm::cl::opt<bool>
652NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000653 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000654 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000655
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000656
657
658static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000659Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000660
Douglas Gregor375733c2009-03-10 00:06:19 +0000661static llvm::cl::opt<unsigned>
662TemplateDepth("ftemplate-depth", llvm::cl::init(99),
663 llvm::cl::desc("Maximum depth of recursive template "
664 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000665static llvm::cl::opt<bool>
666DollarsInIdents("fdollars-in-identifiers",
667 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000668
Anders Carlssondfd77642009-04-06 17:37:10 +0000669
670static llvm::cl::opt<bool>
671OptSize("Os", llvm::cl::desc("Optimize for size"));
672
673static llvm::cl::opt<bool>
674NoCommon("fno-common",
675 llvm::cl::desc("Compile common globals like normal definitions"),
676 llvm::cl::ValueDisallowed);
677
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000678static llvm::cl::opt<std::string>
679MainFileName("main-file-name",
680 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000681
682// It might be nice to add bounds to the CommandLine library directly.
683struct OptLevelParser : public llvm::cl::parser<unsigned> {
684 bool parse(llvm::cl::Option &O, const char *ArgName,
685 const std::string &Arg, unsigned &Val) {
686 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
687 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000688 if (Val > 3)
689 return O.error(": '" + Arg + "' invalid optimization level!");
690 return false;
691 }
692};
693static llvm::cl::opt<unsigned, false, OptLevelParser>
694OptLevel("O", llvm::cl::Prefix,
695 llvm::cl::desc("Optimization level"),
696 llvm::cl::init(0));
697
Daniel Dunbare079c712009-04-08 03:03:23 +0000698static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000699PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
700
701static llvm::cl::opt<bool>
702StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000703
Daniel Dunbar34542952008-08-23 08:43:39 +0000704static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar07181d72009-05-06 03:16:41 +0000705 TargetInfo *Target,
706 const llvm::StringMap<bool> &Features) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000707 // Allow the target to set the default the langauge options as it sees fit.
708 Target->getDefaultLangOptions(Options);
Daniel Dunbar07181d72009-05-06 03:16:41 +0000709
710 // Pass the map of target features to the target for validation and
711 // processing.
712 Target->HandleTargetFeatures(Features);
Chris Lattner738d3f62009-03-02 22:11:07 +0000713
Chris Lattner4b009652007-07-25 00:24:17 +0000714 if (LangStd == lang_unspecified) {
715 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000716 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000717 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000718 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000719 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000720 case langkind_c_cpp:
721 case langkind_objc:
722 case langkind_objc_cpp:
723 LangStd = lang_gnu99;
724 break;
725 case langkind_cxx:
726 case langkind_cxx_cpp:
727 case langkind_objcxx:
728 case langkind_objcxx_cpp:
729 LangStd = lang_gnucxx98;
730 break;
731 }
732 }
733
734 switch (LangStd) {
735 default: assert(0 && "Unknown language standard!");
736
737 // Fall through from newer standards to older ones. This isn't really right.
738 // FIXME: Enable specifically the right features based on the language stds.
739 case lang_gnucxx0x:
740 case lang_cxx0x:
741 Options.CPlusPlus0x = 1;
742 // FALL THROUGH
743 case lang_gnucxx98:
744 case lang_cxx98:
745 Options.CPlusPlus = 1;
746 Options.CXXOperatorNames = !NoOperatorNames;
747 // FALL THROUGH.
748 case lang_gnu99:
749 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000750 Options.C99 = 1;
751 Options.HexFloats = 1;
752 // FALL THROUGH.
753 case lang_gnu89:
754 Options.BCPLComment = 1; // Only for C99/C++.
755 // FALL THROUGH.
756 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000757 Options.Digraphs = 1; // C94, C99, C++.
758 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000759 case lang_c89:
760 break;
761 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000762
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000763 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
764 Options.GNUMode = LangStd >= lang_gnu_START;
765
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000766 if (Options.CPlusPlus) {
767 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000768 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000769 }
Chris Lattner4b009652007-07-25 00:24:17 +0000770
Chris Lattner6ab935b2008-04-05 06:32:51 +0000771 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
772 Options.ImplicitInt = 1;
773 else
774 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000775
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000776 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
777 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000778 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000779 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000780 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000781
Chris Lattner58d5ba52008-12-05 00:10:44 +0000782 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
783 // even if they are normally on for the target. In GNU modes (e.g.
784 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000785 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000786 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000787 Options.Blocks = 0;
788
Chris Lattner284784c2009-04-19 07:06:52 +0000789 // Default to not accepting '$' in identifiers when preprocessing assembler,
790 // but do accept when preprocessing C. FIXME: these defaults are right for
791 // darwin, are they right everywhere?
792 Options.DollarIdents = LK != langkind_asm_cpp;
793 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner77c04832009-04-19 07:00:02 +0000794 Options.DollarIdents = DollarsInIdents;
795
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000796 if (PascalStrings.getPosition())
797 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000798 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000799 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000800 if (NoLaxVectorConversions.getPosition())
801 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000802 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000803 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000804 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000805
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000806 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000807 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000808 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000809 Options.Freestanding = Options.NoBuiltin = 1;
810
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000811 if (EnableHeinousExtensions)
812 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000813
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000814 Options.MathErrno = MathErrno;
815
Douglas Gregor375733c2009-03-10 00:06:19 +0000816 Options.InstantiationDepth = TemplateDepth;
817
Chris Lattnerddae7102008-12-04 22:54:33 +0000818 // Override the default runtime if the user requested it.
819 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000820 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000821 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000822 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000823
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000824 if (ObjCNonFragileABI)
825 Options.ObjCNonFragileABI = 1;
Daniel Dunbar5523e862009-05-04 05:16:21 +0000826
Daniel Dunbar72370582009-05-05 18:52:50 +0000827 Options.ObjCTightLayout = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000828
829 if (EmitAllDecls)
830 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000831
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000832 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
833 // support.
834 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000835
836 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000837 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000838 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000839
840 assert(PICLevel <= 2 && "Invalid value for -pic-level");
841 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000842
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000843 Options.GNUInline = !Options.C99;
Chris Lattnerd7f00522009-05-06 04:38:30 +0000844 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000845 Options.NoInline = !OptSize && !OptLevel;
846
847 Options.Static = StaticDefine;
848
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000849 if (MainFileName.getPosition())
850 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000851}
852
853//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000854// Target Triple Processing.
855//===----------------------------------------------------------------------===//
856
857static llvm::cl::opt<std::string>
858TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000859 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000860
Chris Lattnerfc457002008-03-05 01:18:20 +0000861static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000862Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000863
Chris Lattner2b168e02008-09-30 01:13:12 +0000864static llvm::cl::opt<std::string>
865MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000866 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000867
Chris Lattner01de9c82008-09-30 20:16:56 +0000868// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
869// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000870
871// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000872static void HandleMacOSVersionMin(std::string &Triple) {
873 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
874 if (DarwinDashIdx == std::string::npos) {
875 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000876 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000877 exit(1);
878 }
879 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
880
Chris Lattner01de9c82008-09-30 20:16:56 +0000881 // Remove the number.
882 Triple.resize(DarwinNumIdx);
883
884 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
885 bool MacOSVersionMinIsInvalid = false;
886 int VersionNum = 0;
887 if (MacOSVersionMin.size() < 4 ||
888 MacOSVersionMin.substr(0, 3) != "10." ||
889 !isdigit(MacOSVersionMin[3])) {
890 MacOSVersionMinIsInvalid = true;
891 } else {
892 const char *Start = MacOSVersionMin.c_str()+3;
893 char *End = 0;
894 VersionNum = (int)strtol(Start, &End, 10);
895
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000896 // The version number must be in the range 0-9.
897 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
898
Chris Lattner01de9c82008-09-30 20:16:56 +0000899 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
900 Triple += llvm::itostr(VersionNum+4);
901
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000902 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
903 // Add the period piece (.7) to the end of the triple. This gives us
904 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000905 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000906 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
907 MacOSVersionMinIsInvalid = true;
908 }
909 }
910
911 if (MacOSVersionMinIsInvalid) {
912 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000913 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000914 MacOSVersionMin.c_str());
915 exit(1);
916 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000917 else if (VersionNum <= 4 &&
918 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
919 fprintf(stderr,
920 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
921 MacOSVersionMin.c_str());
922 exit(1);
923 }
924
Chris Lattner01de9c82008-09-30 20:16:56 +0000925}
926
Daniel Dunbar93f64532009-04-10 19:52:24 +0000927static llvm::cl::opt<std::string>
928IPhoneOSVersionMin("miphoneos-version-min",
929 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
930
931// If -miphoneos-version-min=2.2 is specified, change the triple from being
932// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
933// 9 as the default major Darwin number, and encode the iPhone OS version
934// number in the minor version and revision.
935
936// FIXME: We should have the driver do this instead.
937static void HandleIPhoneOSVersionMin(std::string &Triple) {
938 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
939 if (DarwinDashIdx == std::string::npos) {
940 fprintf(stderr,
941 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
942 exit(1);
943 }
944 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
945
946 // Remove the number.
947 Triple.resize(DarwinNumIdx);
948
949 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
950 bool IPhoneOSVersionMinIsInvalid = false;
951 int VersionNum = 0;
952 if (IPhoneOSVersionMin.size() < 3 ||
953 !isdigit(IPhoneOSVersionMin[0])) {
954 IPhoneOSVersionMinIsInvalid = true;
955 } else {
956 const char *Start = IPhoneOSVersionMin.c_str();
957 char *End = 0;
958 VersionNum = (int)strtol(Start, &End, 10);
959
960 // The version number must be in the range 0-9.
961 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
962
963 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
964 Triple += "9." + llvm::itostr(VersionNum);
965
966 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
967 // Add the period piece (.2) to the end of the triple. This gives us
968 // something like ...-darwin9.2.2
969 Triple += End;
970 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
971 IPhoneOSVersionMinIsInvalid = true;
972 }
973 }
974
975 if (IPhoneOSVersionMinIsInvalid) {
976 fprintf(stderr,
977 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
978 IPhoneOSVersionMin.c_str());
979 exit(1);
980 }
981}
982
Chris Lattner01de9c82008-09-30 20:16:56 +0000983/// CreateTargetTriple - Process the various options that affect the target
984/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000985static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000986 // Initialize base triple. If a -triple option has been specified, use
987 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000988 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000989 if (Triple.empty())
990 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000991
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000992 // If -arch foo was specified, remove the architecture from the triple we have
993 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000994
995 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +0000996 if (!Arch.empty()) {
997 // Decompose the base triple into "arch" and suffix.
998 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000999
Chris Lattner2b168e02008-09-30 01:13:12 +00001000 if (FirstDashIdx == std::string::npos) {
1001 fprintf(stderr,
1002 "Malformed target triple: \"%s\" ('-' could not be found).\n",
1003 Triple.c_str());
1004 exit(1);
1005 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +00001006
1007 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1008 if (Arch == "ppc")
1009 Arch = "powerpc";
1010 else if (Arch == "ppc64")
1011 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +00001012
Chris Lattner2b168e02008-09-30 01:13:12 +00001013 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1014 }
1015
1016 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1017 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +00001018 if (!MacOSVersionMin.empty())
1019 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +00001020 else if (!IPhoneOSVersionMin.empty())
1021 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +00001022
Chris Lattner2b168e02008-09-30 01:13:12 +00001023 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001024}
1025
1026//===----------------------------------------------------------------------===//
Chris Lattner94269d72009-04-21 05:40:52 +00001027// SourceManager initialization.
Chris Lattner4b009652007-07-25 00:24:17 +00001028//===----------------------------------------------------------------------===//
1029
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001030static bool InitializeSourceManager(Preprocessor &PP,
1031 const std::string &InFile) {
1032 // Figure out where to get and map in the main file.
1033 SourceManager &SourceMgr = PP.getSourceManager();
1034 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbarbb56def2009-04-27 21:19:07 +00001035
1036 if (EmptyInputOnly) {
1037 const char *EmptyStr = "";
1038 llvm::MemoryBuffer *SB =
1039 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1040 SourceMgr.createMainFileIDForMemBuffer(SB);
1041 } else if (InFile != "-") {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001042 const FileEntry *File = FileMgr.getFile(InFile);
1043 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1044 if (SourceMgr.getMainFileID().isInvalid()) {
1045 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1046 << InFile.c_str();
1047 return true;
1048 }
1049 } else {
1050 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1051
1052 // If stdin was empty, SB is null. Cons up an empty memory
1053 // buffer now.
1054 if (!SB) {
1055 const char *EmptyStr = "";
1056 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1057 }
1058
1059 SourceMgr.createMainFileIDForMemBuffer(SB);
1060 if (SourceMgr.getMainFileID().isInvalid()) {
1061 PP.getDiagnostics().Report(FullSourceLoc(),
1062 diag::err_fe_error_reading_stdin);
1063 return true;
1064 }
1065 }
1066
1067 return false;
1068}
1069
Chris Lattner47b6a162008-04-19 23:09:31 +00001070
Chris Lattner94269d72009-04-21 05:40:52 +00001071//===----------------------------------------------------------------------===//
1072// Preprocessor Initialization
1073//===----------------------------------------------------------------------===//
Sam Bishop61a20782008-04-14 14:41:57 +00001074
Chris Lattner94269d72009-04-21 05:40:52 +00001075// FIXME: Preprocessor builtins to support.
1076// -A... - Play with #assertions
1077// -undef - Undefine all predefined macros
Chris Lattnerb62396d2009-04-08 20:15:42 +00001078
Chris Lattner94269d72009-04-21 05:40:52 +00001079static llvm::cl::list<std::string>
1080D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1081 llvm::cl::desc("Predefine the specified macro"));
1082static llvm::cl::list<std::string>
1083U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1084 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001085
Chris Lattner94269d72009-04-21 05:40:52 +00001086static llvm::cl::list<std::string>
1087ImplicitIncludes("include", llvm::cl::value_desc("file"),
1088 llvm::cl::desc("Include file before parsing"));
1089static llvm::cl::list<std::string>
1090ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1091 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001092
Chris Lattner94269d72009-04-21 05:40:52 +00001093static llvm::cl::opt<std::string>
1094ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1095 llvm::cl::desc("Include precompiled header file"));
1096
1097static llvm::cl::opt<std::string>
1098ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1099 llvm::cl::desc("Include file before parsing"));
1100
Chris Lattner4b009652007-07-25 00:24:17 +00001101
1102//===----------------------------------------------------------------------===//
1103// Preprocessor include path information.
1104//===----------------------------------------------------------------------===//
1105
1106// This tool exports a large number of command line options to control how the
1107// preprocessor searches for header files. At root, however, the Preprocessor
1108// object takes a very simple interface: a list of directories to search for
1109//
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001110// FIXME: -nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001111// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001112//
Chris Lattner4b009652007-07-25 00:24:17 +00001113
1114static llvm::cl::opt<bool>
1115nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1116
1117// Various command line options. These four add directories to each chain.
1118static llvm::cl::list<std::string>
1119F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1120 llvm::cl::desc("Add directory to framework include search path"));
1121static llvm::cl::list<std::string>
1122I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1123 llvm::cl::desc("Add directory to include search path"));
1124static llvm::cl::list<std::string>
1125idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1126 llvm::cl::desc("Add directory to AFTER include search path"));
1127static llvm::cl::list<std::string>
1128iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1129 llvm::cl::desc("Add directory to QUOTE include search path"));
1130static llvm::cl::list<std::string>
1131isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1132 llvm::cl::desc("Add directory to SYSTEM include search path"));
1133
1134// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1135static llvm::cl::list<std::string>
1136iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1137 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1138static llvm::cl::list<std::string>
1139iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1140 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1141static llvm::cl::list<std::string>
1142iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1143 llvm::cl::Prefix,
1144 llvm::cl::desc("Set directory to include search path with prefix"));
1145
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001146static llvm::cl::opt<std::string>
1147isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1148 llvm::cl::desc("Set the system root directory (usually /)"));
1149
Chris Lattner4b009652007-07-25 00:24:17 +00001150// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001151
Chris Lattner4b009652007-07-25 00:24:17 +00001152/// InitializeIncludePaths - Process the -I options and set them in the
1153/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001154void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1155 FileManager &FM, const LangOptions &Lang) {
1156 InitHeaderSearch Init(Headers, Verbose, isysroot);
1157
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001158 // Handle -I... and -F... options, walking the lists in parallel.
1159 unsigned Iidx = 0, Fidx = 0;
1160 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1161 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001162 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001163 ++Iidx;
1164 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001165 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001166 ++Fidx;
1167 }
1168 }
Chris Lattner4b009652007-07-25 00:24:17 +00001169
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001170 // Consume what's left from whatever list was longer.
1171 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001172 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001173 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001174 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001175
1176 // Handle -idirafter... options.
1177 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001178 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1179 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001180
1181 // Handle -iquote... options.
1182 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001183 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001184
1185 // Handle -isystem... options.
1186 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001187 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001188
1189 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1190 // parallel, processing the values in order of occurance to get the right
1191 // prefixes.
1192 {
1193 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1194 unsigned iprefix_idx = 0;
1195 unsigned iwithprefix_idx = 0;
1196 unsigned iwithprefixbefore_idx = 0;
1197 bool iprefix_done = iprefix_vals.empty();
1198 bool iwithprefix_done = iwithprefix_vals.empty();
1199 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1200 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1201 if (!iprefix_done &&
1202 (iwithprefix_done ||
1203 iprefix_vals.getPosition(iprefix_idx) <
1204 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1205 (iwithprefixbefore_done ||
1206 iprefix_vals.getPosition(iprefix_idx) <
1207 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1208 Prefix = iprefix_vals[iprefix_idx];
1209 ++iprefix_idx;
1210 iprefix_done = iprefix_idx == iprefix_vals.size();
1211 } else if (!iwithprefix_done &&
1212 (iwithprefixbefore_done ||
1213 iwithprefix_vals.getPosition(iwithprefix_idx) <
1214 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001215 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1216 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001217 ++iwithprefix_idx;
1218 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1219 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001220 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1221 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001222 ++iwithprefixbefore_idx;
1223 iwithprefixbefore_done =
1224 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1225 }
1226 }
1227 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001228
Nico Weber770e3882008-08-22 09:25:22 +00001229 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001230
Daniel Dunbar4e604292009-02-21 20:52:41 +00001231 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001232 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001233 llvm::sys::Path::GetMainExecutable(Argv0,
1234 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001235 if (!MainExecutablePath.isEmpty()) {
1236 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1237 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001238
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001239 // Get foo/lib/clang/<version>/include
Daniel Dunbar4e604292009-02-21 20:52:41 +00001240 MainExecutablePath.appendComponent("lib");
1241 MainExecutablePath.appendComponent("clang");
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001242 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbar4e604292009-02-21 20:52:41 +00001243 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001244
1245 // We pass true to ignore sysroot so that we *always* look for clang headers
1246 // relative to our executable, never relative to -isysroot.
1247 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1248 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001249 }
1250
Nico Weber770e3882008-08-22 09:25:22 +00001251 if (!nostdinc)
1252 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001253
1254 // Now that we have collected all of the include paths, merge them all
1255 // together and tell the preprocessor about them.
1256
Nico Weber770e3882008-08-22 09:25:22 +00001257 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001258}
1259
Chris Lattner94269d72009-04-21 05:40:52 +00001260void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1261{
1262 // Add macros from the command line.
1263 unsigned d = 0, D = D_macros.size();
1264 unsigned u = 0, U = U_macros.size();
1265 while (d < D || u < U) {
1266 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1267 InitOpts.addMacroDef(D_macros[d++]);
1268 else
1269 InitOpts.addMacroUndef(U_macros[u++]);
1270 }
1271
1272 // If -imacros are specified, include them now. These are processed before
1273 // any -include directives.
1274 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1275 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1276
1277 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) {
1278 // We want to add these paths to the predefines buffer in order, make a
1279 // temporary vector to sort by their occurrence.
1280 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1281
1282 if (!ImplicitIncludePTH.empty())
1283 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1284 &ImplicitIncludePTH));
1285 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1286 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1287 &ImplicitIncludes[i]));
1288 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1289
1290
1291 // Now that they are ordered by position, add to the predefines buffer.
1292 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1293 std::string *Ptr = OrderedPaths[i].second;
1294 if (!ImplicitIncludes.empty() &&
1295 Ptr >= &ImplicitIncludes[0] &&
1296 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1297 InitOpts.addInclude(*Ptr, false);
1298 } else {
1299 assert(Ptr == &ImplicitIncludePTH);
1300 InitOpts.addInclude(*Ptr, true);
1301 }
1302 }
1303 }
1304}
1305
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001306//===----------------------------------------------------------------------===//
1307// Driver PreprocessorFactory - For lazily generating preprocessors ...
1308//===----------------------------------------------------------------------===//
1309
1310namespace {
1311class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001312 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001313 Diagnostic &Diags;
1314 const LangOptions &LangInfo;
1315 TargetInfo &Target;
1316 SourceManager &SourceMgr;
1317 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001318
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001319public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001320 DriverPreprocessorFactory(const std::string &infile,
1321 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001322 TargetInfo &target, SourceManager &SM,
1323 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001324 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001325 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001326
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001327
1328 virtual ~DriverPreprocessorFactory() {}
1329
1330 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001331 llvm::OwningPtr<PTHManager> PTHMgr;
1332
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001333 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1334 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1335 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001336 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001337 }
1338
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001339 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001340 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1341 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001342 PTHMgr.reset(PTHManager::Create(x, &Diags,
1343 TokenCache.empty() ? Diagnostic::Error
1344 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001345 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001346
Ted Kremenek6348cc62009-03-22 06:42:39 +00001347 if (Diags.hasErrorOccurred())
1348 exit(1);
1349
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001350 // Create the Preprocessor.
1351 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1352 SourceMgr, HeaderInfo,
1353 PTHMgr.get()));
1354
1355 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1356 // That argument is used as the IdentifierInfoLookup argument to
1357 // IdentifierTable's ctor.
1358 if (PTHMgr) {
1359 PTHMgr->setPreprocessor(PP.get());
1360 PP->setPTHManager(PTHMgr.take());
1361 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001362
Chris Lattner94269d72009-04-21 05:40:52 +00001363 PreprocessorInitOptions InitOpts;
1364 InitializePreprocessorInitOptions(InitOpts);
1365 if (InitializePreprocessor(*PP, InFile, InitOpts))
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001366 return 0;
Chris Lattner94269d72009-04-21 05:40:52 +00001367
Daniel Dunbarebfb1bc2009-05-03 09:35:25 +00001368 std::string ErrStr;
1369 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1370 if (!DFG && !ErrStr.empty()) {
1371 fprintf(stderr, "%s", ErrStr.c_str());
1372 return 0;
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001373 }
1374
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001375 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001376 }
1377};
1378}
Chris Lattner4b009652007-07-25 00:24:17 +00001379
Chris Lattner4b009652007-07-25 00:24:17 +00001380//===----------------------------------------------------------------------===//
1381// Basic Parser driver
1382//===----------------------------------------------------------------------===//
1383
Chris Lattner9d818a22008-04-19 23:25:44 +00001384static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001385 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001386 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001387
1388 // Parsing the specified input file.
1389 P.ParseTranslationUnit();
1390 delete PA;
1391}
1392
1393//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001394// Code generation options
1395//===----------------------------------------------------------------------===//
1396
1397static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001398GenerateDebugInfo("g",
1399 llvm::cl::desc("Generate source level debug information"));
1400
Daniel Dunbar9101a632009-02-17 19:47:34 +00001401static llvm::cl::opt<std::string>
1402TargetCPU("mcpu",
1403 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1404
Daniel Dunbar07181d72009-05-06 03:16:41 +00001405static llvm::cl::list<std::string>
1406TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1407
1408/// ComputeTargetFeatures - Recompute the target feature list to only
1409/// be the list of things that are enabled, based on the target cpu
1410/// and feature list.
1411static void ComputeFeatureMap(TargetInfo *Target,
1412 llvm::StringMap<bool> &Features) {
1413 assert(Features.empty() && "invalid map");
1414
1415 // Initialize the feature map based on the target.
1416 Target->getDefaultFeatures(TargetCPU, Features);
1417
1418 // Apply the user specified deltas.
1419 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1420 ie = TargetFeatures.end(); it != ie; ++it) {
1421 const char *Name = it->c_str();
1422
1423 // FIXME: Don't handle errors like this.
1424 if (Name[0] != '-' && Name[0] != '+') {
1425 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1426 Name);
1427 exit(1);
1428 }
1429
1430 llvm::StringMap<bool>::iterator it = Features.find(Name + 1);
1431 if (it == Features.end()) {
1432 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1433 Name);
1434 exit(1);
1435 }
1436
1437 // FIXME: Actually, we need to apply all the features implied by
1438 // this feature.
1439 it->second = (Name[0] == '+');
1440 }
1441}
1442
Chris Lattner8a9615c2009-03-16 18:41:18 +00001443static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001444 const LangOptions &LangOpts,
1445 const llvm::StringMap<bool> &Features) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001446 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001447 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001448 if (OptSize) {
1449 // -Os implies -O2
1450 // FIXME: Diagnose conflicting options.
1451 Opts.OptimizationLevel = 2;
1452 } else {
1453 Opts.OptimizationLevel = OptLevel;
1454 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001455
1456 // FIXME: There are llvm-gcc options to control these selectively.
1457 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1458 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001459 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001460
1461#ifdef NDEBUG
1462 Opts.VerifyModule = 0;
1463#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001464
1465 Opts.CPU = TargetCPU;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001466 Opts.Features.clear();
1467 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1468 ie = Features.end(); it != ie; ++it) {
1469 // FIXME: If we are completely confident that we have the right
1470 // set, we only need to pass the minuses.
1471 std::string Name(it->second ? "+" : "-");
1472 Name += it->first();
1473 Opts.Features.push_back(Name);
1474 }
Chris Lattnere8f70712009-02-18 01:23:44 +00001475
Chris Lattnerf04a7562009-03-26 05:00:52 +00001476 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1477
Chris Lattnere8f70712009-02-18 01:23:44 +00001478 // Handle -ftime-report.
1479 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001480}
1481
1482//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001483// Fix-It Options
1484//===----------------------------------------------------------------------===//
1485static llvm::cl::list<ParsedSourceLocation>
1486FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1487 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1488
1489//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001490// -dump-build-information Stuff
1491//===----------------------------------------------------------------------===//
1492
1493static llvm::cl::opt<std::string>
1494DumpBuildInformation("dump-build-information",
1495 llvm::cl::value_desc("filename"),
1496 llvm::cl::desc("output a dump of some build information to a file"));
1497
1498static llvm::raw_ostream *BuildLogFile = 0;
1499
1500/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1501/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1502namespace {
1503class LoggingDiagnosticClient : public DiagnosticClient {
1504 llvm::OwningPtr<DiagnosticClient> Chain1;
1505 llvm::OwningPtr<DiagnosticClient> Chain2;
1506public:
1507
1508 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1509 // Output diags both where requested...
1510 Chain1.reset(Normal);
1511 // .. and to our log file.
1512 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1513 !NoShowColumn,
1514 !NoCaretDiagnostics,
1515 !NoShowLocation,
1516 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001517 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001518 !NoDiagnosticsFixIt,
1519 MessageLength));
Chris Lattner94859302009-04-17 21:05:01 +00001520 }
1521
1522 virtual void setLangOptions(const LangOptions *LO) {
1523 Chain1->setLangOptions(LO);
1524 Chain2->setLangOptions(LO);
1525 }
1526
1527 virtual bool IncludeInDiagnosticCounts() const {
1528 return Chain1->IncludeInDiagnosticCounts();
1529 }
1530
1531 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1532 const DiagnosticInfo &Info) {
1533 Chain1->HandleDiagnostic(DiagLevel, Info);
1534 Chain2->HandleDiagnostic(DiagLevel, Info);
1535 }
1536};
1537} // end anonymous namespace.
1538
1539static void SetUpBuildDumpLog(unsigned argc, char **argv,
1540 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1541
1542 std::string ErrorInfo;
1543 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1544 ErrorInfo);
1545
1546 if (!ErrorInfo.empty()) {
1547 llvm::errs() << "error opening -dump-build-information file '"
1548 << DumpBuildInformation << "', option ignored!\n";
1549 delete BuildLogFile;
1550 BuildLogFile = 0;
1551 DumpBuildInformation = "";
1552 return;
1553 }
1554
1555 (*BuildLogFile) << "clang-cc command line arguments: ";
1556 for (unsigned i = 0; i != argc; ++i)
1557 (*BuildLogFile) << argv[i] << ' ';
1558 (*BuildLogFile) << '\n';
1559
1560 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1561 // the diagnostic producers and the normal receiver.
1562 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1563}
1564
1565
1566
1567//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001568// Main driver
1569//===----------------------------------------------------------------------===//
1570
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001571/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001572/// action. These consumers can operate on both ASTs that are freshly
1573/// parsed from source files as well as those deserialized from Bitcode.
1574/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001575static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001576 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001577 const LangOptions& LangOpts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001578 const llvm::StringMap<bool>& Features,
Chris Lattner21f72d62008-04-16 06:11:58 +00001579 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001580 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001581 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001582 default:
1583 return NULL;
1584
1585 case ASTPrint:
1586 return CreateASTPrinter();
1587
1588 case ASTDump:
Douglas Gregord7915fd2009-04-26 02:02:08 +00001589 return CreateASTDumper(false);
1590
1591 case ASTDumpFull:
1592 return CreateASTDumper(true);
Chris Lattner7f902922009-02-18 01:20:05 +00001593
1594 case ASTView:
1595 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001596
Chris Lattner7f902922009-02-18 01:20:05 +00001597 case PrintDeclContext:
1598 return CreateDeclContextPrinter();
1599
1600 case EmitHTML:
1601 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001602
Chris Lattner7f902922009-02-18 01:20:05 +00001603 case InheritanceView:
1604 return CreateInheritanceViewer(InheritanceViewCls);
1605
Chris Lattner7f902922009-02-18 01:20:05 +00001606 case EmitAssembly:
1607 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001608 case EmitBC:
1609 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001610 BackendAction Act;
1611 if (ProgAction == EmitAssembly)
1612 Act = Backend_EmitAssembly;
1613 else if (ProgAction == EmitLLVM)
1614 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001615 else if (ProgAction == EmitLLVMOnly)
1616 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001617 else
1618 Act = Backend_EmitBC;
1619
1620 CompileOptions Opts;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001621 InitializeCompileOptions(Opts, LangOpts, Features);
Chris Lattner7f902922009-02-18 01:20:05 +00001622 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001623 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001624 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001625
Douglas Gregorc34897d2009-04-09 22:27:44 +00001626 case GeneratePCH:
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001627 return CreatePCHGenerator(*PP, OutputFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001628
Chris Lattner7f902922009-02-18 01:20:05 +00001629 case RewriteObjC:
1630 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001631
Chris Lattner7f902922009-02-18 01:20:05 +00001632 case RewriteBlocks:
1633 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1634
1635 case RunAnalysis:
1636 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001637 }
1638}
1639
Chris Lattner4b009652007-07-25 00:24:17 +00001640/// ProcessInputFile - Process a single input file with the specified state.
1641///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001642static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001643 const std::string &InFile, ProgActions PA,
1644 const llvm::StringMap<bool> &Features) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001645 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001646 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001647 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00001648 bool CompleteTranslationUnit = true;
Douglas Gregor133d2552009-04-02 01:08:08 +00001649
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001650 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001651 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001652 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1653 PP.getFileManager(), PP.getLangOptions(),
Daniel Dunbar07181d72009-05-06 03:16:41 +00001654 Features, &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001655
1656 if (!Consumer) {
1657 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001658 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001659 return;
1660 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001661
Douglas Gregore0d5c562009-04-14 16:27:31 +00001662 if (ProgAction == GeneratePCH)
1663 CompleteTranslationUnit = false;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001664 break;
1665
Chris Lattneraf669fb2008-10-12 05:03:36 +00001666 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001667 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001668 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001669 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001670 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001671 RawLex.SetKeepWhitespaceMode(true);
1672
1673 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001674 RawLex.LexFromRawLexer(RawTok);
1675 while (RawTok.isNot(tok::eof)) {
1676 PP.DumpToken(RawTok, true);
1677 fprintf(stderr, "\n");
1678 RawLex.LexFromRawLexer(RawTok);
1679 }
1680 ClearSourceMgr = true;
1681 break;
1682 }
Chris Lattner4b009652007-07-25 00:24:17 +00001683 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001684 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001685 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001686 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001687 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001688 do {
1689 PP.Lex(Tok);
1690 PP.DumpToken(Tok, true);
1691 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001692 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001693 ClearSourceMgr = true;
1694 break;
1695 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001696 case RunPreprocessorOnly:
Chris Lattner4b009652007-07-25 00:24:17 +00001697 break;
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001698
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001699 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001700 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001701 CacheTokens(PP, OutputFile);
1702 ClearSourceMgr = true;
1703 break;
1704 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001705
Chris Lattner772a7c12009-04-27 22:02:30 +00001706 case PrintPreprocessedInput:
Chris Lattner4b009652007-07-25 00:24:17 +00001707 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001708
Chris Lattner270d29a2009-04-27 21:45:14 +00001709 case ParseNoop:
Chris Lattner4b009652007-07-25 00:24:17 +00001710 break;
1711
Chris Lattnerefe33382009-02-18 01:51:21 +00001712 case ParsePrintCallbacks: {
1713 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001714 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001715 ClearSourceMgr = true;
1716 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001717 }
1718
1719 case ParseSyntaxOnly: { // -fsyntax-only
1720 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001721 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001722 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001723 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001724
1725 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001726 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001727 ClearSourceMgr = true;
1728 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001729
Chris Lattnerefe33382009-02-18 01:51:21 +00001730 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001731 DoRewriteTest(PP, InFile, OutputFile);
1732 ClearSourceMgr = true;
1733 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001734 }
Douglas Gregor133d2552009-04-02 01:08:08 +00001735
1736 case FixIt:
1737 llvm::TimeRegion Timer(ClangFrontendTimer);
1738 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001739 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001740 PP.getSourceManager(),
1741 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00001742 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001743 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001744
Chris Lattner38a4f182009-04-27 21:25:27 +00001745 if (FixItAtLocations.size() > 0) {
1746 // Even without the "-fixit" flag, with may have some specific
1747 // locations where the user has requested fixes. Process those
1748 // locations now.
1749 if (!FixItRewrite)
1750 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1751 PP.getSourceManager(),
1752 PP.getLangOptions());
Chris Lattner143fd6d2009-03-28 01:37:17 +00001753
Chris Lattner38a4f182009-04-27 21:25:27 +00001754 bool AddedFixitLocation = false;
1755 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1756 Idx != Last; ++Idx) {
1757 RequestedSourceLocation Requested;
1758 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1759 Requested)) {
1760 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1761 FixItAtLocations[Idx].FileName.c_str());
1762 } else {
1763 FixItRewrite->addFixItLocation(Requested);
1764 AddedFixitLocation = true;
Douglas Gregor24b48b02009-04-02 19:05:20 +00001765 }
1766 }
1767
Chris Lattner38a4f182009-04-27 21:25:27 +00001768 if (!AddedFixitLocation) {
1769 // All of the fix-it locations were bad. Don't fix anything.
1770 delete FixItRewrite;
1771 FixItRewrite = 0;
1772 }
1773 }
1774
1775 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner270d29a2009-04-27 21:45:14 +00001776 if (Consumer)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001777 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1778 PP.getSourceManager(),
1779 PP.getTargetInfo(),
1780 PP.getIdentifierTable(),
1781 PP.getSelectorTable(),
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001782 /* FreeMemory = */ !DisableFree,
1783 /* size_reserve = */0,
1784 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattner772a7c12009-04-27 22:02:30 +00001785 llvm::OwningPtr<PCHReader> Reader;
1786 llvm::OwningPtr<ExternalASTSource> Source;
1787
Chris Lattner270d29a2009-04-27 21:45:14 +00001788 if (!ImplicitIncludePCH.empty()) {
Chris Lattner772a7c12009-04-27 22:02:30 +00001789 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1790
Chris Lattner270d29a2009-04-27 21:45:14 +00001791 // The user has asked us to include a precompiled header. Load
1792 // the precompiled header into the AST context.
Chris Lattner270d29a2009-04-27 21:45:14 +00001793 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1794 case PCHReader::Success: {
Douglas Gregor32de6312009-04-28 18:58:38 +00001795 // Set the predefines buffer as suggested by the PCH
1796 // reader. Typically, the predefines buffer will be empty.
1797 PP.setPredefines(Reader->getSuggestedPredefines());
1798
Chris Lattner270d29a2009-04-27 21:45:14 +00001799 // Attach the PCH reader to the AST context as an external AST
1800 // source, so that declarations will be deserialized from the
1801 // PCH file as needed.
Chris Lattner772a7c12009-04-27 22:02:30 +00001802 if (ContextOwner) {
1803 Source.reset(Reader.take());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001804 ContextOwner->setExternalSource(Source);
Chris Lattner772a7c12009-04-27 22:02:30 +00001805 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001806 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001807 }
1808
Chris Lattner270d29a2009-04-27 21:45:14 +00001809 case PCHReader::Failure:
1810 // Unrecoverable failure: don't even try to process the input
1811 // file.
1812 return;
1813
1814 case PCHReader::IgnorePCH:
Douglas Gregor9ea9b162009-04-28 22:01:16 +00001815 // No suitable PCH file could be found. Return an error.
1816 return;
1817
1818#if 0
1819 // FIXME: We can recover from failed attempts to load PCH
1820 // files. This code will do so, if we ever want to enable it.
1821
Chris Lattner270d29a2009-04-27 21:45:14 +00001822 // We delayed the initialization of builtins in the hope of
1823 // loading the PCH file. Since the PCH file could not be
1824 // loaded, initialize builtins now.
1825 if (ContextOwner)
1826 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor9ea9b162009-04-28 22:01:16 +00001827#endif
Chris Lattner270d29a2009-04-27 21:45:14 +00001828 }
1829
1830 // Finish preprocessor initialization. We do this now (rather
1831 // than earlier) because this initialization creates new source
1832 // location entries in the source manager, which must come after
1833 // the source location entries for the PCH file.
1834 if (InitializeSourceManager(PP, InFile))
1835 return;
Ted Kremenek88eebed2009-01-28 04:29:29 +00001836 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001837
Chris Lattner270d29a2009-04-27 21:45:14 +00001838
1839 // If we have an ASTConsumer, run the parser with it.
1840 if (Consumer)
1841 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
1842 CompleteTranslationUnit);
1843
1844 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
1845 llvm::TimeRegion Timer(ClangFrontendTimer);
1846 Token Tok;
1847 // Start parsing the specified input file.
1848 PP.EnterMainSourceFile();
1849 do {
1850 PP.Lex(Tok);
1851 } while (Tok.isNot(tok::eof));
1852 ClearSourceMgr = true;
1853 } else if (PA == ParseNoop) { // -parse-noop
1854 llvm::TimeRegion Timer(ClangFrontendTimer);
1855 ParseFile(PP, new MinimalAction(PP));
1856 ClearSourceMgr = true;
Chris Lattner772a7c12009-04-27 22:02:30 +00001857 } else if (PA == PrintPreprocessedInput){ // -E mode.
1858 llvm::TimeRegion Timer(ClangFrontendTimer);
1859 DoPrintPreprocessedInput(PP, OutputFile);
1860 ClearSourceMgr = true;
Chris Lattner270d29a2009-04-27 21:45:14 +00001861 }
1862
Chris Lattner38a4f182009-04-27 21:25:27 +00001863 if (FixItRewrite)
1864 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1865
1866 // If in -disable-free mode, don't deallocate ASTContext.
1867 if (DisableFree)
1868 ContextOwner.take();
1869 else
1870 ContextOwner.reset(); // Delete ASTContext
1871
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001872 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001873 if (CheckDiagnostics(PP))
1874 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001875
Chris Lattner4b009652007-07-25 00:24:17 +00001876 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001877 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001878 PP.PrintStats();
1879 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001880 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001881 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001882 fprintf(stderr, "\n");
1883 }
1884
1885 // For a multi-file compilation, some things are ok with nuking the source
1886 // manager tables, other require stable fileid/macroid's across multiple
1887 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001888 if (ClearSourceMgr)
1889 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001890
1891 if (DisableFree)
1892 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001893}
1894
1895static llvm::cl::list<std::string>
1896InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1897
Douglas Gregor965a13c2009-05-02 00:03:46 +00001898/// \brief Determine the width of the terminal we'll be printing to,
1899/// if any.
1900///
1901/// \returns the width of the terminal (in characters), if there is a
1902/// terminal. If there is no terminal, returns 0.
1903static unsigned getTerminalWidth() {
Douglas Gregor3dd11e82009-05-03 03:52:38 +00001904 // If COLUMNS is defined in the environment, wrap to that many columns.
1905 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
1906 int Columns = atoi(ColumnsStr);
1907 if (Columns > 0)
1908 return Columns;
1909 }
1910
Douglas Gregor965a13c2009-05-02 00:03:46 +00001911 // Is this a terminal? If not, don't wrap by default.
Douglas Gregor3dd11e82009-05-03 03:52:38 +00001912 if (!llvm::sys::Process::StandardErrIsDisplayed())
Douglas Gregor965a13c2009-05-02 00:03:46 +00001913 return 0;
1914
Douglas Gregor3dd11e82009-05-03 03:52:38 +00001915#if HAVE_SYS_TYPES_H
Douglas Gregor965a13c2009-05-02 00:03:46 +00001916 // Try to determine the width of the terminal.
1917 struct winsize ws;
1918 unsigned Columns = 80; // A guess, in case the ioctl fails.
1919 if (ioctl(2, TIOCGWINSZ, &ws) == 0)
1920 Columns = ws.ws_col;
1921
1922 // Give ourselves just a little extra room, since printing to the
1923 // end of the terminal will make it wrap when we don't want it to.
1924 if (Columns)
1925 --Columns;
1926 return Columns;
1927#endif
1928
1929 return 0;
1930}
1931
Chris Lattner4b009652007-07-25 00:24:17 +00001932int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001933 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001934 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001935 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001936 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001937
Chris Lattnerefe33382009-02-18 01:51:21 +00001938 if (TimeReport)
1939 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1940
Chris Lattner4b009652007-07-25 00:24:17 +00001941 // If no input was specified, read from stdin.
1942 if (InputFilenames.empty())
1943 InputFilenames.push_back("-");
Douglas Gregor965a13c2009-05-02 00:03:46 +00001944
Ted Kremenekb240e822007-12-11 23:28:38 +00001945 // Create the diagnostic client for reporting errors or for
1946 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00001947 llvm::OwningPtr<DiagnosticClient> DiagClient;
1948 if (VerifyDiagnostics) {
1949 // When checking diagnostics, just buffer them up.
1950 DiagClient.reset(new TextDiagnosticBuffer());
1951 if (InputFilenames.size() != 1) {
1952 fprintf(stderr, "-verify only works on single input files for now.\n");
1953 return 1;
1954 }
1955 if (!HTMLDiag.empty()) {
1956 fprintf(stderr, "-verify and -html-diags don't work together\n");
1957 return 1;
1958 }
1959 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00001960 // Print diagnostics to stderr by default.
Douglas Gregor965a13c2009-05-02 00:03:46 +00001961
1962 // If -fmessage-length=N was not specified, determine whether this
1963 // is a terminal and, if so, implicitly define -fmessage-length
1964 // appropriately.
1965 if (MessageLength.getNumOccurrences() == 0)
1966 MessageLength.setValue(getTerminalWidth());
1967
Chris Lattner5f7937d2009-04-17 20:40:01 +00001968 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00001969 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001970 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00001971 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00001972 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001973 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001974 !NoDiagnosticsFixIt,
1975 MessageLength));
Ted Kremenek5c341732008-08-07 17:49:57 +00001976 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00001977 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00001978 }
Chris Lattner94859302009-04-17 21:05:01 +00001979
1980 if (!DumpBuildInformation.empty()) {
1981 if (!HTMLDiag.empty()) {
1982 fprintf(stderr,
1983 "-dump-build-information and -html-diags don't work together\n");
1984 return 1;
1985 }
1986
1987 SetUpBuildDumpLog(argc, argv, DiagClient);
1988 }
1989
Ted Kremenek5c341732008-08-07 17:49:57 +00001990
Chris Lattner4b009652007-07-25 00:24:17 +00001991 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001992 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001993 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001994 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001995
Chris Lattner45a56e02007-12-05 23:24:17 +00001996 // -I- is a deprecated GCC feature, scan for it and reject it.
1997 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1998 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001999 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00002000 I_dirs.erase(I_dirs.begin()+i);
2001 --i;
2002 }
2003 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002004
2005 // Get information about the target being compiled for.
2006 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00002007 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2008
Chris Lattner2c77d852008-03-14 06:12:05 +00002009 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00002010 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2011 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002012 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00002013 }
Chris Lattner45a56e02007-12-05 23:24:17 +00002014
Daniel Dunbar9c321102009-01-20 23:17:32 +00002015 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00002016 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00002017
Ted Kremenek2a4224a2008-06-06 22:42:39 +00002018 llvm::OwningPtr<SourceManager> SourceMgr;
2019
Chris Lattnere1be6022009-04-14 23:22:57 +00002020 // Create a file manager object to provide access to and cache the filesystem.
2021 FileManager FileMgr;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00002022
Daniel Dunbar07181d72009-05-06 03:16:41 +00002023 // Compute the feature set, unfortunately this effects the language!
2024 llvm::StringMap<bool> Features;
2025 ComputeFeatureMap(Target.get(), Features);
2026
Chris Lattner4b009652007-07-25 00:24:17 +00002027 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00002028 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00002029
Chris Lattner2b989562009-03-04 21:40:56 +00002030 /// Create a SourceManager object. This tracks and owns all the file
2031 /// buffers allocated to a translation unit.
2032 if (!SourceMgr)
2033 SourceMgr.reset(new SourceManager());
2034 else
2035 SourceMgr->clearIDTables();
2036
2037 // Initialize language options, inferring file types from input filenames.
2038 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00002039 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00002040
Chris Lattner2b989562009-03-04 21:40:56 +00002041 InitializeBaseLanguage();
2042 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002043 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar07181d72009-05-06 03:16:41 +00002044 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002045
2046 // Process the -I options and set them in the HeaderInfo.
2047 HeaderSearch HeaderInfo(FileMgr);
2048
Chris Lattnere1be6022009-04-14 23:22:57 +00002049
Chris Lattner2b989562009-03-04 21:40:56 +00002050 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2051
2052 // Set up the preprocessor with these options.
2053 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
2054 *SourceMgr.get(), HeaderInfo);
2055
2056 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2057
2058 if (!PP)
2059 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002060
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002061 if (ImplicitIncludePCH.empty() &&
2062 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002063 continue;
2064
Chris Lattner5f7937d2009-04-17 20:40:01 +00002065 if (!HTMLDiag.empty())
2066 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00002067
2068 // Process the source file.
Daniel Dunbar07181d72009-05-06 03:16:41 +00002069 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002070
Chris Lattner2961dc52009-04-17 20:16:08 +00002071 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00002072 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00002073 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002074
Mike Stump91d01352009-01-28 02:43:35 +00002075 if (Verbose)
2076 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2077 " hosted on " LLVM_HOSTTRIPLE "\n");
2078
Mike Stumpc4ba6cd2009-04-28 01:19:10 +00002079 if (!NoCaretDiagnostics)
2080 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2081 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2082 (NumDiagnostics == 1 ? "" : "s"));
Chris Lattner4b009652007-07-25 00:24:17 +00002083
2084 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002085 FileMgr.PrintStats();
2086 fprintf(stderr, "\n");
2087 }
Chris Lattner94859302009-04-17 21:05:01 +00002088
2089 delete ClangFrontendTimer;
2090 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002091
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002092 // If verifying diagnostics and we reached here, all is well.
2093 if (VerifyDiagnostics)
2094 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002095
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002096 // Managed static deconstruction. Useful for making things like
2097 // -time-passes usable.
2098 llvm::llvm_shutdown();
2099
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002100 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002101}