blob: ca8d6e51172676184f5b5065f2050e39d529a3b2 [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>
70#endif
Douglas Gregor24b48b02009-04-02 19:05:20 +000071
Chris Lattner4b009652007-07-25 00:24:17 +000072using namespace clang;
73
74//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000075// Source Location Parser
76//===----------------------------------------------------------------------===//
77
78/// \brief A source location that has been parsed on the command line.
79struct ParsedSourceLocation {
80 std::string FileName;
81 unsigned Line;
82 unsigned Column;
83
84 /// \brief Try to resolve the file name of a parsed source location.
85 ///
86 /// \returns true if there was an error, false otherwise.
87 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
88};
89
90bool
91ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
92 RequestedSourceLocation &Result) {
93 const FileEntry *File = FileMgr.getFile(FileName);
94 if (!File)
95 return true;
96
97 Result.File = File;
98 Result.Line = Line;
99 Result.Column = Column;
100 return false;
101}
102
103namespace llvm {
104 namespace cl {
105 /// \brief Command-line option parser that parses source locations.
106 ///
107 /// Source locations are of the form filename:line:column.
108 template<>
109 class parser<ParsedSourceLocation>
110 : public basic_parser<ParsedSourceLocation> {
111 public:
112 bool parse(Option &O, const char *ArgName,
113 const std::string &ArgValue,
114 ParsedSourceLocation &Val);
115 };
116
117 bool
118 parser<ParsedSourceLocation>::
119 parse(Option &O, const char *ArgName, const std::string &ArgValue,
120 ParsedSourceLocation &Val) {
121 using namespace clang;
122
123 const char *ExpectedFormat
124 = "source location must be of the form filename:line:column";
125 std::string::size_type SecondColon = ArgValue.rfind(':');
126 if (SecondColon == std::string::npos) {
127 std::fprintf(stderr, "%s\n", ExpectedFormat);
128 return true;
129 }
130 char *EndPtr;
131 long Column
132 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
133 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
134 std::fprintf(stderr, "%s\n", ExpectedFormat);
135 return true;
136 }
137
138 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
139 if (SecondColon == std::string::npos) {
140 std::fprintf(stderr, "%s\n", ExpectedFormat);
141 return true;
142 }
143 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
144 if (EndPtr != ArgValue.c_str() + SecondColon) {
145 std::fprintf(stderr, "%s\n", ExpectedFormat);
146 return true;
147 }
148
149 Val.FileName = ArgValue.substr(0, FirstColon);
150 Val.Line = Line;
151 Val.Column = Column;
152 return false;
153 }
154 }
155}
156
157//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000158// Global options.
159//===----------------------------------------------------------------------===//
160
Chris Lattnerefe33382009-02-18 01:51:21 +0000161/// ClangFrontendTimer - The front-end activities should charge time to it with
162/// TimeRegion. The -ftime-report option controls whether this will do
163/// anything.
164llvm::Timer *ClangFrontendTimer = 0;
165
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000166static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000167
Chris Lattner4b009652007-07-25 00:24:17 +0000168static llvm::cl::opt<bool>
169Verbose("v", llvm::cl::desc("Enable verbose output"));
170static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000171Stats("print-stats",
172 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000173static llvm::cl::opt<bool>
174DisableFree("disable-free",
175 llvm::cl::desc("Disable freeing of memory on exit"),
176 llvm::cl::init(false));
Daniel Dunbarbb56def2009-04-27 21:19:07 +0000177static llvm::cl::opt<bool>
178EmptyInputOnly("empty-input-only",
179 llvm::cl::desc("Force running on an empty input file"));
Chris Lattner4b009652007-07-25 00:24:17 +0000180
181enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000182 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000183 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000184 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000185 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000186 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000187 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000188 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000189 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000190 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000191 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek24612ae2008-03-18 21:19:49 +0000192 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000193 ASTPrint, // Parse ASTs and print them.
194 ASTDump, // Parse ASTs and dump them.
Douglas Gregord7915fd2009-04-26 02:02:08 +0000195 ASTDumpFull, // Parse ASTs and dump them, including the
196 // contents of a PCH file.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000197 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000198 PrintDeclContext, // Print DeclContext and their Decls.
Chris Lattner4b009652007-07-25 00:24:17 +0000199 ParsePrintCallbacks, // Parse and print each callback.
200 ParseSyntaxOnly, // Parse and perform semantic analysis.
201 ParseNoop, // Parse with noop callbacks.
202 RunPreprocessorOnly, // Just lex, no output.
203 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000204 DumpTokens, // Dump out preprocessed tokens.
205 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000206 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000207 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000208 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000209 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000210};
211
212static llvm::cl::opt<ProgActions>
213ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
214 llvm::cl::init(ParseSyntaxOnly),
215 llvm::cl::values(
216 clEnumValN(RunPreprocessorOnly, "Eonly",
217 "Just run preprocessor, no output (for timings)"),
218 clEnumValN(PrintPreprocessedInput, "E",
219 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000220 clEnumValN(DumpRawTokens, "dump-raw-tokens",
221 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000222 clEnumValN(RunAnalysis, "analyze",
223 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000224 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000225 "Run preprocessor, dump internal rep of tokens"),
226 clEnumValN(ParseNoop, "parse-noop",
227 "Run parser with noop callbacks (for timings)"),
228 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
229 "Run parser and perform semantic analysis"),
230 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
231 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000232 clEnumValN(EmitHTML, "emit-html",
233 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000234 clEnumValN(ASTPrint, "ast-print",
235 "Build ASTs and then pretty-print them"),
236 clEnumValN(ASTDump, "ast-dump",
237 "Build ASTs and then debug dump them"),
Douglas Gregord7915fd2009-04-26 02:02:08 +0000238 clEnumValN(ASTDumpFull, "ast-dump-full",
239 "Build ASTs and then debug dump them, including PCH"),
Chris Lattner664dd082007-10-11 00:37:43 +0000240 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000241 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000242 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000243 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000244 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000245 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000246 clEnumValN(GeneratePCH, "emit-pch",
247 "Generate pre-compiled header file"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000248 clEnumValN(EmitAssembly, "S",
249 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000250 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000251 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000252 clEnumValN(EmitBC, "emit-llvm-bc",
253 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000254 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
255 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000256 clEnumValN(RewriteTest, "rewrite-test",
257 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000258 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000259 "Rewrite ObjC into C (code rewriter example)"),
260 clEnumValN(RewriteMacros, "rewrite-macros",
261 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000262 clEnumValN(RewriteBlocks, "rewrite-blocks",
263 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000264 clEnumValN(FixIt, "fixit",
265 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000266 clEnumValEnd));
267
Ted Kremenekd01eae62007-12-19 19:47:59 +0000268
269static llvm::cl::opt<std::string>
270OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000271 llvm::cl::value_desc("path"),
Douglas Gregor608ff622009-04-22 21:45:53 +0000272 llvm::cl::desc("Specify output file"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000273
Ted Kremenek57f25b22008-12-02 19:57:31 +0000274
275//===----------------------------------------------------------------------===//
276// PTH.
277//===----------------------------------------------------------------------===//
278
279static llvm::cl::opt<std::string>
280TokenCache("token-cache", llvm::cl::value_desc("path"),
281 llvm::cl::desc("Use specified token cache file"));
282
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000283//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000284// Diagnostic Options
285//===----------------------------------------------------------------------===//
286
Ted Kremenek10389cf2007-09-26 19:42:19 +0000287static llvm::cl::opt<bool>
288VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000289 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000290
Ted Kremenekfd75e312008-03-27 06:17:42 +0000291static llvm::cl::opt<std::string>
292HTMLDiag("html-diags",
293 llvm::cl::desc("Generate HTML to report diagnostics"),
294 llvm::cl::value_desc("HTML directory"));
295
Nico Weber0e13eaa2008-08-05 23:33:20 +0000296static llvm::cl::opt<bool>
297NoShowColumn("fno-show-column",
298 llvm::cl::desc("Do not include column number on diagnostics"));
299
300static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000301NoShowLocation("fno-show-source-location",
302 llvm::cl::desc("Do not include source location information with"
303 " diagnostics"));
304
305static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000306NoCaretDiagnostics("fno-caret-diagnostics",
307 llvm::cl::desc("Do not include source line and caret with"
308 " diagnostics"));
309
Chris Lattner695a4f52009-03-13 01:08:23 +0000310static llvm::cl::opt<bool>
Chris Lattner041bd732009-04-19 07:44:08 +0000311NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
312 llvm::cl::desc("Do not include fixit information in"
313 " diagnostics"));
314
315static llvm::cl::opt<bool>
Chris Lattner13bac9e2009-04-21 05:34:31 +0000316PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
317 llvm::cl::desc("Print source range spans in numeric form"));
318
319static llvm::cl::alias
320PrintSourceRangeInfo2("fprint-source-range-info",
321 llvm::cl::desc("Print source range spans in numeric form [deprecated]"),
322 llvm::cl::aliasopt(PrintSourceRangeInfo));
Chris Lattner695a4f52009-03-13 01:08:23 +0000323
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000324static llvm::cl::opt<bool>
325PrintDiagnosticOption("fdiagnostics-show-option",
326 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weber0e13eaa2008-08-05 23:33:20 +0000327
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000328static llvm::cl::opt<unsigned>
329MessageLength("fmessage-length",
330 llvm::cl::desc("Format message diagnostics so that they fit "
331 "within N columns or fewer, when possible."),
332 llvm::cl::value_desc("N"));
333
Chris Lattner4b009652007-07-25 00:24:17 +0000334//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000335// C++ Visualization.
336//===----------------------------------------------------------------------===//
337
338static llvm::cl::opt<std::string>
339InheritanceViewCls("cxx-inheritance-view",
340 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000341 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000342
343//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000344// Builtin Options
345//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000346
347static llvm::cl::opt<bool>
348TimeReport("ftime-report",
349 llvm::cl::desc("Print the amount of time each "
350 "phase of compilation takes"));
351
Douglas Gregor23d23262009-02-14 20:49:29 +0000352static llvm::cl::opt<bool>
353Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000354 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000355 "freestanding environment"));
356
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000357static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000358AllowBuiltins("fbuiltin", llvm::cl::init(true),
359 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000360
361
362static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000363MathErrno("fmath-errno", llvm::cl::init(true),
364 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000365
Douglas Gregor23d23262009-02-14 20:49:29 +0000366//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000367// Language Options
368//===----------------------------------------------------------------------===//
369
370enum LangKind {
371 langkind_unspecified,
372 langkind_c,
373 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000374 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000375 langkind_cxx,
376 langkind_cxx_cpp,
377 langkind_objc,
378 langkind_objc_cpp,
379 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000380 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000381};
382
Chris Lattner4b009652007-07-25 00:24:17 +0000383static llvm::cl::opt<LangKind>
384BaseLang("x", llvm::cl::desc("Base language to compile"),
385 llvm::cl::init(langkind_unspecified),
386 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
387 clEnumValN(langkind_cxx, "c++", "C++"),
388 clEnumValN(langkind_objc, "objective-c", "Objective C"),
389 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000390 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000391 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000392 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
393 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000394 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000395 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000396 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
397 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000398 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000399 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000400 clEnumValN(langkind_c, "c-header",
401 "C header"),
402 clEnumValN(langkind_objc, "objective-c-header",
403 "Objective-C header"),
404 clEnumValN(langkind_cxx, "c++-header",
405 "C++ header"),
406 clEnumValN(langkind_objcxx, "objective-c++-header",
407 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000408 clEnumValEnd));
409
410static llvm::cl::opt<bool>
411LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
412 llvm::cl::Hidden);
413static llvm::cl::opt<bool>
414LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
415 llvm::cl::Hidden);
416
Chris Lattnere1be6022009-04-14 23:22:57 +0000417static llvm::cl::opt<bool>
418ObjCExclusiveGC("fobjc-gc-only",
419 llvm::cl::desc("Use GC exclusively for Objective-C related "
420 "memory management"));
421
422static llvm::cl::opt<bool>
423ObjCEnableGC("fobjc-gc",
424 llvm::cl::desc("Enable Objective-C garbage collection"));
425
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000426static llvm::cl::opt<bool>
427ObjCEnableGCBitmapPrint("print-ivar-layout",
428 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
429
Chris Lattnere1be6022009-04-14 23:22:57 +0000430static llvm::cl::opt<LangOptions::VisibilityMode>
431SymbolVisibility("fvisibility",
432 llvm::cl::desc("Set the default symbol visibility:"),
433 llvm::cl::init(LangOptions::Default),
434 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
435 "Use default symbol visibility"),
436 clEnumValN(LangOptions::Hidden, "hidden",
437 "Use hidden symbol visibility"),
438 clEnumValN(LangOptions::Protected,"protected",
439 "Use protected symbol visibility"),
440 clEnumValEnd));
441
442static llvm::cl::opt<bool>
443OverflowChecking("ftrapv",
444 llvm::cl::desc("Trap on integer overflow"),
445 llvm::cl::init(false));
446
447
Ted Kremenek11ad8952007-12-05 23:49:08 +0000448/// InitializeBaseLanguage - Handle the -x foo options.
449static void InitializeBaseLanguage() {
450 if (LangObjC)
451 BaseLang = langkind_objc;
452 else if (LangObjCXX)
453 BaseLang = langkind_objcxx;
454}
455
456static LangKind GetLanguage(const std::string &Filename) {
457 if (BaseLang != langkind_unspecified)
458 return BaseLang;
459
460 std::string::size_type DotPos = Filename.rfind('.');
461
462 if (DotPos == std::string::npos) {
463 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000464 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000465 }
466
Ted Kremenek11ad8952007-12-05 23:49:08 +0000467 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
468 // C header: .h
469 // C++ header: .hh or .H;
470 // assembler no preprocessing: .s
471 // assembler: .S
472 if (Ext == "c")
473 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000474 else if (Ext == "S" ||
475 // If the compiler is run on a .s file, preprocess it as .S
476 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000477 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000478 else if (Ext == "i")
479 return langkind_c_cpp;
480 else if (Ext == "ii")
481 return langkind_cxx_cpp;
482 else if (Ext == "m")
483 return langkind_objc;
484 else if (Ext == "mi")
485 return langkind_objc_cpp;
486 else if (Ext == "mm" || Ext == "M")
487 return langkind_objcxx;
488 else if (Ext == "mii")
489 return langkind_objcxx_cpp;
490 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
491 Ext == "c++" || Ext == "cp" || Ext == "cxx")
492 return langkind_cxx;
493 else
494 return langkind_c;
495}
496
497
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000498static void InitializeCOptions(LangOptions &Options) {
499 // Do nothing.
500}
501
502static void InitializeObjCOptions(LangOptions &Options) {
503 Options.ObjC1 = Options.ObjC2 = 1;
504}
505
506
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000507static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000508 // FIXME: implement -fpreprocessed mode.
509 bool NoPreprocess = false;
510
Ted Kremenek11ad8952007-12-05 23:49:08 +0000511 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000512 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000513 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000514 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000515 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000516 case langkind_c_cpp:
517 NoPreprocess = true;
518 // FALLTHROUGH
519 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000520 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000521 break;
522 case langkind_cxx_cpp:
523 NoPreprocess = true;
524 // FALLTHROUGH
525 case langkind_cxx:
526 Options.CPlusPlus = 1;
527 break;
528 case langkind_objc_cpp:
529 NoPreprocess = true;
530 // FALLTHROUGH
531 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000532 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000533 break;
534 case langkind_objcxx_cpp:
535 NoPreprocess = true;
536 // FALLTHROUGH
537 case langkind_objcxx:
538 Options.ObjC1 = Options.ObjC2 = 1;
539 Options.CPlusPlus = 1;
540 break;
541 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000542
543 if (ObjCExclusiveGC)
544 Options.setGCMode(LangOptions::GCOnly);
545 else if (ObjCEnableGC)
546 Options.setGCMode(LangOptions::HybridGC);
547
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000548 if (ObjCEnableGCBitmapPrint)
549 Options.ObjCGCBitmapPrint = 1;
550
Chris Lattnere1be6022009-04-14 23:22:57 +0000551 Options.setVisibilityMode(SymbolVisibility);
552 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000553}
554
555/// LangStds - Language standards we support.
556enum LangStds {
557 lang_unspecified,
558 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000559 lang_gnu_START,
560 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000561 lang_cxx98, lang_gnucxx98,
562 lang_cxx0x, lang_gnucxx0x
563};
564
565static llvm::cl::opt<LangStds>
566LangStd("std", llvm::cl::desc("Language standard to compile for"),
567 llvm::cl::init(lang_unspecified),
568 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
569 clEnumValN(lang_c89, "c90", "ISO C 1990"),
570 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
571 clEnumValN(lang_c94, "iso9899:199409",
572 "ISO C 1990 with amendment 1"),
573 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000574 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000575 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000576 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000577 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000578 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000579 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000580 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000581 clEnumValN(lang_gnu99, "gnu9x",
582 "ISO C 1999 with GNU extensions"),
583 clEnumValN(lang_cxx98, "c++98",
584 "ISO C++ 1998 with amendments"),
585 clEnumValN(lang_gnucxx98, "gnu++98",
586 "ISO C++ 1998 with amendments and GNU "
587 "extensions (default for C++)"),
588 clEnumValN(lang_cxx0x, "c++0x",
589 "Upcoming ISO C++ 200x with amendments"),
590 clEnumValN(lang_gnucxx0x, "gnu++0x",
591 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000592 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000593 clEnumValEnd));
594
595static llvm::cl::opt<bool>
596NoOperatorNames("fno-operator-names",
597 llvm::cl::desc("Do not treat C++ operator name keywords as "
598 "synonyms for operators"));
599
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000600static llvm::cl::opt<bool>
601PascalStrings("fpascal-strings",
602 llvm::cl::desc("Recognize and construct Pascal-style "
603 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000604
605static llvm::cl::opt<bool>
606MSExtensions("fms-extensions",
607 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000608 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000609
610static llvm::cl::opt<bool>
611WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000612 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000613
614static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000615NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000616 llvm::cl::desc("Disallow implicit conversions between "
617 "vectors with a different number of "
618 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000619
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000620static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000621EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000622
623static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000624EnableHeinousExtensions("fheinous-gnu-extensions",
625 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
626 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
627
628static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000629ObjCNonFragileABI("fobjc-nonfragile-abi",
630 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000631
Daniel Dunbar5523e862009-05-04 05:16:21 +0000632
633static llvm::cl::opt<bool>
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000634EmitAllDecls("femit-all-decls",
635 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000636
Daniel Dunbar91692d92008-08-11 17:36:14 +0000637static llvm::cl::opt<bool>
638Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000639 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000640
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000641static llvm::cl::opt<bool>
642GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000643 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000644 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000645
646static llvm::cl::opt<bool>
647NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000648 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000649 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000650
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000651
652
653static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000654Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000655
Douglas Gregor375733c2009-03-10 00:06:19 +0000656static llvm::cl::opt<unsigned>
657TemplateDepth("ftemplate-depth", llvm::cl::init(99),
658 llvm::cl::desc("Maximum depth of recursive template "
659 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000660static llvm::cl::opt<bool>
661DollarsInIdents("fdollars-in-identifiers",
662 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000663
Anders Carlssondfd77642009-04-06 17:37:10 +0000664
665static llvm::cl::opt<bool>
666OptSize("Os", llvm::cl::desc("Optimize for size"));
667
668static llvm::cl::opt<bool>
669NoCommon("fno-common",
670 llvm::cl::desc("Compile common globals like normal definitions"),
671 llvm::cl::ValueDisallowed);
672
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000673static llvm::cl::opt<std::string>
674MainFileName("main-file-name",
675 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000676
677// It might be nice to add bounds to the CommandLine library directly.
678struct OptLevelParser : public llvm::cl::parser<unsigned> {
679 bool parse(llvm::cl::Option &O, const char *ArgName,
680 const std::string &Arg, unsigned &Val) {
681 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
682 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000683 if (Val > 3)
684 return O.error(": '" + Arg + "' invalid optimization level!");
685 return false;
686 }
687};
688static llvm::cl::opt<unsigned, false, OptLevelParser>
689OptLevel("O", llvm::cl::Prefix,
690 llvm::cl::desc("Optimization level"),
691 llvm::cl::init(0));
692
Daniel Dunbare079c712009-04-08 03:03:23 +0000693static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000694PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
695
696static llvm::cl::opt<bool>
697StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000698
Daniel Dunbar34542952008-08-23 08:43:39 +0000699static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar07181d72009-05-06 03:16:41 +0000700 TargetInfo *Target,
701 const llvm::StringMap<bool> &Features) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000702 // Allow the target to set the default the langauge options as it sees fit.
703 Target->getDefaultLangOptions(Options);
Daniel Dunbar07181d72009-05-06 03:16:41 +0000704
705 // Pass the map of target features to the target for validation and
706 // processing.
707 Target->HandleTargetFeatures(Features);
Chris Lattner738d3f62009-03-02 22:11:07 +0000708
Chris Lattner4b009652007-07-25 00:24:17 +0000709 if (LangStd == lang_unspecified) {
710 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000711 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000712 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000713 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000714 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000715 case langkind_c_cpp:
716 case langkind_objc:
717 case langkind_objc_cpp:
718 LangStd = lang_gnu99;
719 break;
720 case langkind_cxx:
721 case langkind_cxx_cpp:
722 case langkind_objcxx:
723 case langkind_objcxx_cpp:
724 LangStd = lang_gnucxx98;
725 break;
726 }
727 }
728
729 switch (LangStd) {
730 default: assert(0 && "Unknown language standard!");
731
732 // Fall through from newer standards to older ones. This isn't really right.
733 // FIXME: Enable specifically the right features based on the language stds.
734 case lang_gnucxx0x:
735 case lang_cxx0x:
736 Options.CPlusPlus0x = 1;
737 // FALL THROUGH
738 case lang_gnucxx98:
739 case lang_cxx98:
740 Options.CPlusPlus = 1;
741 Options.CXXOperatorNames = !NoOperatorNames;
742 // FALL THROUGH.
743 case lang_gnu99:
744 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000745 Options.C99 = 1;
746 Options.HexFloats = 1;
747 // FALL THROUGH.
748 case lang_gnu89:
749 Options.BCPLComment = 1; // Only for C99/C++.
750 // FALL THROUGH.
751 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000752 Options.Digraphs = 1; // C94, C99, C++.
753 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000754 case lang_c89:
755 break;
756 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000757
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000758 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
759 Options.GNUMode = LangStd >= lang_gnu_START;
760
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000761 if (Options.CPlusPlus) {
762 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000763 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000764 }
Chris Lattner4b009652007-07-25 00:24:17 +0000765
Chris Lattner6ab935b2008-04-05 06:32:51 +0000766 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
767 Options.ImplicitInt = 1;
768 else
769 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000770
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000771 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
772 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000773 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000774 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000775 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000776
Chris Lattner58d5ba52008-12-05 00:10:44 +0000777 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
778 // even if they are normally on for the target. In GNU modes (e.g.
779 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000780 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000781 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000782 Options.Blocks = 0;
783
Chris Lattner284784c2009-04-19 07:06:52 +0000784 // Default to not accepting '$' in identifiers when preprocessing assembler,
785 // but do accept when preprocessing C. FIXME: these defaults are right for
786 // darwin, are they right everywhere?
787 Options.DollarIdents = LK != langkind_asm_cpp;
788 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner77c04832009-04-19 07:00:02 +0000789 Options.DollarIdents = DollarsInIdents;
790
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000791 if (PascalStrings.getPosition())
792 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000793 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000794 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000795 if (NoLaxVectorConversions.getPosition())
796 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000797 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000798 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000799 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000800
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000801 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000802 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000803 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000804 Options.Freestanding = Options.NoBuiltin = 1;
805
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000806 if (EnableHeinousExtensions)
807 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000808
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000809 Options.MathErrno = MathErrno;
810
Douglas Gregor375733c2009-03-10 00:06:19 +0000811 Options.InstantiationDepth = TemplateDepth;
812
Chris Lattnerddae7102008-12-04 22:54:33 +0000813 // Override the default runtime if the user requested it.
814 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000815 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000816 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000817 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000818
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000819 if (ObjCNonFragileABI)
820 Options.ObjCNonFragileABI = 1;
Daniel Dunbar5523e862009-05-04 05:16:21 +0000821
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000822 if (EmitAllDecls)
823 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000824
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000825 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
826 // support.
827 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000828
829 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000830 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000831 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000832
833 assert(PICLevel <= 2 && "Invalid value for -pic-level");
834 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000835
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000836 Options.GNUInline = !Options.C99;
Chris Lattnerd7f00522009-05-06 04:38:30 +0000837 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000838 Options.NoInline = !OptSize && !OptLevel;
839
840 Options.Static = StaticDefine;
841
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000842 if (MainFileName.getPosition())
843 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000844}
845
846//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000847// Target Triple Processing.
848//===----------------------------------------------------------------------===//
849
850static llvm::cl::opt<std::string>
851TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000852 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000853
Chris Lattnerfc457002008-03-05 01:18:20 +0000854static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000855Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000856
Chris Lattner2b168e02008-09-30 01:13:12 +0000857static llvm::cl::opt<std::string>
858MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000859 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000860
Chris Lattner01de9c82008-09-30 20:16:56 +0000861// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
862// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000863
864// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000865static void HandleMacOSVersionMin(std::string &Triple) {
866 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
867 if (DarwinDashIdx == std::string::npos) {
868 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000869 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000870 exit(1);
871 }
872 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
873
Chris Lattner01de9c82008-09-30 20:16:56 +0000874 // Remove the number.
875 Triple.resize(DarwinNumIdx);
876
877 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
878 bool MacOSVersionMinIsInvalid = false;
879 int VersionNum = 0;
880 if (MacOSVersionMin.size() < 4 ||
881 MacOSVersionMin.substr(0, 3) != "10." ||
882 !isdigit(MacOSVersionMin[3])) {
883 MacOSVersionMinIsInvalid = true;
884 } else {
885 const char *Start = MacOSVersionMin.c_str()+3;
886 char *End = 0;
887 VersionNum = (int)strtol(Start, &End, 10);
888
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000889 // The version number must be in the range 0-9.
890 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
891
Chris Lattner01de9c82008-09-30 20:16:56 +0000892 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
893 Triple += llvm::itostr(VersionNum+4);
894
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000895 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
896 // Add the period piece (.7) to the end of the triple. This gives us
897 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000898 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000899 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
900 MacOSVersionMinIsInvalid = true;
901 }
902 }
903
904 if (MacOSVersionMinIsInvalid) {
905 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000906 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000907 MacOSVersionMin.c_str());
908 exit(1);
909 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000910 else if (VersionNum <= 4 &&
911 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
912 fprintf(stderr,
913 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
914 MacOSVersionMin.c_str());
915 exit(1);
916 }
917
Chris Lattner01de9c82008-09-30 20:16:56 +0000918}
919
Daniel Dunbar93f64532009-04-10 19:52:24 +0000920static llvm::cl::opt<std::string>
921IPhoneOSVersionMin("miphoneos-version-min",
922 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
923
924// If -miphoneos-version-min=2.2 is specified, change the triple from being
925// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
926// 9 as the default major Darwin number, and encode the iPhone OS version
927// number in the minor version and revision.
928
929// FIXME: We should have the driver do this instead.
930static void HandleIPhoneOSVersionMin(std::string &Triple) {
931 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
932 if (DarwinDashIdx == std::string::npos) {
933 fprintf(stderr,
934 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
935 exit(1);
936 }
937 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
938
939 // Remove the number.
940 Triple.resize(DarwinNumIdx);
941
942 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
943 bool IPhoneOSVersionMinIsInvalid = false;
944 int VersionNum = 0;
945 if (IPhoneOSVersionMin.size() < 3 ||
946 !isdigit(IPhoneOSVersionMin[0])) {
947 IPhoneOSVersionMinIsInvalid = true;
948 } else {
949 const char *Start = IPhoneOSVersionMin.c_str();
950 char *End = 0;
951 VersionNum = (int)strtol(Start, &End, 10);
952
953 // The version number must be in the range 0-9.
954 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
955
956 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
957 Triple += "9." + llvm::itostr(VersionNum);
958
959 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
960 // Add the period piece (.2) to the end of the triple. This gives us
961 // something like ...-darwin9.2.2
962 Triple += End;
963 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
964 IPhoneOSVersionMinIsInvalid = true;
965 }
966 }
967
968 if (IPhoneOSVersionMinIsInvalid) {
969 fprintf(stderr,
970 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
971 IPhoneOSVersionMin.c_str());
972 exit(1);
973 }
974}
975
Chris Lattner01de9c82008-09-30 20:16:56 +0000976/// CreateTargetTriple - Process the various options that affect the target
977/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000978static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000979 // Initialize base triple. If a -triple option has been specified, use
980 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000981 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000982 if (Triple.empty())
983 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000984
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000985 // If -arch foo was specified, remove the architecture from the triple we have
986 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000987
988 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +0000989 if (!Arch.empty()) {
990 // Decompose the base triple into "arch" and suffix.
991 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000992
Chris Lattner2b168e02008-09-30 01:13:12 +0000993 if (FirstDashIdx == std::string::npos) {
994 fprintf(stderr,
995 "Malformed target triple: \"%s\" ('-' could not be found).\n",
996 Triple.c_str());
997 exit(1);
998 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +0000999
1000 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1001 if (Arch == "ppc")
1002 Arch = "powerpc";
1003 else if (Arch == "ppc64")
1004 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +00001005
Chris Lattner2b168e02008-09-30 01:13:12 +00001006 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1007 }
1008
1009 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1010 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +00001011 if (!MacOSVersionMin.empty())
1012 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +00001013 else if (!IPhoneOSVersionMin.empty())
1014 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +00001015
Chris Lattner2b168e02008-09-30 01:13:12 +00001016 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001017}
1018
1019//===----------------------------------------------------------------------===//
Chris Lattner94269d72009-04-21 05:40:52 +00001020// SourceManager initialization.
Chris Lattner4b009652007-07-25 00:24:17 +00001021//===----------------------------------------------------------------------===//
1022
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001023static bool InitializeSourceManager(Preprocessor &PP,
1024 const std::string &InFile) {
1025 // Figure out where to get and map in the main file.
1026 SourceManager &SourceMgr = PP.getSourceManager();
1027 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbarbb56def2009-04-27 21:19:07 +00001028
1029 if (EmptyInputOnly) {
1030 const char *EmptyStr = "";
1031 llvm::MemoryBuffer *SB =
1032 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1033 SourceMgr.createMainFileIDForMemBuffer(SB);
1034 } else if (InFile != "-") {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001035 const FileEntry *File = FileMgr.getFile(InFile);
1036 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1037 if (SourceMgr.getMainFileID().isInvalid()) {
1038 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1039 << InFile.c_str();
1040 return true;
1041 }
1042 } else {
1043 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1044
1045 // If stdin was empty, SB is null. Cons up an empty memory
1046 // buffer now.
1047 if (!SB) {
1048 const char *EmptyStr = "";
1049 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1050 }
1051
1052 SourceMgr.createMainFileIDForMemBuffer(SB);
1053 if (SourceMgr.getMainFileID().isInvalid()) {
1054 PP.getDiagnostics().Report(FullSourceLoc(),
1055 diag::err_fe_error_reading_stdin);
1056 return true;
1057 }
1058 }
1059
1060 return false;
1061}
1062
Chris Lattner47b6a162008-04-19 23:09:31 +00001063
Chris Lattner94269d72009-04-21 05:40:52 +00001064//===----------------------------------------------------------------------===//
1065// Preprocessor Initialization
1066//===----------------------------------------------------------------------===//
Sam Bishop61a20782008-04-14 14:41:57 +00001067
Chris Lattner94269d72009-04-21 05:40:52 +00001068// FIXME: Preprocessor builtins to support.
1069// -A... - Play with #assertions
1070// -undef - Undefine all predefined macros
Chris Lattnerb62396d2009-04-08 20:15:42 +00001071
Chris Lattner94269d72009-04-21 05:40:52 +00001072static llvm::cl::list<std::string>
1073D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1074 llvm::cl::desc("Predefine the specified macro"));
1075static llvm::cl::list<std::string>
1076U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1077 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001078
Chris Lattner94269d72009-04-21 05:40:52 +00001079static llvm::cl::list<std::string>
1080ImplicitIncludes("include", llvm::cl::value_desc("file"),
1081 llvm::cl::desc("Include file before parsing"));
1082static llvm::cl::list<std::string>
1083ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1084 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001085
Chris Lattner94269d72009-04-21 05:40:52 +00001086static llvm::cl::opt<std::string>
1087ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1088 llvm::cl::desc("Include precompiled header file"));
1089
1090static llvm::cl::opt<std::string>
1091ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1092 llvm::cl::desc("Include file before parsing"));
1093
Chris Lattner4b009652007-07-25 00:24:17 +00001094
1095//===----------------------------------------------------------------------===//
1096// Preprocessor include path information.
1097//===----------------------------------------------------------------------===//
1098
1099// This tool exports a large number of command line options to control how the
1100// preprocessor searches for header files. At root, however, the Preprocessor
1101// object takes a very simple interface: a list of directories to search for
1102//
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001103// FIXME: -nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001104// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001105//
Chris Lattner4b009652007-07-25 00:24:17 +00001106
1107static llvm::cl::opt<bool>
1108nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1109
1110// Various command line options. These four add directories to each chain.
1111static llvm::cl::list<std::string>
1112F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1113 llvm::cl::desc("Add directory to framework include search path"));
1114static llvm::cl::list<std::string>
1115I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1116 llvm::cl::desc("Add directory to include search path"));
1117static llvm::cl::list<std::string>
1118idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1119 llvm::cl::desc("Add directory to AFTER include search path"));
1120static llvm::cl::list<std::string>
1121iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1122 llvm::cl::desc("Add directory to QUOTE include search path"));
1123static llvm::cl::list<std::string>
1124isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1125 llvm::cl::desc("Add directory to SYSTEM include search path"));
1126
1127// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1128static llvm::cl::list<std::string>
1129iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1130 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1131static llvm::cl::list<std::string>
1132iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1133 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1134static llvm::cl::list<std::string>
1135iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1136 llvm::cl::Prefix,
1137 llvm::cl::desc("Set directory to include search path with prefix"));
1138
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001139static llvm::cl::opt<std::string>
1140isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1141 llvm::cl::desc("Set the system root directory (usually /)"));
1142
Chris Lattner4b009652007-07-25 00:24:17 +00001143// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001144
Chris Lattner4b009652007-07-25 00:24:17 +00001145/// InitializeIncludePaths - Process the -I options and set them in the
1146/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001147void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1148 FileManager &FM, const LangOptions &Lang) {
1149 InitHeaderSearch Init(Headers, Verbose, isysroot);
1150
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001151 // Handle -I... and -F... options, walking the lists in parallel.
1152 unsigned Iidx = 0, Fidx = 0;
1153 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1154 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001155 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001156 ++Iidx;
1157 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001158 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001159 ++Fidx;
1160 }
1161 }
Chris Lattner4b009652007-07-25 00:24:17 +00001162
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001163 // Consume what's left from whatever list was longer.
1164 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001165 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001166 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001167 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001168
1169 // Handle -idirafter... options.
1170 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001171 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1172 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001173
1174 // Handle -iquote... options.
1175 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001176 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001177
1178 // Handle -isystem... options.
1179 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001180 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001181
1182 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1183 // parallel, processing the values in order of occurance to get the right
1184 // prefixes.
1185 {
1186 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1187 unsigned iprefix_idx = 0;
1188 unsigned iwithprefix_idx = 0;
1189 unsigned iwithprefixbefore_idx = 0;
1190 bool iprefix_done = iprefix_vals.empty();
1191 bool iwithprefix_done = iwithprefix_vals.empty();
1192 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1193 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1194 if (!iprefix_done &&
1195 (iwithprefix_done ||
1196 iprefix_vals.getPosition(iprefix_idx) <
1197 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1198 (iwithprefixbefore_done ||
1199 iprefix_vals.getPosition(iprefix_idx) <
1200 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1201 Prefix = iprefix_vals[iprefix_idx];
1202 ++iprefix_idx;
1203 iprefix_done = iprefix_idx == iprefix_vals.size();
1204 } else if (!iwithprefix_done &&
1205 (iwithprefixbefore_done ||
1206 iwithprefix_vals.getPosition(iwithprefix_idx) <
1207 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001208 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1209 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001210 ++iwithprefix_idx;
1211 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1212 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001213 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1214 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001215 ++iwithprefixbefore_idx;
1216 iwithprefixbefore_done =
1217 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1218 }
1219 }
1220 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001221
Nico Weber770e3882008-08-22 09:25:22 +00001222 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001223
Daniel Dunbar4e604292009-02-21 20:52:41 +00001224 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001225 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001226 llvm::sys::Path::GetMainExecutable(Argv0,
1227 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001228 if (!MainExecutablePath.isEmpty()) {
1229 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1230 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001231
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001232 // Get foo/lib/clang/<version>/include
Daniel Dunbar4e604292009-02-21 20:52:41 +00001233 MainExecutablePath.appendComponent("lib");
1234 MainExecutablePath.appendComponent("clang");
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001235 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbar4e604292009-02-21 20:52:41 +00001236 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001237
1238 // We pass true to ignore sysroot so that we *always* look for clang headers
1239 // relative to our executable, never relative to -isysroot.
1240 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1241 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001242 }
1243
Nico Weber770e3882008-08-22 09:25:22 +00001244 if (!nostdinc)
1245 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001246
1247 // Now that we have collected all of the include paths, merge them all
1248 // together and tell the preprocessor about them.
1249
Nico Weber770e3882008-08-22 09:25:22 +00001250 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001251}
1252
Chris Lattner94269d72009-04-21 05:40:52 +00001253void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1254{
1255 // Add macros from the command line.
1256 unsigned d = 0, D = D_macros.size();
1257 unsigned u = 0, U = U_macros.size();
1258 while (d < D || u < U) {
1259 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1260 InitOpts.addMacroDef(D_macros[d++]);
1261 else
1262 InitOpts.addMacroUndef(U_macros[u++]);
1263 }
1264
1265 // If -imacros are specified, include them now. These are processed before
1266 // any -include directives.
1267 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1268 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1269
1270 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) {
1271 // We want to add these paths to the predefines buffer in order, make a
1272 // temporary vector to sort by their occurrence.
1273 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1274
1275 if (!ImplicitIncludePTH.empty())
1276 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1277 &ImplicitIncludePTH));
1278 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1279 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1280 &ImplicitIncludes[i]));
1281 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1282
1283
1284 // Now that they are ordered by position, add to the predefines buffer.
1285 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1286 std::string *Ptr = OrderedPaths[i].second;
1287 if (!ImplicitIncludes.empty() &&
1288 Ptr >= &ImplicitIncludes[0] &&
1289 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1290 InitOpts.addInclude(*Ptr, false);
1291 } else {
1292 assert(Ptr == &ImplicitIncludePTH);
1293 InitOpts.addInclude(*Ptr, true);
1294 }
1295 }
1296 }
1297}
1298
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001299//===----------------------------------------------------------------------===//
1300// Driver PreprocessorFactory - For lazily generating preprocessors ...
1301//===----------------------------------------------------------------------===//
1302
1303namespace {
1304class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001305 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001306 Diagnostic &Diags;
1307 const LangOptions &LangInfo;
1308 TargetInfo &Target;
1309 SourceManager &SourceMgr;
1310 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001311
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001312public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001313 DriverPreprocessorFactory(const std::string &infile,
1314 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001315 TargetInfo &target, SourceManager &SM,
1316 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001317 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001318 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001319
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001320
1321 virtual ~DriverPreprocessorFactory() {}
1322
1323 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001324 llvm::OwningPtr<PTHManager> PTHMgr;
1325
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001326 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1327 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1328 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001329 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001330 }
1331
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001332 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001333 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1334 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001335 PTHMgr.reset(PTHManager::Create(x, &Diags,
1336 TokenCache.empty() ? Diagnostic::Error
1337 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001338 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001339
Ted Kremenek6348cc62009-03-22 06:42:39 +00001340 if (Diags.hasErrorOccurred())
1341 exit(1);
1342
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001343 // Create the Preprocessor.
1344 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1345 SourceMgr, HeaderInfo,
1346 PTHMgr.get()));
1347
1348 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1349 // That argument is used as the IdentifierInfoLookup argument to
1350 // IdentifierTable's ctor.
1351 if (PTHMgr) {
1352 PTHMgr->setPreprocessor(PP.get());
1353 PP->setPTHManager(PTHMgr.take());
1354 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001355
Chris Lattner94269d72009-04-21 05:40:52 +00001356 PreprocessorInitOptions InitOpts;
1357 InitializePreprocessorInitOptions(InitOpts);
1358 if (InitializePreprocessor(*PP, InFile, InitOpts))
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001359 return 0;
Chris Lattner94269d72009-04-21 05:40:52 +00001360
Daniel Dunbarebfb1bc2009-05-03 09:35:25 +00001361 std::string ErrStr;
1362 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1363 if (!DFG && !ErrStr.empty()) {
1364 fprintf(stderr, "%s", ErrStr.c_str());
1365 return 0;
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001366 }
1367
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001368 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001369 }
1370};
1371}
Chris Lattner4b009652007-07-25 00:24:17 +00001372
Chris Lattner4b009652007-07-25 00:24:17 +00001373//===----------------------------------------------------------------------===//
1374// Basic Parser driver
1375//===----------------------------------------------------------------------===//
1376
Chris Lattner9d818a22008-04-19 23:25:44 +00001377static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001378 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001379 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001380
1381 // Parsing the specified input file.
1382 P.ParseTranslationUnit();
1383 delete PA;
1384}
1385
1386//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001387// Code generation options
1388//===----------------------------------------------------------------------===//
1389
1390static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001391GenerateDebugInfo("g",
1392 llvm::cl::desc("Generate source level debug information"));
1393
Daniel Dunbar9101a632009-02-17 19:47:34 +00001394static llvm::cl::opt<std::string>
1395TargetCPU("mcpu",
1396 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1397
Daniel Dunbar07181d72009-05-06 03:16:41 +00001398static llvm::cl::list<std::string>
1399TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1400
1401/// ComputeTargetFeatures - Recompute the target feature list to only
1402/// be the list of things that are enabled, based on the target cpu
1403/// and feature list.
1404static void ComputeFeatureMap(TargetInfo *Target,
1405 llvm::StringMap<bool> &Features) {
1406 assert(Features.empty() && "invalid map");
1407
1408 // Initialize the feature map based on the target.
1409 Target->getDefaultFeatures(TargetCPU, Features);
1410
1411 // Apply the user specified deltas.
1412 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1413 ie = TargetFeatures.end(); it != ie; ++it) {
1414 const char *Name = it->c_str();
1415
1416 // FIXME: Don't handle errors like this.
1417 if (Name[0] != '-' && Name[0] != '+') {
1418 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1419 Name);
1420 exit(1);
1421 }
Daniel Dunbar0838f962009-05-06 21:07:50 +00001422 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1423 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1424 Name + 1);
Daniel Dunbar07181d72009-05-06 03:16:41 +00001425 exit(1);
1426 }
Daniel Dunbar07181d72009-05-06 03:16:41 +00001427 }
1428}
1429
Chris Lattner8a9615c2009-03-16 18:41:18 +00001430static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001431 const LangOptions &LangOpts,
1432 const llvm::StringMap<bool> &Features) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001433 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001434 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001435 if (OptSize) {
1436 // -Os implies -O2
1437 // FIXME: Diagnose conflicting options.
1438 Opts.OptimizationLevel = 2;
1439 } else {
1440 Opts.OptimizationLevel = OptLevel;
1441 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001442
1443 // FIXME: There are llvm-gcc options to control these selectively.
1444 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1445 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001446 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001447
1448#ifdef NDEBUG
1449 Opts.VerifyModule = 0;
1450#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001451
1452 Opts.CPU = TargetCPU;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001453 Opts.Features.clear();
1454 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1455 ie = Features.end(); it != ie; ++it) {
1456 // FIXME: If we are completely confident that we have the right
1457 // set, we only need to pass the minuses.
1458 std::string Name(it->second ? "+" : "-");
1459 Name += it->first();
1460 Opts.Features.push_back(Name);
1461 }
Chris Lattnere8f70712009-02-18 01:23:44 +00001462
Chris Lattnerf04a7562009-03-26 05:00:52 +00001463 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1464
Chris Lattnere8f70712009-02-18 01:23:44 +00001465 // Handle -ftime-report.
1466 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001467}
1468
1469//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001470// Fix-It Options
1471//===----------------------------------------------------------------------===//
1472static llvm::cl::list<ParsedSourceLocation>
1473FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1474 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1475
1476//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001477// -dump-build-information Stuff
1478//===----------------------------------------------------------------------===//
1479
1480static llvm::cl::opt<std::string>
1481DumpBuildInformation("dump-build-information",
1482 llvm::cl::value_desc("filename"),
1483 llvm::cl::desc("output a dump of some build information to a file"));
1484
1485static llvm::raw_ostream *BuildLogFile = 0;
1486
1487/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1488/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1489namespace {
1490class LoggingDiagnosticClient : public DiagnosticClient {
1491 llvm::OwningPtr<DiagnosticClient> Chain1;
1492 llvm::OwningPtr<DiagnosticClient> Chain2;
1493public:
1494
1495 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1496 // Output diags both where requested...
1497 Chain1.reset(Normal);
1498 // .. and to our log file.
1499 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1500 !NoShowColumn,
1501 !NoCaretDiagnostics,
1502 !NoShowLocation,
1503 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001504 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001505 !NoDiagnosticsFixIt,
1506 MessageLength));
Chris Lattner94859302009-04-17 21:05:01 +00001507 }
1508
1509 virtual void setLangOptions(const LangOptions *LO) {
1510 Chain1->setLangOptions(LO);
1511 Chain2->setLangOptions(LO);
1512 }
1513
1514 virtual bool IncludeInDiagnosticCounts() const {
1515 return Chain1->IncludeInDiagnosticCounts();
1516 }
1517
1518 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1519 const DiagnosticInfo &Info) {
1520 Chain1->HandleDiagnostic(DiagLevel, Info);
1521 Chain2->HandleDiagnostic(DiagLevel, Info);
1522 }
1523};
1524} // end anonymous namespace.
1525
1526static void SetUpBuildDumpLog(unsigned argc, char **argv,
1527 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1528
1529 std::string ErrorInfo;
1530 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1531 ErrorInfo);
1532
1533 if (!ErrorInfo.empty()) {
1534 llvm::errs() << "error opening -dump-build-information file '"
1535 << DumpBuildInformation << "', option ignored!\n";
1536 delete BuildLogFile;
1537 BuildLogFile = 0;
1538 DumpBuildInformation = "";
1539 return;
1540 }
1541
1542 (*BuildLogFile) << "clang-cc command line arguments: ";
1543 for (unsigned i = 0; i != argc; ++i)
1544 (*BuildLogFile) << argv[i] << ' ';
1545 (*BuildLogFile) << '\n';
1546
1547 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1548 // the diagnostic producers and the normal receiver.
1549 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1550}
1551
1552
1553
1554//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001555// Main driver
1556//===----------------------------------------------------------------------===//
1557
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001558/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001559/// action. These consumers can operate on both ASTs that are freshly
1560/// parsed from source files as well as those deserialized from Bitcode.
1561/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001562static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001563 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001564 const LangOptions& LangOpts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001565 const llvm::StringMap<bool>& Features,
Chris Lattner21f72d62008-04-16 06:11:58 +00001566 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001567 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001568 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001569 default:
1570 return NULL;
1571
1572 case ASTPrint:
1573 return CreateASTPrinter();
1574
1575 case ASTDump:
Douglas Gregord7915fd2009-04-26 02:02:08 +00001576 return CreateASTDumper(false);
1577
1578 case ASTDumpFull:
1579 return CreateASTDumper(true);
Chris Lattner7f902922009-02-18 01:20:05 +00001580
1581 case ASTView:
1582 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001583
Chris Lattner7f902922009-02-18 01:20:05 +00001584 case PrintDeclContext:
1585 return CreateDeclContextPrinter();
1586
1587 case EmitHTML:
1588 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001589
Chris Lattner7f902922009-02-18 01:20:05 +00001590 case InheritanceView:
1591 return CreateInheritanceViewer(InheritanceViewCls);
1592
Chris Lattner7f902922009-02-18 01:20:05 +00001593 case EmitAssembly:
1594 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001595 case EmitBC:
1596 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001597 BackendAction Act;
1598 if (ProgAction == EmitAssembly)
1599 Act = Backend_EmitAssembly;
1600 else if (ProgAction == EmitLLVM)
1601 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001602 else if (ProgAction == EmitLLVMOnly)
1603 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001604 else
1605 Act = Backend_EmitBC;
1606
1607 CompileOptions Opts;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001608 InitializeCompileOptions(Opts, LangOpts, Features);
Chris Lattner7f902922009-02-18 01:20:05 +00001609 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001610 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001611 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001612
Douglas Gregorc34897d2009-04-09 22:27:44 +00001613 case GeneratePCH:
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001614 return CreatePCHGenerator(*PP, OutputFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001615
Chris Lattner7f902922009-02-18 01:20:05 +00001616 case RewriteObjC:
1617 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001618
Chris Lattner7f902922009-02-18 01:20:05 +00001619 case RewriteBlocks:
1620 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1621
1622 case RunAnalysis:
1623 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001624 }
1625}
1626
Chris Lattner4b009652007-07-25 00:24:17 +00001627/// ProcessInputFile - Process a single input file with the specified state.
1628///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001629static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001630 const std::string &InFile, ProgActions PA,
1631 const llvm::StringMap<bool> &Features) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001632 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001633 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001634 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00001635 bool CompleteTranslationUnit = true;
Douglas Gregor133d2552009-04-02 01:08:08 +00001636
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001637 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001638 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001639 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1640 PP.getFileManager(), PP.getLangOptions(),
Daniel Dunbar07181d72009-05-06 03:16:41 +00001641 Features, &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001642
1643 if (!Consumer) {
1644 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001645 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001646 return;
1647 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001648
Douglas Gregore0d5c562009-04-14 16:27:31 +00001649 if (ProgAction == GeneratePCH)
1650 CompleteTranslationUnit = false;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001651 break;
1652
Chris Lattneraf669fb2008-10-12 05:03:36 +00001653 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001654 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001655 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001656 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001657 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001658 RawLex.SetKeepWhitespaceMode(true);
1659
1660 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001661 RawLex.LexFromRawLexer(RawTok);
1662 while (RawTok.isNot(tok::eof)) {
1663 PP.DumpToken(RawTok, true);
1664 fprintf(stderr, "\n");
1665 RawLex.LexFromRawLexer(RawTok);
1666 }
1667 ClearSourceMgr = true;
1668 break;
1669 }
Chris Lattner4b009652007-07-25 00:24:17 +00001670 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001671 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001672 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001673 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001674 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001675 do {
1676 PP.Lex(Tok);
1677 PP.DumpToken(Tok, true);
1678 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001679 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001680 ClearSourceMgr = true;
1681 break;
1682 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001683 case RunPreprocessorOnly:
Chris Lattner4b009652007-07-25 00:24:17 +00001684 break;
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001685
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001686 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001687 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001688 CacheTokens(PP, OutputFile);
1689 ClearSourceMgr = true;
1690 break;
1691 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001692
Chris Lattner772a7c12009-04-27 22:02:30 +00001693 case PrintPreprocessedInput:
Chris Lattner4b009652007-07-25 00:24:17 +00001694 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001695
Chris Lattner270d29a2009-04-27 21:45:14 +00001696 case ParseNoop:
Chris Lattner4b009652007-07-25 00:24:17 +00001697 break;
1698
Chris Lattnerefe33382009-02-18 01:51:21 +00001699 case ParsePrintCallbacks: {
1700 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001701 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001702 ClearSourceMgr = true;
1703 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001704 }
1705
1706 case ParseSyntaxOnly: { // -fsyntax-only
1707 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001708 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001709 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001710 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001711
1712 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001713 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001714 ClearSourceMgr = true;
1715 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001716
Chris Lattnerefe33382009-02-18 01:51:21 +00001717 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001718 DoRewriteTest(PP, InFile, OutputFile);
1719 ClearSourceMgr = true;
1720 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001721 }
Douglas Gregor133d2552009-04-02 01:08:08 +00001722
1723 case FixIt:
1724 llvm::TimeRegion Timer(ClangFrontendTimer);
1725 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001726 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001727 PP.getSourceManager(),
1728 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00001729 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001730 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001731
Chris Lattner38a4f182009-04-27 21:25:27 +00001732 if (FixItAtLocations.size() > 0) {
1733 // Even without the "-fixit" flag, with may have some specific
1734 // locations where the user has requested fixes. Process those
1735 // locations now.
1736 if (!FixItRewrite)
1737 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1738 PP.getSourceManager(),
1739 PP.getLangOptions());
Chris Lattner143fd6d2009-03-28 01:37:17 +00001740
Chris Lattner38a4f182009-04-27 21:25:27 +00001741 bool AddedFixitLocation = false;
1742 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1743 Idx != Last; ++Idx) {
1744 RequestedSourceLocation Requested;
1745 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1746 Requested)) {
1747 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1748 FixItAtLocations[Idx].FileName.c_str());
1749 } else {
1750 FixItRewrite->addFixItLocation(Requested);
1751 AddedFixitLocation = true;
Douglas Gregor24b48b02009-04-02 19:05:20 +00001752 }
1753 }
1754
Chris Lattner38a4f182009-04-27 21:25:27 +00001755 if (!AddedFixitLocation) {
1756 // All of the fix-it locations were bad. Don't fix anything.
1757 delete FixItRewrite;
1758 FixItRewrite = 0;
1759 }
1760 }
1761
1762 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner270d29a2009-04-27 21:45:14 +00001763 if (Consumer)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001764 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1765 PP.getSourceManager(),
1766 PP.getTargetInfo(),
1767 PP.getIdentifierTable(),
1768 PP.getSelectorTable(),
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001769 /* FreeMemory = */ !DisableFree,
1770 /* size_reserve = */0,
1771 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattner772a7c12009-04-27 22:02:30 +00001772 llvm::OwningPtr<PCHReader> Reader;
1773 llvm::OwningPtr<ExternalASTSource> Source;
1774
Chris Lattner270d29a2009-04-27 21:45:14 +00001775 if (!ImplicitIncludePCH.empty()) {
Chris Lattner772a7c12009-04-27 22:02:30 +00001776 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1777
Chris Lattner270d29a2009-04-27 21:45:14 +00001778 // The user has asked us to include a precompiled header. Load
1779 // the precompiled header into the AST context.
Chris Lattner270d29a2009-04-27 21:45:14 +00001780 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1781 case PCHReader::Success: {
Douglas Gregor32de6312009-04-28 18:58:38 +00001782 // Set the predefines buffer as suggested by the PCH
1783 // reader. Typically, the predefines buffer will be empty.
1784 PP.setPredefines(Reader->getSuggestedPredefines());
1785
Chris Lattner270d29a2009-04-27 21:45:14 +00001786 // Attach the PCH reader to the AST context as an external AST
1787 // source, so that declarations will be deserialized from the
1788 // PCH file as needed.
Chris Lattner772a7c12009-04-27 22:02:30 +00001789 if (ContextOwner) {
1790 Source.reset(Reader.take());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001791 ContextOwner->setExternalSource(Source);
Chris Lattner772a7c12009-04-27 22:02:30 +00001792 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001793 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001794 }
1795
Chris Lattner270d29a2009-04-27 21:45:14 +00001796 case PCHReader::Failure:
1797 // Unrecoverable failure: don't even try to process the input
1798 // file.
1799 return;
1800
1801 case PCHReader::IgnorePCH:
Douglas Gregor9ea9b162009-04-28 22:01:16 +00001802 // No suitable PCH file could be found. Return an error.
1803 return;
1804
1805#if 0
1806 // FIXME: We can recover from failed attempts to load PCH
1807 // files. This code will do so, if we ever want to enable it.
1808
Chris Lattner270d29a2009-04-27 21:45:14 +00001809 // We delayed the initialization of builtins in the hope of
1810 // loading the PCH file. Since the PCH file could not be
1811 // loaded, initialize builtins now.
1812 if (ContextOwner)
1813 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor9ea9b162009-04-28 22:01:16 +00001814#endif
Chris Lattner270d29a2009-04-27 21:45:14 +00001815 }
1816
1817 // Finish preprocessor initialization. We do this now (rather
1818 // than earlier) because this initialization creates new source
1819 // location entries in the source manager, which must come after
1820 // the source location entries for the PCH file.
1821 if (InitializeSourceManager(PP, InFile))
1822 return;
Ted Kremenek88eebed2009-01-28 04:29:29 +00001823 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001824
Chris Lattner270d29a2009-04-27 21:45:14 +00001825
1826 // If we have an ASTConsumer, run the parser with it.
1827 if (Consumer)
1828 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
1829 CompleteTranslationUnit);
1830
1831 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
1832 llvm::TimeRegion Timer(ClangFrontendTimer);
1833 Token Tok;
1834 // Start parsing the specified input file.
1835 PP.EnterMainSourceFile();
1836 do {
1837 PP.Lex(Tok);
1838 } while (Tok.isNot(tok::eof));
1839 ClearSourceMgr = true;
1840 } else if (PA == ParseNoop) { // -parse-noop
1841 llvm::TimeRegion Timer(ClangFrontendTimer);
1842 ParseFile(PP, new MinimalAction(PP));
1843 ClearSourceMgr = true;
Chris Lattner772a7c12009-04-27 22:02:30 +00001844 } else if (PA == PrintPreprocessedInput){ // -E mode.
1845 llvm::TimeRegion Timer(ClangFrontendTimer);
1846 DoPrintPreprocessedInput(PP, OutputFile);
1847 ClearSourceMgr = true;
Chris Lattner270d29a2009-04-27 21:45:14 +00001848 }
1849
Chris Lattner38a4f182009-04-27 21:25:27 +00001850 if (FixItRewrite)
1851 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1852
1853 // If in -disable-free mode, don't deallocate ASTContext.
1854 if (DisableFree)
1855 ContextOwner.take();
1856 else
1857 ContextOwner.reset(); // Delete ASTContext
1858
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001859 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001860 if (CheckDiagnostics(PP))
1861 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001862
Chris Lattner4b009652007-07-25 00:24:17 +00001863 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001864 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001865 PP.PrintStats();
1866 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001867 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001868 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001869 fprintf(stderr, "\n");
1870 }
1871
1872 // For a multi-file compilation, some things are ok with nuking the source
1873 // manager tables, other require stable fileid/macroid's across multiple
1874 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001875 if (ClearSourceMgr)
1876 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001877
1878 if (DisableFree)
1879 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001880}
1881
1882static llvm::cl::list<std::string>
1883InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1884
Chris Lattner4b009652007-07-25 00:24:17 +00001885int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001886 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001887 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001888 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001889 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001890
Chris Lattnerefe33382009-02-18 01:51:21 +00001891 if (TimeReport)
1892 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1893
Chris Lattner4b009652007-07-25 00:24:17 +00001894 // If no input was specified, read from stdin.
1895 if (InputFilenames.empty())
1896 InputFilenames.push_back("-");
Douglas Gregor965a13c2009-05-02 00:03:46 +00001897
Ted Kremenekb240e822007-12-11 23:28:38 +00001898 // Create the diagnostic client for reporting errors or for
1899 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00001900 llvm::OwningPtr<DiagnosticClient> DiagClient;
1901 if (VerifyDiagnostics) {
1902 // When checking diagnostics, just buffer them up.
1903 DiagClient.reset(new TextDiagnosticBuffer());
1904 if (InputFilenames.size() != 1) {
1905 fprintf(stderr, "-verify only works on single input files for now.\n");
1906 return 1;
1907 }
1908 if (!HTMLDiag.empty()) {
1909 fprintf(stderr, "-verify and -html-diags don't work together\n");
1910 return 1;
1911 }
1912 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00001913 // Print diagnostics to stderr by default.
Douglas Gregor965a13c2009-05-02 00:03:46 +00001914
1915 // If -fmessage-length=N was not specified, determine whether this
1916 // is a terminal and, if so, implicitly define -fmessage-length
1917 // appropriately.
1918 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregorc604d722009-05-11 18:06:49 +00001919 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor965a13c2009-05-02 00:03:46 +00001920
Chris Lattner5f7937d2009-04-17 20:40:01 +00001921 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00001922 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001923 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00001924 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00001925 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001926 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001927 !NoDiagnosticsFixIt,
1928 MessageLength));
Ted Kremenek5c341732008-08-07 17:49:57 +00001929 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00001930 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00001931 }
Chris Lattner94859302009-04-17 21:05:01 +00001932
1933 if (!DumpBuildInformation.empty()) {
1934 if (!HTMLDiag.empty()) {
1935 fprintf(stderr,
1936 "-dump-build-information and -html-diags don't work together\n");
1937 return 1;
1938 }
1939
1940 SetUpBuildDumpLog(argc, argv, DiagClient);
1941 }
1942
Ted Kremenek5c341732008-08-07 17:49:57 +00001943
Chris Lattner4b009652007-07-25 00:24:17 +00001944 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001945 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001946 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001947 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001948
Chris Lattner45a56e02007-12-05 23:24:17 +00001949 // -I- is a deprecated GCC feature, scan for it and reject it.
1950 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1951 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001952 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001953 I_dirs.erase(I_dirs.begin()+i);
1954 --i;
1955 }
1956 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001957
1958 // Get information about the target being compiled for.
1959 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001960 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1961
Chris Lattner2c77d852008-03-14 06:12:05 +00001962 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001963 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1964 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001965 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001966 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001967
Daniel Dunbar9c321102009-01-20 23:17:32 +00001968 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001969 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001970
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001971 llvm::OwningPtr<SourceManager> SourceMgr;
1972
Chris Lattnere1be6022009-04-14 23:22:57 +00001973 // Create a file manager object to provide access to and cache the filesystem.
1974 FileManager FileMgr;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001975
Daniel Dunbar07181d72009-05-06 03:16:41 +00001976 // Compute the feature set, unfortunately this effects the language!
1977 llvm::StringMap<bool> Features;
1978 ComputeFeatureMap(Target.get(), Features);
1979
Chris Lattner4b009652007-07-25 00:24:17 +00001980 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001981 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001982
Chris Lattner2b989562009-03-04 21:40:56 +00001983 /// Create a SourceManager object. This tracks and owns all the file
1984 /// buffers allocated to a translation unit.
1985 if (!SourceMgr)
1986 SourceMgr.reset(new SourceManager());
1987 else
1988 SourceMgr->clearIDTables();
1989
1990 // Initialize language options, inferring file types from input filenames.
1991 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00001992 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00001993
Chris Lattner2b989562009-03-04 21:40:56 +00001994 InitializeBaseLanguage();
1995 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001996 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar07181d72009-05-06 03:16:41 +00001997 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattner2b989562009-03-04 21:40:56 +00001998
1999 // Process the -I options and set them in the HeaderInfo.
2000 HeaderSearch HeaderInfo(FileMgr);
2001
Chris Lattnere1be6022009-04-14 23:22:57 +00002002
Chris Lattner2b989562009-03-04 21:40:56 +00002003 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2004
2005 // Set up the preprocessor with these options.
2006 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
2007 *SourceMgr.get(), HeaderInfo);
2008
2009 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2010
2011 if (!PP)
2012 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002013
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002014 if (ImplicitIncludePCH.empty() &&
2015 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002016 continue;
2017
Chris Lattner5f7937d2009-04-17 20:40:01 +00002018 if (!HTMLDiag.empty())
2019 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00002020
2021 // Process the source file.
Daniel Dunbar07181d72009-05-06 03:16:41 +00002022 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002023
Chris Lattner2961dc52009-04-17 20:16:08 +00002024 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00002025 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00002026 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002027
Mike Stump91d01352009-01-28 02:43:35 +00002028 if (Verbose)
2029 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2030 " hosted on " LLVM_HOSTTRIPLE "\n");
2031
Mike Stumpc4ba6cd2009-04-28 01:19:10 +00002032 if (!NoCaretDiagnostics)
2033 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2034 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2035 (NumDiagnostics == 1 ? "" : "s"));
Chris Lattner4b009652007-07-25 00:24:17 +00002036
2037 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002038 FileMgr.PrintStats();
2039 fprintf(stderr, "\n");
2040 }
Chris Lattner94859302009-04-17 21:05:01 +00002041
2042 delete ClangFrontendTimer;
2043 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002044
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002045 // If verifying diagnostics and we reached here, all is well.
2046 if (VerifyDiagnostics)
2047 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002048
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002049 // Managed static deconstruction. Useful for making things like
2050 // -time-passes usable.
2051 llvm::llvm_shutdown();
2052
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002053 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002054}