blob: bba5723724aad5617dc805a471ee9fc9ee6f1150 [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"
Chris Lattner01de9c82008-09-30 20:16:56 +000050#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000051#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000052#include "llvm/ADT/StringExtras.h"
Chris Lattner0e004a12009-04-08 18:24:34 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000054#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000055#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000056#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000057#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000058#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000059#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000060#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000061#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000062#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000063#include "llvm/System/Signals.h"
Douglas Gregor24b48b02009-04-02 19:05:20 +000064#include <cstdlib>
65
Chris Lattner4b009652007-07-25 00:24:17 +000066using namespace clang;
67
68//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000069// Source Location Parser
70//===----------------------------------------------------------------------===//
71
72/// \brief A source location that has been parsed on the command line.
73struct ParsedSourceLocation {
74 std::string FileName;
75 unsigned Line;
76 unsigned Column;
77
78 /// \brief Try to resolve the file name of a parsed source location.
79 ///
80 /// \returns true if there was an error, false otherwise.
81 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
82};
83
84bool
85ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
86 RequestedSourceLocation &Result) {
87 const FileEntry *File = FileMgr.getFile(FileName);
88 if (!File)
89 return true;
90
91 Result.File = File;
92 Result.Line = Line;
93 Result.Column = Column;
94 return false;
95}
96
97namespace llvm {
98 namespace cl {
99 /// \brief Command-line option parser that parses source locations.
100 ///
101 /// Source locations are of the form filename:line:column.
102 template<>
103 class parser<ParsedSourceLocation>
104 : public basic_parser<ParsedSourceLocation> {
105 public:
106 bool parse(Option &O, const char *ArgName,
107 const std::string &ArgValue,
108 ParsedSourceLocation &Val);
109 };
110
111 bool
112 parser<ParsedSourceLocation>::
113 parse(Option &O, const char *ArgName, const std::string &ArgValue,
114 ParsedSourceLocation &Val) {
115 using namespace clang;
116
117 const char *ExpectedFormat
118 = "source location must be of the form filename:line:column";
119 std::string::size_type SecondColon = ArgValue.rfind(':');
120 if (SecondColon == std::string::npos) {
121 std::fprintf(stderr, "%s\n", ExpectedFormat);
122 return true;
123 }
124 char *EndPtr;
125 long Column
126 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
127 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
128 std::fprintf(stderr, "%s\n", ExpectedFormat);
129 return true;
130 }
131
132 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
133 if (SecondColon == std::string::npos) {
134 std::fprintf(stderr, "%s\n", ExpectedFormat);
135 return true;
136 }
137 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
138 if (EndPtr != ArgValue.c_str() + SecondColon) {
139 std::fprintf(stderr, "%s\n", ExpectedFormat);
140 return true;
141 }
142
143 Val.FileName = ArgValue.substr(0, FirstColon);
144 Val.Line = Line;
145 Val.Column = Column;
146 return false;
147 }
148 }
149}
150
151//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000152// Global options.
153//===----------------------------------------------------------------------===//
154
Chris Lattnerefe33382009-02-18 01:51:21 +0000155/// ClangFrontendTimer - The front-end activities should charge time to it with
156/// TimeRegion. The -ftime-report option controls whether this will do
157/// anything.
158llvm::Timer *ClangFrontendTimer = 0;
159
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000160static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000161
Chris Lattner4b009652007-07-25 00:24:17 +0000162static llvm::cl::opt<bool>
163Verbose("v", llvm::cl::desc("Enable verbose output"));
164static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000165Stats("print-stats",
166 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000167static llvm::cl::opt<bool>
168DisableFree("disable-free",
169 llvm::cl::desc("Disable freeing of memory on exit"),
170 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +0000171
172enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000173 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000174 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000175 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000176 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000177 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000178 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000179 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000180 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000181 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000182 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek24612ae2008-03-18 21:19:49 +0000183 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000184 ASTPrint, // Parse ASTs and print them.
185 ASTDump, // Parse ASTs and dump them.
Douglas Gregord7915fd2009-04-26 02:02:08 +0000186 ASTDumpFull, // Parse ASTs and dump them, including the
187 // contents of a PCH file.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000188 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000189 PrintDeclContext, // Print DeclContext and their Decls.
Chris Lattner4b009652007-07-25 00:24:17 +0000190 ParsePrintCallbacks, // Parse and print each callback.
191 ParseSyntaxOnly, // Parse and perform semantic analysis.
192 ParseNoop, // Parse with noop callbacks.
193 RunPreprocessorOnly, // Just lex, no output.
194 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000195 DumpTokens, // Dump out preprocessed tokens.
196 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000197 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000198 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000199 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000200 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000201};
202
203static llvm::cl::opt<ProgActions>
204ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
205 llvm::cl::init(ParseSyntaxOnly),
206 llvm::cl::values(
207 clEnumValN(RunPreprocessorOnly, "Eonly",
208 "Just run preprocessor, no output (for timings)"),
209 clEnumValN(PrintPreprocessedInput, "E",
210 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000211 clEnumValN(DumpRawTokens, "dump-raw-tokens",
212 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000213 clEnumValN(RunAnalysis, "analyze",
214 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000215 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000216 "Run preprocessor, dump internal rep of tokens"),
217 clEnumValN(ParseNoop, "parse-noop",
218 "Run parser with noop callbacks (for timings)"),
219 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
220 "Run parser and perform semantic analysis"),
221 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
222 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000223 clEnumValN(EmitHTML, "emit-html",
224 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000225 clEnumValN(ASTPrint, "ast-print",
226 "Build ASTs and then pretty-print them"),
227 clEnumValN(ASTDump, "ast-dump",
228 "Build ASTs and then debug dump them"),
Douglas Gregord7915fd2009-04-26 02:02:08 +0000229 clEnumValN(ASTDumpFull, "ast-dump-full",
230 "Build ASTs and then debug dump them, including PCH"),
Chris Lattner664dd082007-10-11 00:37:43 +0000231 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000232 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000233 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000234 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000235 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000236 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000237 clEnumValN(GeneratePCH, "emit-pch",
238 "Generate pre-compiled header file"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000239 clEnumValN(EmitAssembly, "S",
240 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000241 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000242 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000243 clEnumValN(EmitBC, "emit-llvm-bc",
244 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000245 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
246 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000247 clEnumValN(RewriteTest, "rewrite-test",
248 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000249 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000250 "Rewrite ObjC into C (code rewriter example)"),
251 clEnumValN(RewriteMacros, "rewrite-macros",
252 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000253 clEnumValN(RewriteBlocks, "rewrite-blocks",
254 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000255 clEnumValN(FixIt, "fixit",
256 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000257 clEnumValEnd));
258
Ted Kremenekd01eae62007-12-19 19:47:59 +0000259
260static llvm::cl::opt<std::string>
261OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000262 llvm::cl::value_desc("path"),
Douglas Gregor608ff622009-04-22 21:45:53 +0000263 llvm::cl::desc("Specify output file"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000264
Ted Kremenek57f25b22008-12-02 19:57:31 +0000265
266//===----------------------------------------------------------------------===//
267// PTH.
268//===----------------------------------------------------------------------===//
269
270static llvm::cl::opt<std::string>
271TokenCache("token-cache", llvm::cl::value_desc("path"),
272 llvm::cl::desc("Use specified token cache file"));
273
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000274//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000275// Diagnostic Options
276//===----------------------------------------------------------------------===//
277
Ted Kremenek10389cf2007-09-26 19:42:19 +0000278static llvm::cl::opt<bool>
279VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000280 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000281
Ted Kremenekfd75e312008-03-27 06:17:42 +0000282static llvm::cl::opt<std::string>
283HTMLDiag("html-diags",
284 llvm::cl::desc("Generate HTML to report diagnostics"),
285 llvm::cl::value_desc("HTML directory"));
286
Nico Weber0e13eaa2008-08-05 23:33:20 +0000287static llvm::cl::opt<bool>
288NoShowColumn("fno-show-column",
289 llvm::cl::desc("Do not include column number on diagnostics"));
290
291static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000292NoShowLocation("fno-show-source-location",
293 llvm::cl::desc("Do not include source location information with"
294 " diagnostics"));
295
296static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000297NoCaretDiagnostics("fno-caret-diagnostics",
298 llvm::cl::desc("Do not include source line and caret with"
299 " diagnostics"));
300
Chris Lattner695a4f52009-03-13 01:08:23 +0000301static llvm::cl::opt<bool>
Chris Lattner041bd732009-04-19 07:44:08 +0000302NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
303 llvm::cl::desc("Do not include fixit information in"
304 " diagnostics"));
305
306static llvm::cl::opt<bool>
Chris Lattner13bac9e2009-04-21 05:34:31 +0000307PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
308 llvm::cl::desc("Print source range spans in numeric form"));
309
310static llvm::cl::alias
311PrintSourceRangeInfo2("fprint-source-range-info",
312 llvm::cl::desc("Print source range spans in numeric form [deprecated]"),
313 llvm::cl::aliasopt(PrintSourceRangeInfo));
Chris Lattner695a4f52009-03-13 01:08:23 +0000314
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000315static llvm::cl::opt<bool>
316PrintDiagnosticOption("fdiagnostics-show-option",
317 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weber0e13eaa2008-08-05 23:33:20 +0000318
Chris Lattner4b009652007-07-25 00:24:17 +0000319//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000320// C++ Visualization.
321//===----------------------------------------------------------------------===//
322
323static llvm::cl::opt<std::string>
324InheritanceViewCls("cxx-inheritance-view",
325 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000326 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000327
328//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000329// Builtin Options
330//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000331
332static llvm::cl::opt<bool>
333TimeReport("ftime-report",
334 llvm::cl::desc("Print the amount of time each "
335 "phase of compilation takes"));
336
Douglas Gregor23d23262009-02-14 20:49:29 +0000337static llvm::cl::opt<bool>
338Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000339 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000340 "freestanding environment"));
341
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000342static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000343AllowBuiltins("fbuiltin", llvm::cl::init(true),
344 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000345
346
347static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000348MathErrno("fmath-errno", llvm::cl::init(true),
349 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000350
Douglas Gregor23d23262009-02-14 20:49:29 +0000351//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000352// Language Options
353//===----------------------------------------------------------------------===//
354
355enum LangKind {
356 langkind_unspecified,
357 langkind_c,
358 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000359 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000360 langkind_cxx,
361 langkind_cxx_cpp,
362 langkind_objc,
363 langkind_objc_cpp,
364 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000365 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000366};
367
Chris Lattner4b009652007-07-25 00:24:17 +0000368static llvm::cl::opt<LangKind>
369BaseLang("x", llvm::cl::desc("Base language to compile"),
370 llvm::cl::init(langkind_unspecified),
371 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
372 clEnumValN(langkind_cxx, "c++", "C++"),
373 clEnumValN(langkind_objc, "objective-c", "Objective C"),
374 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000375 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000376 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000377 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
378 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000379 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000380 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000381 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
382 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000383 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000384 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000385 clEnumValN(langkind_c, "c-header",
386 "C header"),
387 clEnumValN(langkind_objc, "objective-c-header",
388 "Objective-C header"),
389 clEnumValN(langkind_cxx, "c++-header",
390 "C++ header"),
391 clEnumValN(langkind_objcxx, "objective-c++-header",
392 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000393 clEnumValEnd));
394
395static llvm::cl::opt<bool>
396LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
397 llvm::cl::Hidden);
398static llvm::cl::opt<bool>
399LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
400 llvm::cl::Hidden);
401
Chris Lattnere1be6022009-04-14 23:22:57 +0000402static llvm::cl::opt<bool>
403ObjCExclusiveGC("fobjc-gc-only",
404 llvm::cl::desc("Use GC exclusively for Objective-C related "
405 "memory management"));
406
407static llvm::cl::opt<bool>
408ObjCEnableGC("fobjc-gc",
409 llvm::cl::desc("Enable Objective-C garbage collection"));
410
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000411static llvm::cl::opt<bool>
412ObjCEnableGCBitmapPrint("print-ivar-layout",
413 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
414
Chris Lattnere1be6022009-04-14 23:22:57 +0000415static llvm::cl::opt<LangOptions::VisibilityMode>
416SymbolVisibility("fvisibility",
417 llvm::cl::desc("Set the default symbol visibility:"),
418 llvm::cl::init(LangOptions::Default),
419 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
420 "Use default symbol visibility"),
421 clEnumValN(LangOptions::Hidden, "hidden",
422 "Use hidden symbol visibility"),
423 clEnumValN(LangOptions::Protected,"protected",
424 "Use protected symbol visibility"),
425 clEnumValEnd));
426
427static llvm::cl::opt<bool>
428OverflowChecking("ftrapv",
429 llvm::cl::desc("Trap on integer overflow"),
430 llvm::cl::init(false));
431
432
Ted Kremenek11ad8952007-12-05 23:49:08 +0000433/// InitializeBaseLanguage - Handle the -x foo options.
434static void InitializeBaseLanguage() {
435 if (LangObjC)
436 BaseLang = langkind_objc;
437 else if (LangObjCXX)
438 BaseLang = langkind_objcxx;
439}
440
441static LangKind GetLanguage(const std::string &Filename) {
442 if (BaseLang != langkind_unspecified)
443 return BaseLang;
444
445 std::string::size_type DotPos = Filename.rfind('.');
446
447 if (DotPos == std::string::npos) {
448 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000449 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000450 }
451
Ted Kremenek11ad8952007-12-05 23:49:08 +0000452 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
453 // C header: .h
454 // C++ header: .hh or .H;
455 // assembler no preprocessing: .s
456 // assembler: .S
457 if (Ext == "c")
458 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000459 else if (Ext == "S" ||
460 // If the compiler is run on a .s file, preprocess it as .S
461 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000462 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000463 else if (Ext == "i")
464 return langkind_c_cpp;
465 else if (Ext == "ii")
466 return langkind_cxx_cpp;
467 else if (Ext == "m")
468 return langkind_objc;
469 else if (Ext == "mi")
470 return langkind_objc_cpp;
471 else if (Ext == "mm" || Ext == "M")
472 return langkind_objcxx;
473 else if (Ext == "mii")
474 return langkind_objcxx_cpp;
475 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
476 Ext == "c++" || Ext == "cp" || Ext == "cxx")
477 return langkind_cxx;
478 else
479 return langkind_c;
480}
481
482
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000483static void InitializeCOptions(LangOptions &Options) {
484 // Do nothing.
485}
486
487static void InitializeObjCOptions(LangOptions &Options) {
488 Options.ObjC1 = Options.ObjC2 = 1;
489}
490
491
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000492static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000493 // FIXME: implement -fpreprocessed mode.
494 bool NoPreprocess = false;
495
Ted Kremenek11ad8952007-12-05 23:49:08 +0000496 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000497 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000498 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000499 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000500 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000501 case langkind_c_cpp:
502 NoPreprocess = true;
503 // FALLTHROUGH
504 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000505 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000506 break;
507 case langkind_cxx_cpp:
508 NoPreprocess = true;
509 // FALLTHROUGH
510 case langkind_cxx:
511 Options.CPlusPlus = 1;
512 break;
513 case langkind_objc_cpp:
514 NoPreprocess = true;
515 // FALLTHROUGH
516 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000517 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000518 break;
519 case langkind_objcxx_cpp:
520 NoPreprocess = true;
521 // FALLTHROUGH
522 case langkind_objcxx:
523 Options.ObjC1 = Options.ObjC2 = 1;
524 Options.CPlusPlus = 1;
525 break;
526 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000527
528 if (ObjCExclusiveGC)
529 Options.setGCMode(LangOptions::GCOnly);
530 else if (ObjCEnableGC)
531 Options.setGCMode(LangOptions::HybridGC);
532
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000533 if (ObjCEnableGCBitmapPrint)
534 Options.ObjCGCBitmapPrint = 1;
535
Chris Lattnere1be6022009-04-14 23:22:57 +0000536 Options.setVisibilityMode(SymbolVisibility);
537 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000538}
539
540/// LangStds - Language standards we support.
541enum LangStds {
542 lang_unspecified,
543 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000544 lang_gnu_START,
545 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000546 lang_cxx98, lang_gnucxx98,
547 lang_cxx0x, lang_gnucxx0x
548};
549
550static llvm::cl::opt<LangStds>
551LangStd("std", llvm::cl::desc("Language standard to compile for"),
552 llvm::cl::init(lang_unspecified),
553 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
554 clEnumValN(lang_c89, "c90", "ISO C 1990"),
555 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
556 clEnumValN(lang_c94, "iso9899:199409",
557 "ISO C 1990 with amendment 1"),
558 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000559 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000560 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000561 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000562 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000563 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000564 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000565 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000566 clEnumValN(lang_gnu99, "gnu9x",
567 "ISO C 1999 with GNU extensions"),
568 clEnumValN(lang_cxx98, "c++98",
569 "ISO C++ 1998 with amendments"),
570 clEnumValN(lang_gnucxx98, "gnu++98",
571 "ISO C++ 1998 with amendments and GNU "
572 "extensions (default for C++)"),
573 clEnumValN(lang_cxx0x, "c++0x",
574 "Upcoming ISO C++ 200x with amendments"),
575 clEnumValN(lang_gnucxx0x, "gnu++0x",
576 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000577 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000578 clEnumValEnd));
579
580static llvm::cl::opt<bool>
581NoOperatorNames("fno-operator-names",
582 llvm::cl::desc("Do not treat C++ operator name keywords as "
583 "synonyms for operators"));
584
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000585static llvm::cl::opt<bool>
586PascalStrings("fpascal-strings",
587 llvm::cl::desc("Recognize and construct Pascal-style "
588 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000589
590static llvm::cl::opt<bool>
591MSExtensions("fms-extensions",
592 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000593 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000594
595static llvm::cl::opt<bool>
596WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000597 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000598
599static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000600NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000601 llvm::cl::desc("Disallow implicit conversions between "
602 "vectors with a different number of "
603 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000604
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000605static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000606EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000607
608static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000609EnableHeinousExtensions("fheinous-gnu-extensions",
610 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
611 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
612
613static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000614ObjCNonFragileABI("fobjc-nonfragile-abi",
615 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000616
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000617static llvm::cl::opt<bool>
618EmitAllDecls("femit-all-decls",
619 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000620
Daniel Dunbar91692d92008-08-11 17:36:14 +0000621// FIXME: This (and all GCC -f options) really come in -f... and
622// -fno-... forms, and additionally support automagic behavior when
623// they are not defined. For example, -fexceptions defaults to on or
624// off depending on the language. We should support this behavior in
625// some form (perhaps just add a facility for distinguishing when an
626// has its default value from when it has been set to its default
627// value).
628static llvm::cl::opt<bool>
629Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000630 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000631
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000632static llvm::cl::opt<bool>
633GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000634 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000635 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000636
637static llvm::cl::opt<bool>
638NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000639 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000640 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000641
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000642
643
644static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000645Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000646
Chris Lattner738d3f62009-03-02 22:11:07 +0000647static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000648TargetFeatures("mattr", llvm::cl::CommaSeparated,
649 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
650
Douglas Gregor375733c2009-03-10 00:06:19 +0000651static llvm::cl::opt<unsigned>
652TemplateDepth("ftemplate-depth", llvm::cl::init(99),
653 llvm::cl::desc("Maximum depth of recursive template "
654 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000655static llvm::cl::opt<bool>
656DollarsInIdents("fdollars-in-identifiers",
657 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000658
Anders Carlssondfd77642009-04-06 17:37:10 +0000659
660static llvm::cl::opt<bool>
661OptSize("Os", llvm::cl::desc("Optimize for size"));
662
663static llvm::cl::opt<bool>
664NoCommon("fno-common",
665 llvm::cl::desc("Compile common globals like normal definitions"),
666 llvm::cl::ValueDisallowed);
667
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000668static llvm::cl::opt<std::string>
669MainFileName("main-file-name",
670 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000671
672// It might be nice to add bounds to the CommandLine library directly.
673struct OptLevelParser : public llvm::cl::parser<unsigned> {
674 bool parse(llvm::cl::Option &O, const char *ArgName,
675 const std::string &Arg, unsigned &Val) {
676 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
677 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000678 if (Val > 3)
679 return O.error(": '" + Arg + "' invalid optimization level!");
680 return false;
681 }
682};
683static llvm::cl::opt<unsigned, false, OptLevelParser>
684OptLevel("O", llvm::cl::Prefix,
685 llvm::cl::desc("Optimization level"),
686 llvm::cl::init(0));
687
Daniel Dunbare079c712009-04-08 03:03:23 +0000688static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000689PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
690
691static llvm::cl::opt<bool>
692StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000693
Daniel Dunbar34542952008-08-23 08:43:39 +0000694static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
695 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000696 // Allow the target to set the default the langauge options as it sees fit.
697 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000698
Chris Lattnerf6790a82009-03-03 19:56:18 +0000699 // If there are any -mattr options, pass them to the target for validation and
700 // processing. The driver should have already consolidated all the
701 // target-feature settings and passed them to us in the -mattr list. The
702 // -mattr list is treated by the code generator as a diff against the -mcpu
703 // setting, but the driver should pass all enabled options as "+" settings.
704 // This means that the target should only look at + settings.
Chris Lattner880d38e2009-04-13 06:33:49 +0000705 if (!TargetFeatures.empty()) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000706 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000707 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
708 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000709 if (Opt != -1) {
710 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000711 fprintf(stderr, "invalid feature '%s'\n",
712 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000713 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000714 fprintf(stderr, "feature '%s': %s\n",
715 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000716 exit(1);
717 }
718 }
719
Chris Lattner4b009652007-07-25 00:24:17 +0000720 if (LangStd == lang_unspecified) {
721 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000722 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000723 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000724 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000725 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000726 case langkind_c_cpp:
727 case langkind_objc:
728 case langkind_objc_cpp:
729 LangStd = lang_gnu99;
730 break;
731 case langkind_cxx:
732 case langkind_cxx_cpp:
733 case langkind_objcxx:
734 case langkind_objcxx_cpp:
735 LangStd = lang_gnucxx98;
736 break;
737 }
738 }
739
740 switch (LangStd) {
741 default: assert(0 && "Unknown language standard!");
742
743 // Fall through from newer standards to older ones. This isn't really right.
744 // FIXME: Enable specifically the right features based on the language stds.
745 case lang_gnucxx0x:
746 case lang_cxx0x:
747 Options.CPlusPlus0x = 1;
748 // FALL THROUGH
749 case lang_gnucxx98:
750 case lang_cxx98:
751 Options.CPlusPlus = 1;
752 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000753 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000754 // FALL THROUGH.
755 case lang_gnu99:
756 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000757 Options.C99 = 1;
758 Options.HexFloats = 1;
759 // FALL THROUGH.
760 case lang_gnu89:
761 Options.BCPLComment = 1; // Only for C99/C++.
762 // FALL THROUGH.
763 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000764 Options.Digraphs = 1; // C94, C99, C++.
765 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000766 case lang_c89:
767 break;
768 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000769
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000770 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
771 Options.GNUMode = LangStd >= lang_gnu_START;
772
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000773 if (Options.CPlusPlus) {
774 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000775 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000776 }
Chris Lattner4b009652007-07-25 00:24:17 +0000777
Chris Lattner6ab935b2008-04-05 06:32:51 +0000778 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
779 Options.ImplicitInt = 1;
780 else
781 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000782
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000783 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
784 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000785 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000786 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000787 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000788
Chris Lattner58d5ba52008-12-05 00:10:44 +0000789 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
790 // even if they are normally on for the target. In GNU modes (e.g.
791 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000792 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000793 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000794 Options.Blocks = 0;
795
Chris Lattner284784c2009-04-19 07:06:52 +0000796 // Default to not accepting '$' in identifiers when preprocessing assembler,
797 // but do accept when preprocessing C. FIXME: these defaults are right for
798 // darwin, are they right everywhere?
799 Options.DollarIdents = LK != langkind_asm_cpp;
800 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner77c04832009-04-19 07:00:02 +0000801 Options.DollarIdents = DollarsInIdents;
802
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000803 if (PascalStrings.getPosition())
804 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000805 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000806 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000807 if (NoLaxVectorConversions.getPosition())
808 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000809 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000810 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000811 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000812
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000813 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000814 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000815 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000816 Options.Freestanding = Options.NoBuiltin = 1;
817
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000818 if (EnableHeinousExtensions)
819 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000820
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000821 Options.MathErrno = MathErrno;
822
Douglas Gregor375733c2009-03-10 00:06:19 +0000823 Options.InstantiationDepth = TemplateDepth;
824
Chris Lattnerddae7102008-12-04 22:54:33 +0000825 // Override the default runtime if the user requested it.
826 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000827 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000828 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000829 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000830
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000831 if (ObjCNonFragileABI)
832 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000833
834 if (EmitAllDecls)
835 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000836
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000837 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
838 // support.
839 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000840
841 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000842 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000843 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000844
845 assert(PICLevel <= 2 && "Invalid value for -pic-level");
846 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000847
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000848 Options.GNUInline = !Options.C99;
849 // FIXME: This is affected by other options (-fno-inline).
850 Options.NoInline = !OptSize && !OptLevel;
851
852 Options.Static = StaticDefine;
853
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000854 if (MainFileName.getPosition())
855 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000856}
857
858//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000859// Target Triple Processing.
860//===----------------------------------------------------------------------===//
861
862static llvm::cl::opt<std::string>
863TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000864 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000865
Chris Lattnerfc457002008-03-05 01:18:20 +0000866static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000867Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000868
Chris Lattner2b168e02008-09-30 01:13:12 +0000869static llvm::cl::opt<std::string>
870MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000871 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000872
Chris Lattner01de9c82008-09-30 20:16:56 +0000873// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
874// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000875
876// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000877static void HandleMacOSVersionMin(std::string &Triple) {
878 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
879 if (DarwinDashIdx == std::string::npos) {
880 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000881 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000882 exit(1);
883 }
884 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
885
Chris Lattner01de9c82008-09-30 20:16:56 +0000886 // Remove the number.
887 Triple.resize(DarwinNumIdx);
888
889 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
890 bool MacOSVersionMinIsInvalid = false;
891 int VersionNum = 0;
892 if (MacOSVersionMin.size() < 4 ||
893 MacOSVersionMin.substr(0, 3) != "10." ||
894 !isdigit(MacOSVersionMin[3])) {
895 MacOSVersionMinIsInvalid = true;
896 } else {
897 const char *Start = MacOSVersionMin.c_str()+3;
898 char *End = 0;
899 VersionNum = (int)strtol(Start, &End, 10);
900
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000901 // The version number must be in the range 0-9.
902 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
903
Chris Lattner01de9c82008-09-30 20:16:56 +0000904 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
905 Triple += llvm::itostr(VersionNum+4);
906
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000907 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
908 // Add the period piece (.7) to the end of the triple. This gives us
909 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000910 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000911 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
912 MacOSVersionMinIsInvalid = true;
913 }
914 }
915
916 if (MacOSVersionMinIsInvalid) {
917 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000918 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000919 MacOSVersionMin.c_str());
920 exit(1);
921 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000922 else if (VersionNum <= 4 &&
923 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
924 fprintf(stderr,
925 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
926 MacOSVersionMin.c_str());
927 exit(1);
928 }
929
Chris Lattner01de9c82008-09-30 20:16:56 +0000930}
931
Daniel Dunbar93f64532009-04-10 19:52:24 +0000932static llvm::cl::opt<std::string>
933IPhoneOSVersionMin("miphoneos-version-min",
934 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
935
936// If -miphoneos-version-min=2.2 is specified, change the triple from being
937// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
938// 9 as the default major Darwin number, and encode the iPhone OS version
939// number in the minor version and revision.
940
941// FIXME: We should have the driver do this instead.
942static void HandleIPhoneOSVersionMin(std::string &Triple) {
943 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
944 if (DarwinDashIdx == std::string::npos) {
945 fprintf(stderr,
946 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
947 exit(1);
948 }
949 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
950
951 // Remove the number.
952 Triple.resize(DarwinNumIdx);
953
954 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
955 bool IPhoneOSVersionMinIsInvalid = false;
956 int VersionNum = 0;
957 if (IPhoneOSVersionMin.size() < 3 ||
958 !isdigit(IPhoneOSVersionMin[0])) {
959 IPhoneOSVersionMinIsInvalid = true;
960 } else {
961 const char *Start = IPhoneOSVersionMin.c_str();
962 char *End = 0;
963 VersionNum = (int)strtol(Start, &End, 10);
964
965 // The version number must be in the range 0-9.
966 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
967
968 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
969 Triple += "9." + llvm::itostr(VersionNum);
970
971 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
972 // Add the period piece (.2) to the end of the triple. This gives us
973 // something like ...-darwin9.2.2
974 Triple += End;
975 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
976 IPhoneOSVersionMinIsInvalid = true;
977 }
978 }
979
980 if (IPhoneOSVersionMinIsInvalid) {
981 fprintf(stderr,
982 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
983 IPhoneOSVersionMin.c_str());
984 exit(1);
985 }
986}
987
Chris Lattner01de9c82008-09-30 20:16:56 +0000988/// CreateTargetTriple - Process the various options that affect the target
989/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000990static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000991 // Initialize base triple. If a -triple option has been specified, use
992 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000993 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000994 if (Triple.empty())
995 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000996
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000997 // If -arch foo was specified, remove the architecture from the triple we have
998 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000999
1000 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +00001001 if (!Arch.empty()) {
1002 // Decompose the base triple into "arch" and suffix.
1003 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +00001004
Chris Lattner2b168e02008-09-30 01:13:12 +00001005 if (FirstDashIdx == std::string::npos) {
1006 fprintf(stderr,
1007 "Malformed target triple: \"%s\" ('-' could not be found).\n",
1008 Triple.c_str());
1009 exit(1);
1010 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +00001011
1012 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1013 if (Arch == "ppc")
1014 Arch = "powerpc";
1015 else if (Arch == "ppc64")
1016 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +00001017
Chris Lattner2b168e02008-09-30 01:13:12 +00001018 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1019 }
1020
1021 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1022 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +00001023 if (!MacOSVersionMin.empty())
1024 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +00001025 else if (!IPhoneOSVersionMin.empty())
1026 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +00001027
Chris Lattner2b168e02008-09-30 01:13:12 +00001028 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001029}
1030
1031//===----------------------------------------------------------------------===//
Chris Lattner94269d72009-04-21 05:40:52 +00001032// SourceManager initialization.
Chris Lattner4b009652007-07-25 00:24:17 +00001033//===----------------------------------------------------------------------===//
1034
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001035static bool InitializeSourceManager(Preprocessor &PP,
1036 const std::string &InFile) {
1037 // Figure out where to get and map in the main file.
1038 SourceManager &SourceMgr = PP.getSourceManager();
1039 FileManager &FileMgr = PP.getFileManager();
1040
1041 if (InFile != "-") {
1042 const FileEntry *File = FileMgr.getFile(InFile);
1043 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1044 if (SourceMgr.getMainFileID().isInvalid()) {
1045 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1046 << InFile.c_str();
1047 return true;
1048 }
1049 } else {
1050 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1051
1052 // If stdin was empty, SB is null. Cons up an empty memory
1053 // buffer now.
1054 if (!SB) {
1055 const char *EmptyStr = "";
1056 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1057 }
1058
1059 SourceMgr.createMainFileIDForMemBuffer(SB);
1060 if (SourceMgr.getMainFileID().isInvalid()) {
1061 PP.getDiagnostics().Report(FullSourceLoc(),
1062 diag::err_fe_error_reading_stdin);
1063 return true;
1064 }
1065 }
1066
1067 return false;
1068}
1069
Chris Lattner47b6a162008-04-19 23:09:31 +00001070
Chris Lattner94269d72009-04-21 05:40:52 +00001071//===----------------------------------------------------------------------===//
1072// Preprocessor Initialization
1073//===----------------------------------------------------------------------===//
Sam Bishop61a20782008-04-14 14:41:57 +00001074
Chris Lattner94269d72009-04-21 05:40:52 +00001075// FIXME: Preprocessor builtins to support.
1076// -A... - Play with #assertions
1077// -undef - Undefine all predefined macros
Chris Lattnerb62396d2009-04-08 20:15:42 +00001078
Chris Lattner94269d72009-04-21 05:40:52 +00001079static llvm::cl::list<std::string>
1080D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1081 llvm::cl::desc("Predefine the specified macro"));
1082static llvm::cl::list<std::string>
1083U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1084 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001085
Chris Lattner94269d72009-04-21 05:40:52 +00001086static llvm::cl::list<std::string>
1087ImplicitIncludes("include", llvm::cl::value_desc("file"),
1088 llvm::cl::desc("Include file before parsing"));
1089static llvm::cl::list<std::string>
1090ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1091 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001092
Chris Lattner94269d72009-04-21 05:40:52 +00001093static llvm::cl::opt<std::string>
1094ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1095 llvm::cl::desc("Include precompiled header file"));
1096
1097static llvm::cl::opt<std::string>
1098ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1099 llvm::cl::desc("Include file before parsing"));
1100
Chris Lattner4b009652007-07-25 00:24:17 +00001101
1102//===----------------------------------------------------------------------===//
1103// Preprocessor include path information.
1104//===----------------------------------------------------------------------===//
1105
1106// This tool exports a large number of command line options to control how the
1107// preprocessor searches for header files. At root, however, the Preprocessor
1108// object takes a very simple interface: a list of directories to search for
1109//
1110// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001111// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001112//
Chris Lattner4b009652007-07-25 00:24:17 +00001113
1114static llvm::cl::opt<bool>
1115nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1116
1117// Various command line options. These four add directories to each chain.
1118static llvm::cl::list<std::string>
1119F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1120 llvm::cl::desc("Add directory to framework include search path"));
1121static llvm::cl::list<std::string>
1122I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1123 llvm::cl::desc("Add directory to include search path"));
1124static llvm::cl::list<std::string>
1125idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1126 llvm::cl::desc("Add directory to AFTER include search path"));
1127static llvm::cl::list<std::string>
1128iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1129 llvm::cl::desc("Add directory to QUOTE include search path"));
1130static llvm::cl::list<std::string>
1131isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1132 llvm::cl::desc("Add directory to SYSTEM include search path"));
1133
1134// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1135static llvm::cl::list<std::string>
1136iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1137 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1138static llvm::cl::list<std::string>
1139iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1140 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1141static llvm::cl::list<std::string>
1142iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1143 llvm::cl::Prefix,
1144 llvm::cl::desc("Set directory to include search path with prefix"));
1145
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001146static llvm::cl::opt<std::string>
1147isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1148 llvm::cl::desc("Set the system root directory (usually /)"));
1149
Chris Lattner4b009652007-07-25 00:24:17 +00001150// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001151
Chris Lattner4b009652007-07-25 00:24:17 +00001152/// InitializeIncludePaths - Process the -I options and set them in the
1153/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001154void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1155 FileManager &FM, const LangOptions &Lang) {
1156 InitHeaderSearch Init(Headers, Verbose, isysroot);
1157
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001158 // Handle -I... and -F... options, walking the lists in parallel.
1159 unsigned Iidx = 0, Fidx = 0;
1160 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1161 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001162 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001163 ++Iidx;
1164 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001165 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001166 ++Fidx;
1167 }
1168 }
Chris Lattner4b009652007-07-25 00:24:17 +00001169
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001170 // Consume what's left from whatever list was longer.
1171 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001172 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001173 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001174 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001175
1176 // Handle -idirafter... options.
1177 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001178 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1179 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001180
1181 // Handle -iquote... options.
1182 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001183 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001184
1185 // Handle -isystem... options.
1186 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001187 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001188
1189 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1190 // parallel, processing the values in order of occurance to get the right
1191 // prefixes.
1192 {
1193 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1194 unsigned iprefix_idx = 0;
1195 unsigned iwithprefix_idx = 0;
1196 unsigned iwithprefixbefore_idx = 0;
1197 bool iprefix_done = iprefix_vals.empty();
1198 bool iwithprefix_done = iwithprefix_vals.empty();
1199 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1200 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1201 if (!iprefix_done &&
1202 (iwithprefix_done ||
1203 iprefix_vals.getPosition(iprefix_idx) <
1204 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1205 (iwithprefixbefore_done ||
1206 iprefix_vals.getPosition(iprefix_idx) <
1207 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1208 Prefix = iprefix_vals[iprefix_idx];
1209 ++iprefix_idx;
1210 iprefix_done = iprefix_idx == iprefix_vals.size();
1211 } else if (!iwithprefix_done &&
1212 (iwithprefixbefore_done ||
1213 iwithprefix_vals.getPosition(iwithprefix_idx) <
1214 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001215 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1216 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001217 ++iwithprefix_idx;
1218 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1219 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001220 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1221 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001222 ++iwithprefixbefore_idx;
1223 iwithprefixbefore_done =
1224 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1225 }
1226 }
1227 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001228
Nico Weber770e3882008-08-22 09:25:22 +00001229 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001230
Daniel Dunbar4e604292009-02-21 20:52:41 +00001231 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001232 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001233 llvm::sys::Path::GetMainExecutable(Argv0,
1234 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001235 if (!MainExecutablePath.isEmpty()) {
1236 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1237 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001238
1239 // Get foo/lib/clang/1.0/include
1240 //
1241 // FIXME: Don't embed version here.
1242 MainExecutablePath.appendComponent("lib");
1243 MainExecutablePath.appendComponent("clang");
1244 MainExecutablePath.appendComponent("1.0");
1245 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001246
1247 // We pass true to ignore sysroot so that we *always* look for clang headers
1248 // relative to our executable, never relative to -isysroot.
1249 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1250 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001251 }
1252
Nico Weber770e3882008-08-22 09:25:22 +00001253 if (!nostdinc)
1254 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001255
1256 // Now that we have collected all of the include paths, merge them all
1257 // together and tell the preprocessor about them.
1258
Nico Weber770e3882008-08-22 09:25:22 +00001259 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001260}
1261
Chris Lattner94269d72009-04-21 05:40:52 +00001262void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1263{
1264 // Add macros from the command line.
1265 unsigned d = 0, D = D_macros.size();
1266 unsigned u = 0, U = U_macros.size();
1267 while (d < D || u < U) {
1268 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1269 InitOpts.addMacroDef(D_macros[d++]);
1270 else
1271 InitOpts.addMacroUndef(U_macros[u++]);
1272 }
1273
1274 // If -imacros are specified, include them now. These are processed before
1275 // any -include directives.
1276 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1277 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1278
1279 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) {
1280 // We want to add these paths to the predefines buffer in order, make a
1281 // temporary vector to sort by their occurrence.
1282 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1283
1284 if (!ImplicitIncludePTH.empty())
1285 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1286 &ImplicitIncludePTH));
1287 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1288 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1289 &ImplicitIncludes[i]));
1290 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1291
1292
1293 // Now that they are ordered by position, add to the predefines buffer.
1294 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1295 std::string *Ptr = OrderedPaths[i].second;
1296 if (!ImplicitIncludes.empty() &&
1297 Ptr >= &ImplicitIncludes[0] &&
1298 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1299 InitOpts.addInclude(*Ptr, false);
1300 } else {
1301 assert(Ptr == &ImplicitIncludePTH);
1302 InitOpts.addInclude(*Ptr, true);
1303 }
1304 }
1305 }
1306}
1307
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001308//===----------------------------------------------------------------------===//
1309// Driver PreprocessorFactory - For lazily generating preprocessors ...
1310//===----------------------------------------------------------------------===//
1311
1312namespace {
1313class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001314 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001315 Diagnostic &Diags;
1316 const LangOptions &LangInfo;
1317 TargetInfo &Target;
1318 SourceManager &SourceMgr;
1319 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001320
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001321public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001322 DriverPreprocessorFactory(const std::string &infile,
1323 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001324 TargetInfo &target, SourceManager &SM,
1325 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001326 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001327 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001328
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001329
1330 virtual ~DriverPreprocessorFactory() {}
1331
1332 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001333 llvm::OwningPtr<PTHManager> PTHMgr;
1334
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001335 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1336 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1337 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001338 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001339 }
1340
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001341 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001342 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1343 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001344 PTHMgr.reset(PTHManager::Create(x, &Diags,
1345 TokenCache.empty() ? Diagnostic::Error
1346 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001347 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001348
Ted Kremenek6348cc62009-03-22 06:42:39 +00001349 if (Diags.hasErrorOccurred())
1350 exit(1);
1351
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001352 // Create the Preprocessor.
1353 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1354 SourceMgr, HeaderInfo,
1355 PTHMgr.get()));
1356
1357 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1358 // That argument is used as the IdentifierInfoLookup argument to
1359 // IdentifierTable's ctor.
1360 if (PTHMgr) {
1361 PTHMgr->setPreprocessor(PP.get());
1362 PP->setPTHManager(PTHMgr.take());
1363 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001364
Chris Lattner94269d72009-04-21 05:40:52 +00001365 PreprocessorInitOptions InitOpts;
1366 InitializePreprocessorInitOptions(InitOpts);
1367 if (InitializePreprocessor(*PP, InFile, InitOpts))
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001368 return 0;
Chris Lattner94269d72009-04-21 05:40:52 +00001369
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001370 /// FIXME: PP can only handle one callback
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001371 if (ProgAction != PrintPreprocessedInput) {
1372 std::string ErrStr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001373 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001374 if (!DFG && !ErrStr.empty()) {
1375 fprintf(stderr, "%s", ErrStr.c_str());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001376 return 0;
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001377 }
1378 }
1379
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001380 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001381 }
1382};
1383}
Chris Lattner4b009652007-07-25 00:24:17 +00001384
Chris Lattner4b009652007-07-25 00:24:17 +00001385//===----------------------------------------------------------------------===//
1386// Basic Parser driver
1387//===----------------------------------------------------------------------===//
1388
Chris Lattner9d818a22008-04-19 23:25:44 +00001389static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001390 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001391 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001392
1393 // Parsing the specified input file.
1394 P.ParseTranslationUnit();
1395 delete PA;
1396}
1397
1398//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001399// Code generation options
1400//===----------------------------------------------------------------------===//
1401
1402static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001403GenerateDebugInfo("g",
1404 llvm::cl::desc("Generate source level debug information"));
1405
Daniel Dunbar9101a632009-02-17 19:47:34 +00001406static llvm::cl::opt<std::string>
1407TargetCPU("mcpu",
1408 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1409
Chris Lattner8a9615c2009-03-16 18:41:18 +00001410static void InitializeCompileOptions(CompileOptions &Opts,
1411 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001412 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001413 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001414 if (OptSize) {
1415 // -Os implies -O2
1416 // FIXME: Diagnose conflicting options.
1417 Opts.OptimizationLevel = 2;
1418 } else {
1419 Opts.OptimizationLevel = OptLevel;
1420 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001421
1422 // FIXME: There are llvm-gcc options to control these selectively.
1423 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1424 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001425 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001426
1427#ifdef NDEBUG
1428 Opts.VerifyModule = 0;
1429#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001430
1431 Opts.CPU = TargetCPU;
1432 Opts.Features.insert(Opts.Features.end(),
1433 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001434
Chris Lattnerf04a7562009-03-26 05:00:52 +00001435 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1436
Chris Lattnere8f70712009-02-18 01:23:44 +00001437 // Handle -ftime-report.
1438 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001439}
1440
1441//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001442// Fix-It Options
1443//===----------------------------------------------------------------------===//
1444static llvm::cl::list<ParsedSourceLocation>
1445FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1446 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1447
1448//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001449// -dump-build-information Stuff
1450//===----------------------------------------------------------------------===//
1451
1452static llvm::cl::opt<std::string>
1453DumpBuildInformation("dump-build-information",
1454 llvm::cl::value_desc("filename"),
1455 llvm::cl::desc("output a dump of some build information to a file"));
1456
1457static llvm::raw_ostream *BuildLogFile = 0;
1458
1459/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1460/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1461namespace {
1462class LoggingDiagnosticClient : public DiagnosticClient {
1463 llvm::OwningPtr<DiagnosticClient> Chain1;
1464 llvm::OwningPtr<DiagnosticClient> Chain2;
1465public:
1466
1467 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1468 // Output diags both where requested...
1469 Chain1.reset(Normal);
1470 // .. and to our log file.
1471 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1472 !NoShowColumn,
1473 !NoCaretDiagnostics,
1474 !NoShowLocation,
1475 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001476 PrintDiagnosticOption,
1477 !NoDiagnosticsFixIt));
Chris Lattner94859302009-04-17 21:05:01 +00001478 }
1479
1480 virtual void setLangOptions(const LangOptions *LO) {
1481 Chain1->setLangOptions(LO);
1482 Chain2->setLangOptions(LO);
1483 }
1484
1485 virtual bool IncludeInDiagnosticCounts() const {
1486 return Chain1->IncludeInDiagnosticCounts();
1487 }
1488
1489 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1490 const DiagnosticInfo &Info) {
1491 Chain1->HandleDiagnostic(DiagLevel, Info);
1492 Chain2->HandleDiagnostic(DiagLevel, Info);
1493 }
1494};
1495} // end anonymous namespace.
1496
1497static void SetUpBuildDumpLog(unsigned argc, char **argv,
1498 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1499
1500 std::string ErrorInfo;
1501 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1502 ErrorInfo);
1503
1504 if (!ErrorInfo.empty()) {
1505 llvm::errs() << "error opening -dump-build-information file '"
1506 << DumpBuildInformation << "', option ignored!\n";
1507 delete BuildLogFile;
1508 BuildLogFile = 0;
1509 DumpBuildInformation = "";
1510 return;
1511 }
1512
1513 (*BuildLogFile) << "clang-cc command line arguments: ";
1514 for (unsigned i = 0; i != argc; ++i)
1515 (*BuildLogFile) << argv[i] << ' ';
1516 (*BuildLogFile) << '\n';
1517
1518 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1519 // the diagnostic producers and the normal receiver.
1520 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1521}
1522
1523
1524
1525//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001526// Main driver
1527//===----------------------------------------------------------------------===//
1528
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001529/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001530/// action. These consumers can operate on both ASTs that are freshly
1531/// parsed from source files as well as those deserialized from Bitcode.
1532/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001533static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001534 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001535 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001536 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001537 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001538 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001539 default:
1540 return NULL;
1541
1542 case ASTPrint:
1543 return CreateASTPrinter();
1544
1545 case ASTDump:
Douglas Gregord7915fd2009-04-26 02:02:08 +00001546 return CreateASTDumper(false);
1547
1548 case ASTDumpFull:
1549 return CreateASTDumper(true);
Chris Lattner7f902922009-02-18 01:20:05 +00001550
1551 case ASTView:
1552 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001553
Chris Lattner7f902922009-02-18 01:20:05 +00001554 case PrintDeclContext:
1555 return CreateDeclContextPrinter();
1556
1557 case EmitHTML:
1558 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001559
Chris Lattner7f902922009-02-18 01:20:05 +00001560 case InheritanceView:
1561 return CreateInheritanceViewer(InheritanceViewCls);
1562
Chris Lattner7f902922009-02-18 01:20:05 +00001563 case EmitAssembly:
1564 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001565 case EmitBC:
1566 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001567 BackendAction Act;
1568 if (ProgAction == EmitAssembly)
1569 Act = Backend_EmitAssembly;
1570 else if (ProgAction == EmitLLVM)
1571 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001572 else if (ProgAction == EmitLLVMOnly)
1573 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001574 else
1575 Act = Backend_EmitBC;
1576
1577 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001578 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001579 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001580 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001581 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001582
Douglas Gregorc34897d2009-04-09 22:27:44 +00001583 case GeneratePCH:
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001584 return CreatePCHGenerator(*PP, OutputFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001585
Chris Lattner7f902922009-02-18 01:20:05 +00001586 case RewriteObjC:
1587 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001588
Chris Lattner7f902922009-02-18 01:20:05 +00001589 case RewriteBlocks:
1590 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1591
1592 case RunAnalysis:
1593 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001594 }
1595}
1596
Chris Lattner4b009652007-07-25 00:24:17 +00001597/// ProcessInputFile - Process a single input file with the specified state.
1598///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001599static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001600 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001601 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001602 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001603 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00001604 bool CompleteTranslationUnit = true;
Douglas Gregor133d2552009-04-02 01:08:08 +00001605
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001606 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001607 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001608 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1609 PP.getFileManager(), PP.getLangOptions(),
1610 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001611
1612 if (!Consumer) {
1613 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001614 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001615 return;
1616 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001617
Douglas Gregore0d5c562009-04-14 16:27:31 +00001618 if (ProgAction == GeneratePCH)
1619 CompleteTranslationUnit = false;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001620 break;
1621
Chris Lattneraf669fb2008-10-12 05:03:36 +00001622 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001623 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001624 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001625 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001626 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001627 RawLex.SetKeepWhitespaceMode(true);
1628
1629 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001630 RawLex.LexFromRawLexer(RawTok);
1631 while (RawTok.isNot(tok::eof)) {
1632 PP.DumpToken(RawTok, true);
1633 fprintf(stderr, "\n");
1634 RawLex.LexFromRawLexer(RawTok);
1635 }
1636 ClearSourceMgr = true;
1637 break;
1638 }
Chris Lattner4b009652007-07-25 00:24:17 +00001639 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001640 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001641 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001642 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001643 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001644 do {
1645 PP.Lex(Tok);
1646 PP.DumpToken(Tok, true);
1647 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001648 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001649 ClearSourceMgr = true;
1650 break;
1651 }
1652 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001653 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001654 Token Tok;
1655 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001656 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001657 do {
1658 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001659 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001660 ClearSourceMgr = true;
1661 break;
1662 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001663
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001664 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001665 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001666 CacheTokens(PP, OutputFile);
1667 ClearSourceMgr = true;
1668 break;
1669 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001670
Chris Lattnerefe33382009-02-18 01:51:21 +00001671 case PrintPreprocessedInput: { // -E mode.
1672 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001673 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001674 ClearSourceMgr = true;
1675 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001676 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001677
Chris Lattnerefe33382009-02-18 01:51:21 +00001678 case ParseNoop: { // -parse-noop
1679 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001680 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001681 ClearSourceMgr = true;
1682 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001683 }
Chris Lattner4b009652007-07-25 00:24:17 +00001684
Chris Lattnerefe33382009-02-18 01:51:21 +00001685 case ParsePrintCallbacks: {
1686 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001687 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001688 ClearSourceMgr = true;
1689 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001690 }
1691
1692 case ParseSyntaxOnly: { // -fsyntax-only
1693 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001694 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001695 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001696 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001697
1698 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001699 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001700 ClearSourceMgr = true;
1701 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001702
Chris Lattnerefe33382009-02-18 01:51:21 +00001703 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001704 DoRewriteTest(PP, InFile, OutputFile);
1705 ClearSourceMgr = true;
1706 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001707 }
Douglas Gregor133d2552009-04-02 01:08:08 +00001708
1709 case FixIt:
1710 llvm::TimeRegion Timer(ClangFrontendTimer);
1711 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001712 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001713 PP.getSourceManager(),
1714 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00001715 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001716 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001717
1718 if (Consumer) {
Chris Lattner143fd6d2009-03-28 01:37:17 +00001719 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner143fd6d2009-03-28 01:37:17 +00001720
Douglas Gregor24b48b02009-04-02 19:05:20 +00001721 if (FixItAtLocations.size() > 0) {
1722 // Even without the "-fixit" flag, with may have some specific
1723 // locations where the user has requested fixes. Process those
1724 // locations now.
1725 if (!FixItRewrite)
1726 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001727 PP.getSourceManager(),
1728 PP.getLangOptions());
Douglas Gregor24b48b02009-04-02 19:05:20 +00001729
1730 bool AddedFixitLocation = false;
1731 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1732 Idx != Last; ++Idx) {
1733 RequestedSourceLocation Requested;
1734 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1735 Requested)) {
1736 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1737 FixItAtLocations[Idx].FileName.c_str());
1738 } else {
1739 FixItRewrite->addFixItLocation(Requested);
1740 AddedFixitLocation = true;
1741 }
1742 }
1743
1744 if (!AddedFixitLocation) {
1745 // All of the fix-it locations were bad. Don't fix anything.
1746 delete FixItRewrite;
1747 FixItRewrite = 0;
1748 }
1749 }
1750
Chris Lattner143fd6d2009-03-28 01:37:17 +00001751 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1752 PP.getSourceManager(),
1753 PP.getTargetInfo(),
1754 PP.getIdentifierTable(),
1755 PP.getSelectorTable(),
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001756 /* FreeMemory = */ !DisableFree,
1757 /* size_reserve = */0,
1758 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattner143fd6d2009-03-28 01:37:17 +00001759
Douglas Gregorc34897d2009-04-09 22:27:44 +00001760 if (!ImplicitIncludePCH.empty()) {
1761 // The user has asked us to include a precompiled header. Load
1762 // the precompiled header into the AST context.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001763 llvm::OwningPtr<PCHReader> Reader(new PCHReader(PP, *ContextOwner.get()));
1764 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1765 case PCHReader::Success: {
1766 // Attach the PCH reader to the AST context as an external AST
1767 // source, so that declarations will be deserialized from the
1768 // PCH file as needed.
1769 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
1770 ContextOwner->setExternalSource(Source);
1771
1772 // Clear out the predefines buffer, because all of the
1773 // predefines are already in the PCH file.
1774 PP.setPredefines("");
1775 break;
1776 }
1777
1778 case PCHReader::Failure:
1779 // Unrecoverable failure: don't even try to process the input
1780 // file.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001781 return;
1782
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001783 case PCHReader::IgnorePCH:
1784 // No suitable PCH file could be found. Just ignore the
1785 // -include-pch option entirely.
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001786
1787 // We delayed the initialization of builtins in the hope of
1788 // loading the PCH file. Since the PCH file could not be
1789 // loaded, initialize builtins now.
1790 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001791 break;
1792 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001793
1794 // Finish preprocessor initialization. We do this now (rather
1795 // than earlier) because this initialization creates new source
1796 // location entries in the source manager, which must come after
1797 // the source location entries for the PCH file.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001798 if (InitializeSourceManager(PP, InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00001799 return;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001800 }
1801
Douglas Gregore0d5c562009-04-14 16:27:31 +00001802 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
1803 CompleteTranslationUnit);
Chris Lattner143fd6d2009-03-28 01:37:17 +00001804
Douglas Gregor133d2552009-04-02 01:08:08 +00001805 if (FixItRewrite)
1806 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1807
Chris Lattner143fd6d2009-03-28 01:37:17 +00001808 // If in -disable-free mode, don't deallocate these when they go out of
1809 // scope.
Chris Lattner07b08c02009-03-28 04:13:34 +00001810 if (DisableFree)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001811 ContextOwner.take();
Ted Kremenek88eebed2009-01-28 04:29:29 +00001812 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001813
1814 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001815 if (CheckDiagnostics(PP))
1816 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001817
Chris Lattner4b009652007-07-25 00:24:17 +00001818 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001819 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001820 PP.PrintStats();
1821 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001822 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001823 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001824 fprintf(stderr, "\n");
1825 }
1826
1827 // For a multi-file compilation, some things are ok with nuking the source
1828 // manager tables, other require stable fileid/macroid's across multiple
1829 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001830 if (ClearSourceMgr)
1831 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001832
1833 if (DisableFree)
1834 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001835}
1836
1837static llvm::cl::list<std::string>
1838InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1839
Chris Lattner4b009652007-07-25 00:24:17 +00001840int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001841 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001842 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001843 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001844 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001845
Chris Lattnerefe33382009-02-18 01:51:21 +00001846 if (TimeReport)
1847 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1848
Chris Lattner4b009652007-07-25 00:24:17 +00001849 // If no input was specified, read from stdin.
1850 if (InputFilenames.empty())
1851 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001852
Ted Kremenekb240e822007-12-11 23:28:38 +00001853 // Create the diagnostic client for reporting errors or for
1854 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00001855 llvm::OwningPtr<DiagnosticClient> DiagClient;
1856 if (VerifyDiagnostics) {
1857 // When checking diagnostics, just buffer them up.
1858 DiagClient.reset(new TextDiagnosticBuffer());
1859 if (InputFilenames.size() != 1) {
1860 fprintf(stderr, "-verify only works on single input files for now.\n");
1861 return 1;
1862 }
1863 if (!HTMLDiag.empty()) {
1864 fprintf(stderr, "-verify and -html-diags don't work together\n");
1865 return 1;
1866 }
1867 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00001868 // Print diagnostics to stderr by default.
Chris Lattner5f7937d2009-04-17 20:40:01 +00001869 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00001870 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001871 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00001872 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00001873 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001874 PrintDiagnosticOption,
1875 !NoDiagnosticsFixIt));
Ted Kremenek5c341732008-08-07 17:49:57 +00001876 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00001877 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00001878 }
Chris Lattner94859302009-04-17 21:05:01 +00001879
1880 if (!DumpBuildInformation.empty()) {
1881 if (!HTMLDiag.empty()) {
1882 fprintf(stderr,
1883 "-dump-build-information and -html-diags don't work together\n");
1884 return 1;
1885 }
1886
1887 SetUpBuildDumpLog(argc, argv, DiagClient);
1888 }
1889
Ted Kremenek5c341732008-08-07 17:49:57 +00001890
Chris Lattner4b009652007-07-25 00:24:17 +00001891 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001892 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001893 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001894 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001895
Chris Lattner45a56e02007-12-05 23:24:17 +00001896 // -I- is a deprecated GCC feature, scan for it and reject it.
1897 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1898 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001899 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001900 I_dirs.erase(I_dirs.begin()+i);
1901 --i;
1902 }
1903 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001904
1905 // Get information about the target being compiled for.
1906 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001907 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1908
Chris Lattner2c77d852008-03-14 06:12:05 +00001909 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001910 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1911 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001912 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001913 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001914
Daniel Dunbar9c321102009-01-20 23:17:32 +00001915 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001916 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001917
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001918 llvm::OwningPtr<SourceManager> SourceMgr;
1919
Chris Lattnere1be6022009-04-14 23:22:57 +00001920 // Create a file manager object to provide access to and cache the filesystem.
1921 FileManager FileMgr;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001922
Chris Lattner4b009652007-07-25 00:24:17 +00001923 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001924 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001925
Chris Lattner2b989562009-03-04 21:40:56 +00001926 /// Create a SourceManager object. This tracks and owns all the file
1927 /// buffers allocated to a translation unit.
1928 if (!SourceMgr)
1929 SourceMgr.reset(new SourceManager());
1930 else
1931 SourceMgr->clearIDTables();
1932
1933 // Initialize language options, inferring file types from input filenames.
1934 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00001935 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00001936
Chris Lattner2b989562009-03-04 21:40:56 +00001937 InitializeBaseLanguage();
1938 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001939 InitializeLangOptions(LangInfo, LK);
Chris Lattner2b989562009-03-04 21:40:56 +00001940 InitializeLanguageStandard(LangInfo, LK, Target.get());
1941
1942 // Process the -I options and set them in the HeaderInfo.
1943 HeaderSearch HeaderInfo(FileMgr);
1944
Chris Lattnere1be6022009-04-14 23:22:57 +00001945
Chris Lattner2b989562009-03-04 21:40:56 +00001946 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1947
1948 // Set up the preprocessor with these options.
1949 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1950 *SourceMgr.get(), HeaderInfo);
1951
1952 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1953
1954 if (!PP)
1955 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001956
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001957 if (ImplicitIncludePCH.empty() &&
1958 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00001959 continue;
1960
Chris Lattner5f7937d2009-04-17 20:40:01 +00001961 if (!HTMLDiag.empty())
1962 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00001963
1964 // Process the source file.
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001965 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattner2b989562009-03-04 21:40:56 +00001966
Chris Lattner2961dc52009-04-17 20:16:08 +00001967 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00001968 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00001969 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001970
Mike Stump91d01352009-01-28 02:43:35 +00001971 if (Verbose)
1972 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1973 " hosted on " LLVM_HOSTTRIPLE "\n");
1974
Ted Kremenekec6c5252008-08-07 18:13:12 +00001975 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001976 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1977 (NumDiagnostics == 1 ? "" : "s"));
1978
1979 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001980 FileMgr.PrintStats();
1981 fprintf(stderr, "\n");
1982 }
Chris Lattner94859302009-04-17 21:05:01 +00001983
1984 delete ClangFrontendTimer;
1985 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00001986
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001987 // If verifying diagnostics and we reached here, all is well.
1988 if (VerifyDiagnostics)
1989 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001990
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001991 // Managed static deconstruction. Useful for making things like
1992 // -time-passes usable.
1993 llvm::llvm_shutdown();
1994
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001995 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001996}