blob: 258076836a8e2924cc5c0c9435fe25f345a97d1e [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"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000031#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000032#include "clang/Frontend/PCHReader.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000033#include "clang/Frontend/TextDiagnosticBuffer.h"
34#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000035#include "clang/Analysis/PathDiagnostic.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000036#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000037#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000038#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000039#include "clang/AST/ASTConsumer.h"
Chris Lattnerfc318192009-03-28 04:31:31 +000040#include "clang/AST/ASTContext.h"
41#include "clang/AST/Decl.h"
Chris Lattnera17991f2009-03-29 16:50:03 +000042#include "clang/AST/DeclGroup.h"
Chris Lattner4b009652007-07-25 00:24:17 +000043#include "clang/Parse/Parser.h"
44#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000045#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000046#include "clang/Basic/FileManager.h"
47#include "clang/Basic/SourceManager.h"
48#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000049#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000050#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000051#include "llvm/ADT/StringExtras.h"
Chris Lattner0e004a12009-04-08 18:24:34 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000053#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000054#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000055#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000056#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000057#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000058#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000059#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000060#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000061#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000062#include "llvm/System/Signals.h"
Douglas Gregor24b48b02009-04-02 19:05:20 +000063#include <cstdlib>
64
Chris Lattner4b009652007-07-25 00:24:17 +000065using namespace clang;
66
67//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000068// Source Location Parser
69//===----------------------------------------------------------------------===//
70
71/// \brief A source location that has been parsed on the command line.
72struct ParsedSourceLocation {
73 std::string FileName;
74 unsigned Line;
75 unsigned Column;
76
77 /// \brief Try to resolve the file name of a parsed source location.
78 ///
79 /// \returns true if there was an error, false otherwise.
80 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
81};
82
83bool
84ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
85 RequestedSourceLocation &Result) {
86 const FileEntry *File = FileMgr.getFile(FileName);
87 if (!File)
88 return true;
89
90 Result.File = File;
91 Result.Line = Line;
92 Result.Column = Column;
93 return false;
94}
95
96namespace llvm {
97 namespace cl {
98 /// \brief Command-line option parser that parses source locations.
99 ///
100 /// Source locations are of the form filename:line:column.
101 template<>
102 class parser<ParsedSourceLocation>
103 : public basic_parser<ParsedSourceLocation> {
104 public:
105 bool parse(Option &O, const char *ArgName,
106 const std::string &ArgValue,
107 ParsedSourceLocation &Val);
108 };
109
110 bool
111 parser<ParsedSourceLocation>::
112 parse(Option &O, const char *ArgName, const std::string &ArgValue,
113 ParsedSourceLocation &Val) {
114 using namespace clang;
115
116 const char *ExpectedFormat
117 = "source location must be of the form filename:line:column";
118 std::string::size_type SecondColon = ArgValue.rfind(':');
119 if (SecondColon == std::string::npos) {
120 std::fprintf(stderr, "%s\n", ExpectedFormat);
121 return true;
122 }
123 char *EndPtr;
124 long Column
125 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
126 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
127 std::fprintf(stderr, "%s\n", ExpectedFormat);
128 return true;
129 }
130
131 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
132 if (SecondColon == std::string::npos) {
133 std::fprintf(stderr, "%s\n", ExpectedFormat);
134 return true;
135 }
136 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
137 if (EndPtr != ArgValue.c_str() + SecondColon) {
138 std::fprintf(stderr, "%s\n", ExpectedFormat);
139 return true;
140 }
141
142 Val.FileName = ArgValue.substr(0, FirstColon);
143 Val.Line = Line;
144 Val.Column = Column;
145 return false;
146 }
147 }
148}
149
150//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000151// Global options.
152//===----------------------------------------------------------------------===//
153
Chris Lattnerefe33382009-02-18 01:51:21 +0000154/// ClangFrontendTimer - The front-end activities should charge time to it with
155/// TimeRegion. The -ftime-report option controls whether this will do
156/// anything.
157llvm::Timer *ClangFrontendTimer = 0;
158
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000159static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000160
Chris Lattner4b009652007-07-25 00:24:17 +0000161static llvm::cl::opt<bool>
162Verbose("v", llvm::cl::desc("Enable verbose output"));
163static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000164Stats("print-stats",
165 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000166static llvm::cl::opt<bool>
167DisableFree("disable-free",
168 llvm::cl::desc("Disable freeing of memory on exit"),
169 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +0000170
171enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000172 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000173 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000174 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000175 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000176 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000177 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000178 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000179 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000180 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000181 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek397de012007-12-13 00:37:31 +0000182 SerializeAST, // Emit a .ast file.
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.
186 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000187 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000188 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +0000189 ParsePrintCallbacks, // Parse and print each callback.
190 ParseSyntaxOnly, // Parse and perform semantic analysis.
191 ParseNoop, // Parse with noop callbacks.
192 RunPreprocessorOnly, // Just lex, no output.
193 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000194 DumpTokens, // Dump out preprocessed tokens.
195 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000196 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000197 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000198 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000199 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000200};
201
202static llvm::cl::opt<ProgActions>
203ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
204 llvm::cl::init(ParseSyntaxOnly),
205 llvm::cl::values(
206 clEnumValN(RunPreprocessorOnly, "Eonly",
207 "Just run preprocessor, no output (for timings)"),
208 clEnumValN(PrintPreprocessedInput, "E",
209 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000210 clEnumValN(DumpRawTokens, "dump-raw-tokens",
211 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000212 clEnumValN(RunAnalysis, "analyze",
213 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000214 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000215 "Run preprocessor, dump internal rep of tokens"),
216 clEnumValN(ParseNoop, "parse-noop",
217 "Run parser with noop callbacks (for timings)"),
218 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
219 "Run parser and perform semantic analysis"),
220 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
221 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000222 clEnumValN(EmitHTML, "emit-html",
223 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000224 clEnumValN(ASTPrint, "ast-print",
225 "Build ASTs and then pretty-print them"),
226 clEnumValN(ASTDump, "ast-dump",
227 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000228 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000229 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000230 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000231 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000232 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000233 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000234 clEnumValN(GeneratePCH, "emit-pch",
235 "Generate pre-compiled header file"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000236 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000237 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000238 clEnumValN(EmitAssembly, "S",
239 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000240 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000241 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000242 clEnumValN(EmitBC, "emit-llvm-bc",
243 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000244 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
245 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000246 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000247 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000248 clEnumValN(RewriteTest, "rewrite-test",
249 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000250 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000251 "Rewrite ObjC into C (code rewriter example)"),
252 clEnumValN(RewriteMacros, "rewrite-macros",
253 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000254 clEnumValN(RewriteBlocks, "rewrite-blocks",
255 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000256 clEnumValN(FixIt, "fixit",
257 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000258 clEnumValEnd));
259
Ted Kremenekd01eae62007-12-19 19:47:59 +0000260
261static llvm::cl::opt<std::string>
262OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000263 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000264 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000265
Ted Kremenek57f25b22008-12-02 19:57:31 +0000266
267//===----------------------------------------------------------------------===//
268// PTH.
269//===----------------------------------------------------------------------===//
270
271static llvm::cl::opt<std::string>
272TokenCache("token-cache", llvm::cl::value_desc("path"),
273 llvm::cl::desc("Use specified token cache file"));
274
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000275//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000276// Diagnostic Options
277//===----------------------------------------------------------------------===//
278
Ted Kremenek10389cf2007-09-26 19:42:19 +0000279static llvm::cl::opt<bool>
280VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000281 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000282
Ted Kremenekfd75e312008-03-27 06:17:42 +0000283static llvm::cl::opt<std::string>
284HTMLDiag("html-diags",
285 llvm::cl::desc("Generate HTML to report diagnostics"),
286 llvm::cl::value_desc("HTML directory"));
287
Nico Weber0e13eaa2008-08-05 23:33:20 +0000288static llvm::cl::opt<bool>
289NoShowColumn("fno-show-column",
290 llvm::cl::desc("Do not include column number on diagnostics"));
291
292static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000293NoShowLocation("fno-show-source-location",
294 llvm::cl::desc("Do not include source location information with"
295 " diagnostics"));
296
297static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000298NoCaretDiagnostics("fno-caret-diagnostics",
299 llvm::cl::desc("Do not include source line and caret with"
300 " diagnostics"));
301
Chris Lattner695a4f52009-03-13 01:08:23 +0000302static llvm::cl::opt<bool>
303PrintSourceRangeInfo("fprint-source-range-info",
304 llvm::cl::desc("Print source range spans in numeric form"));
305
Nico Weber0e13eaa2008-08-05 23:33:20 +0000306
Chris Lattner4b009652007-07-25 00:24:17 +0000307//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000308// C++ Visualization.
309//===----------------------------------------------------------------------===//
310
311static llvm::cl::opt<std::string>
312InheritanceViewCls("cxx-inheritance-view",
313 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000314 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000315
316//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000317// Builtin Options
318//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000319
320static llvm::cl::opt<bool>
321TimeReport("ftime-report",
322 llvm::cl::desc("Print the amount of time each "
323 "phase of compilation takes"));
324
Douglas Gregor23d23262009-02-14 20:49:29 +0000325static llvm::cl::opt<bool>
326Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000327 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000328 "freestanding environment"));
329
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000330static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000331AllowBuiltins("fbuiltin", llvm::cl::init(true),
332 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000333
334
335static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000336MathErrno("fmath-errno", llvm::cl::init(true),
337 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000338
Douglas Gregor23d23262009-02-14 20:49:29 +0000339//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000340// Language Options
341//===----------------------------------------------------------------------===//
342
343enum LangKind {
344 langkind_unspecified,
345 langkind_c,
346 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000347 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000348 langkind_cxx,
349 langkind_cxx_cpp,
350 langkind_objc,
351 langkind_objc_cpp,
352 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000353 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000354};
355
Chris Lattner4b009652007-07-25 00:24:17 +0000356static llvm::cl::opt<LangKind>
357BaseLang("x", llvm::cl::desc("Base language to compile"),
358 llvm::cl::init(langkind_unspecified),
359 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
360 clEnumValN(langkind_cxx, "c++", "C++"),
361 clEnumValN(langkind_objc, "objective-c", "Objective C"),
362 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000363 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000364 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000365 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
366 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000367 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000368 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000369 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
370 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000371 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000372 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000373 clEnumValN(langkind_c, "c-header",
374 "C header"),
375 clEnumValN(langkind_objc, "objective-c-header",
376 "Objective-C header"),
377 clEnumValN(langkind_cxx, "c++-header",
378 "C++ header"),
379 clEnumValN(langkind_objcxx, "objective-c++-header",
380 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000381 clEnumValEnd));
382
383static llvm::cl::opt<bool>
384LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
385 llvm::cl::Hidden);
386static llvm::cl::opt<bool>
387LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
388 llvm::cl::Hidden);
389
Ted Kremenek11ad8952007-12-05 23:49:08 +0000390/// InitializeBaseLanguage - Handle the -x foo options.
391static void InitializeBaseLanguage() {
392 if (LangObjC)
393 BaseLang = langkind_objc;
394 else if (LangObjCXX)
395 BaseLang = langkind_objcxx;
396}
397
398static LangKind GetLanguage(const std::string &Filename) {
399 if (BaseLang != langkind_unspecified)
400 return BaseLang;
401
402 std::string::size_type DotPos = Filename.rfind('.');
403
404 if (DotPos == std::string::npos) {
405 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000406 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000407 }
408
Ted Kremenek11ad8952007-12-05 23:49:08 +0000409 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
410 // C header: .h
411 // C++ header: .hh or .H;
412 // assembler no preprocessing: .s
413 // assembler: .S
414 if (Ext == "c")
415 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000416 else if (Ext == "S" ||
417 // If the compiler is run on a .s file, preprocess it as .S
418 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000419 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000420 else if (Ext == "i")
421 return langkind_c_cpp;
422 else if (Ext == "ii")
423 return langkind_cxx_cpp;
424 else if (Ext == "m")
425 return langkind_objc;
426 else if (Ext == "mi")
427 return langkind_objc_cpp;
428 else if (Ext == "mm" || Ext == "M")
429 return langkind_objcxx;
430 else if (Ext == "mii")
431 return langkind_objcxx_cpp;
432 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
433 Ext == "c++" || Ext == "cp" || Ext == "cxx")
434 return langkind_cxx;
435 else
436 return langkind_c;
437}
438
439
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000440static void InitializeCOptions(LangOptions &Options) {
441 // Do nothing.
442}
443
444static void InitializeObjCOptions(LangOptions &Options) {
445 Options.ObjC1 = Options.ObjC2 = 1;
446}
447
448
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000449static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000450 // FIXME: implement -fpreprocessed mode.
451 bool NoPreprocess = false;
452
Ted Kremenek11ad8952007-12-05 23:49:08 +0000453 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000454 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000455 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000456 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000457 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000458 case langkind_c_cpp:
459 NoPreprocess = true;
460 // FALLTHROUGH
461 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000462 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000463 break;
464 case langkind_cxx_cpp:
465 NoPreprocess = true;
466 // FALLTHROUGH
467 case langkind_cxx:
468 Options.CPlusPlus = 1;
469 break;
470 case langkind_objc_cpp:
471 NoPreprocess = true;
472 // FALLTHROUGH
473 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000474 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000475 break;
476 case langkind_objcxx_cpp:
477 NoPreprocess = true;
478 // FALLTHROUGH
479 case langkind_objcxx:
480 Options.ObjC1 = Options.ObjC2 = 1;
481 Options.CPlusPlus = 1;
482 break;
483 }
484}
485
486/// LangStds - Language standards we support.
487enum LangStds {
488 lang_unspecified,
489 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000490 lang_gnu_START,
491 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000492 lang_cxx98, lang_gnucxx98,
493 lang_cxx0x, lang_gnucxx0x
494};
495
496static llvm::cl::opt<LangStds>
497LangStd("std", llvm::cl::desc("Language standard to compile for"),
498 llvm::cl::init(lang_unspecified),
499 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
500 clEnumValN(lang_c89, "c90", "ISO C 1990"),
501 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
502 clEnumValN(lang_c94, "iso9899:199409",
503 "ISO C 1990 with amendment 1"),
504 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000505 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000506 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000507 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000508 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000509 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000510 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000511 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000512 clEnumValN(lang_gnu99, "gnu9x",
513 "ISO C 1999 with GNU extensions"),
514 clEnumValN(lang_cxx98, "c++98",
515 "ISO C++ 1998 with amendments"),
516 clEnumValN(lang_gnucxx98, "gnu++98",
517 "ISO C++ 1998 with amendments and GNU "
518 "extensions (default for C++)"),
519 clEnumValN(lang_cxx0x, "c++0x",
520 "Upcoming ISO C++ 200x with amendments"),
521 clEnumValN(lang_gnucxx0x, "gnu++0x",
522 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000523 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000524 clEnumValEnd));
525
526static llvm::cl::opt<bool>
527NoOperatorNames("fno-operator-names",
528 llvm::cl::desc("Do not treat C++ operator name keywords as "
529 "synonyms for operators"));
530
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000531static llvm::cl::opt<bool>
532PascalStrings("fpascal-strings",
533 llvm::cl::desc("Recognize and construct Pascal-style "
534 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000535
536static llvm::cl::opt<bool>
537MSExtensions("fms-extensions",
538 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000539 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000540
541static llvm::cl::opt<bool>
542WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000543 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000544
545static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000546NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000547 llvm::cl::desc("Disallow implicit conversions between "
548 "vectors with a different number of "
549 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000550
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000551static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000552EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000553
554static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000555EnableHeinousExtensions("fheinous-gnu-extensions",
556 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
557 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
558
559static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000560ObjCNonFragileABI("fobjc-nonfragile-abi",
561 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000562
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000563static llvm::cl::opt<bool>
564EmitAllDecls("femit-all-decls",
565 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000566
Daniel Dunbar91692d92008-08-11 17:36:14 +0000567// FIXME: This (and all GCC -f options) really come in -f... and
568// -fno-... forms, and additionally support automagic behavior when
569// they are not defined. For example, -fexceptions defaults to on or
570// off depending on the language. We should support this behavior in
571// some form (perhaps just add a facility for distinguishing when an
572// has its default value from when it has been set to its default
573// value).
574static llvm::cl::opt<bool>
575Exceptions("fexceptions",
576 llvm::cl::desc("Enable support for exception handling."));
577
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000578static llvm::cl::opt<bool>
579GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000580 llvm::cl::desc("Generate output compatible with the standard GNU "
581 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000582
583static llvm::cl::opt<bool>
584NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000585 llvm::cl::desc("Generate output compatible with the NeXT "
586 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000587
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000588
589
590static llvm::cl::opt<bool>
591Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
592
Chris Lattner738d3f62009-03-02 22:11:07 +0000593static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000594TargetFeatures("mattr", llvm::cl::CommaSeparated,
595 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
596
Douglas Gregor375733c2009-03-10 00:06:19 +0000597static llvm::cl::opt<unsigned>
598TemplateDepth("ftemplate-depth", llvm::cl::init(99),
599 llvm::cl::desc("Maximum depth of recursive template "
600 "instantiation"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000601
Anders Carlssondfd77642009-04-06 17:37:10 +0000602
603static llvm::cl::opt<bool>
604OptSize("Os", llvm::cl::desc("Optimize for size"));
605
606static llvm::cl::opt<bool>
607NoCommon("fno-common",
608 llvm::cl::desc("Compile common globals like normal definitions"),
609 llvm::cl::ValueDisallowed);
610
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000611static llvm::cl::opt<std::string>
612MainFileName("main-file-name",
613 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000614
615// It might be nice to add bounds to the CommandLine library directly.
616struct OptLevelParser : public llvm::cl::parser<unsigned> {
617 bool parse(llvm::cl::Option &O, const char *ArgName,
618 const std::string &Arg, unsigned &Val) {
619 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
620 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000621 if (Val > 3)
622 return O.error(": '" + Arg + "' invalid optimization level!");
623 return false;
624 }
625};
626static llvm::cl::opt<unsigned, false, OptLevelParser>
627OptLevel("O", llvm::cl::Prefix,
628 llvm::cl::desc("Optimization level"),
629 llvm::cl::init(0));
630
Daniel Dunbare079c712009-04-08 03:03:23 +0000631static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000632PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
633
634static llvm::cl::opt<bool>
635StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000636
Chris Lattner4b009652007-07-25 00:24:17 +0000637// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000638// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000639static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
640 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000641 // Allow the target to set the default the langauge options as it sees fit.
642 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000643
Chris Lattnerf6790a82009-03-03 19:56:18 +0000644 // If there are any -mattr options, pass them to the target for validation and
645 // processing. The driver should have already consolidated all the
646 // target-feature settings and passed them to us in the -mattr list. The
647 // -mattr list is treated by the code generator as a diff against the -mcpu
648 // setting, but the driver should pass all enabled options as "+" settings.
649 // This means that the target should only look at + settings.
650 if (!TargetFeatures.empty()
651 // FIXME: The driver is not quite yet ready for this.
652 && 0) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000653 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000654 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
655 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000656 if (Opt != -1) {
657 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000658 fprintf(stderr, "invalid feature '%s'\n",
659 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000660 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000661 fprintf(stderr, "feature '%s': %s\n",
662 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000663 exit(1);
664 }
665 }
666
Chris Lattner4b009652007-07-25 00:24:17 +0000667 if (LangStd == lang_unspecified) {
668 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000669 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000670 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000671 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000672 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000673 case langkind_c_cpp:
674 case langkind_objc:
675 case langkind_objc_cpp:
676 LangStd = lang_gnu99;
677 break;
678 case langkind_cxx:
679 case langkind_cxx_cpp:
680 case langkind_objcxx:
681 case langkind_objcxx_cpp:
682 LangStd = lang_gnucxx98;
683 break;
684 }
685 }
686
687 switch (LangStd) {
688 default: assert(0 && "Unknown language standard!");
689
690 // Fall through from newer standards to older ones. This isn't really right.
691 // FIXME: Enable specifically the right features based on the language stds.
692 case lang_gnucxx0x:
693 case lang_cxx0x:
694 Options.CPlusPlus0x = 1;
695 // FALL THROUGH
696 case lang_gnucxx98:
697 case lang_cxx98:
698 Options.CPlusPlus = 1;
699 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000700 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000701 // FALL THROUGH.
702 case lang_gnu99:
703 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000704 Options.C99 = 1;
705 Options.HexFloats = 1;
706 // FALL THROUGH.
707 case lang_gnu89:
708 Options.BCPLComment = 1; // Only for C99/C++.
709 // FALL THROUGH.
710 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000711 Options.Digraphs = 1; // C94, C99, C++.
712 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000713 case lang_c89:
714 break;
715 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000716
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000717 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
718 Options.GNUMode = LangStd >= lang_gnu_START;
719
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000720 if (Options.CPlusPlus) {
721 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000722 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000723 }
Chris Lattner4b009652007-07-25 00:24:17 +0000724
Chris Lattner6ab935b2008-04-05 06:32:51 +0000725 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
726 Options.ImplicitInt = 1;
727 else
728 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000729
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000730 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
731 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000732 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000733 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000734 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000735
Chris Lattner58d5ba52008-12-05 00:10:44 +0000736 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
737 // even if they are normally on for the target. In GNU modes (e.g.
738 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000739 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000740 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000741 Options.Blocks = 0;
742
Daniel Dunbar551236b2009-03-15 00:11:28 +0000743 // Never accept '$' in identifiers when preprocessing assembler.
744 if (LK != langkind_asm_cpp)
745 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000746 if (PascalStrings.getPosition())
747 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000748 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000749 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000750 if (NoLaxVectorConversions.getPosition())
751 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000752 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000753 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000754 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000755
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000756 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000757 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000758 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000759 Options.Freestanding = Options.NoBuiltin = 1;
760
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000761 if (EnableHeinousExtensions)
762 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000763
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000764 Options.MathErrno = MathErrno;
765
Douglas Gregor375733c2009-03-10 00:06:19 +0000766 Options.InstantiationDepth = TemplateDepth;
767
Chris Lattnerddae7102008-12-04 22:54:33 +0000768 // Override the default runtime if the user requested it.
769 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000770 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000771 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000772 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000773
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000774 if (ObjCNonFragileABI)
775 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000776
777 if (EmitAllDecls)
778 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000779
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000780 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
781 // support.
782 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000783
784 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000785 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000786 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000787
788 assert(PICLevel <= 2 && "Invalid value for -pic-level");
789 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000790
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000791 Options.GNUInline = !Options.C99;
792 // FIXME: This is affected by other options (-fno-inline).
793 Options.NoInline = !OptSize && !OptLevel;
794
795 Options.Static = StaticDefine;
796
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000797 if (MainFileName.getPosition())
798 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000799}
800
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000801static llvm::cl::opt<bool>
802ObjCExclusiveGC("fobjc-gc-only",
803 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000804 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000805
806static llvm::cl::opt<bool>
807ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000808 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000809
810void InitializeGCMode(LangOptions &Options) {
811 if (ObjCExclusiveGC)
812 Options.setGCMode(LangOptions::GCOnly);
813 else if (ObjCEnableGC)
814 Options.setGCMode(LangOptions::HybridGC);
815}
816
Fariborz Jahanian49343332009-04-03 03:28:57 +0000817static llvm::cl::opt<std::string>
818SymbolVisibility("fvisibility",
819 llvm::cl::desc("Set the default visibility to the specific option"));
820
821void InitializeSymbolVisibility(LangOptions &Options) {
822 if (SymbolVisibility.empty())
823 return;
824 std::string Visibility = SymbolVisibility;
825 const char *vkind = Visibility.c_str();
826 if (!strcmp(vkind, "default"))
827 Options.setVisibilityMode(LangOptions::DefaultVisibility);
828 else if (!strcmp(vkind, "protected"))
829 Options.setVisibilityMode(LangOptions::ProtectedVisibility);
830 else if (!strcmp(vkind, "hidden"))
831 Options.setVisibilityMode(LangOptions::HiddenVisibility);
832 else if (!strcmp(vkind, "internal"))
833 Options.setVisibilityMode(LangOptions::InternalVisibility);
834 else
835 fprintf(stderr,
836 "-fvisibility only valid for default|protected|hidden|internal\n");
837}
838
Mike Stumpdb789912009-04-01 20:28:16 +0000839static llvm::cl::opt<bool>
840OverflowChecking("ftrapv",
Mike Stumpf71b7742009-04-02 18:15:54 +0000841 llvm::cl::desc("Trap on integer overflow"),
Mike Stumpdb789912009-04-01 20:28:16 +0000842 llvm::cl::init(false));
843
844void InitializeOverflowChecking(LangOptions &Options) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000845 Options.OverflowChecking = OverflowChecking;
Mike Stumpdb789912009-04-01 20:28:16 +0000846}
Chris Lattner4b009652007-07-25 00:24:17 +0000847//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000848// Target Triple Processing.
849//===----------------------------------------------------------------------===//
850
851static llvm::cl::opt<std::string>
852TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000853 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000854
Chris Lattnerfc457002008-03-05 01:18:20 +0000855static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000856Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000857
Chris Lattner2b168e02008-09-30 01:13:12 +0000858static llvm::cl::opt<std::string>
859MacOSVersionMin("mmacosx-version-min",
860 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
861
Chris Lattner01de9c82008-09-30 20:16:56 +0000862// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
863// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000864
865// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000866static void HandleMacOSVersionMin(std::string &Triple) {
867 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
868 if (DarwinDashIdx == std::string::npos) {
869 fprintf(stderr,
870 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
871 exit(1);
872 }
873 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
874
Chris Lattner01de9c82008-09-30 20:16:56 +0000875 // Remove the number.
876 Triple.resize(DarwinNumIdx);
877
878 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
879 bool MacOSVersionMinIsInvalid = false;
880 int VersionNum = 0;
881 if (MacOSVersionMin.size() < 4 ||
882 MacOSVersionMin.substr(0, 3) != "10." ||
883 !isdigit(MacOSVersionMin[3])) {
884 MacOSVersionMinIsInvalid = true;
885 } else {
886 const char *Start = MacOSVersionMin.c_str()+3;
887 char *End = 0;
888 VersionNum = (int)strtol(Start, &End, 10);
889
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000890 // The version number must be in the range 0-9.
891 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
892
Chris Lattner01de9c82008-09-30 20:16:56 +0000893 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
894 Triple += llvm::itostr(VersionNum+4);
895
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000896 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
897 // Add the period piece (.7) to the end of the triple. This gives us
898 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000899 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000900 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
901 MacOSVersionMinIsInvalid = true;
902 }
903 }
904
905 if (MacOSVersionMinIsInvalid) {
906 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000907 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000908 MacOSVersionMin.c_str());
909 exit(1);
910 }
911}
912
913/// CreateTargetTriple - Process the various options that affect the target
914/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000915static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000916 // Initialize base triple. If a -triple option has been specified, use
917 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000918 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000919 if (Triple.empty())
920 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000921
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000922 // If -arch foo was specified, remove the architecture from the triple we have
923 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000924
925 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +0000926 if (!Arch.empty()) {
927 // Decompose the base triple into "arch" and suffix.
928 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000929
Chris Lattner2b168e02008-09-30 01:13:12 +0000930 if (FirstDashIdx == std::string::npos) {
931 fprintf(stderr,
932 "Malformed target triple: \"%s\" ('-' could not be found).\n",
933 Triple.c_str());
934 exit(1);
935 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +0000936
937 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
938 if (Arch == "ppc")
939 Arch = "powerpc";
940 else if (Arch == "ppc64")
941 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +0000942
Chris Lattner2b168e02008-09-30 01:13:12 +0000943 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
944 }
945
946 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
947 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000948 if (!MacOSVersionMin.empty())
949 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000950
Chris Lattner2b168e02008-09-30 01:13:12 +0000951 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000952}
953
954//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000955// Preprocessor Initialization
956//===----------------------------------------------------------------------===//
957
958// FIXME: Preprocessor builtins to support.
959// -A... - Play with #assertions
960// -undef - Undefine all predefined macros
961
Chris Lattner695a4f52009-03-13 01:08:23 +0000962// FIXME: -imacros
963
Chris Lattner4b009652007-07-25 00:24:17 +0000964static llvm::cl::list<std::string>
965D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
966 llvm::cl::desc("Predefine the specified macro"));
967static llvm::cl::list<std::string>
968U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
969 llvm::cl::desc("Undefine the specified macro"));
970
Chris Lattner008da782008-01-10 01:53:41 +0000971static llvm::cl::list<std::string>
972ImplicitIncludes("include", llvm::cl::value_desc("file"),
973 llvm::cl::desc("Include file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +0000974static llvm::cl::list<std::string>
975ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
976 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner008da782008-01-10 01:53:41 +0000977
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000978static llvm::cl::opt<std::string>
979ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
980 llvm::cl::desc("Include file before parsing"));
981
Douglas Gregorc34897d2009-04-09 22:27:44 +0000982static llvm::cl::opt<std::string>
983ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
984 llvm::cl::desc("Include precompiled header file"));
985
Chris Lattner4b009652007-07-25 00:24:17 +0000986// Append a #define line to Buf for Macro. Macro should be of the form XXX,
987// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
988// "#define XXX Y z W". To get a #define with no value, use "XXX=".
989static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
990 const char *Command = "#define ") {
991 Buf.insert(Buf.end(), Command, Command+strlen(Command));
992 if (const char *Equal = strchr(Macro, '=')) {
993 // Turn the = into ' '.
994 Buf.insert(Buf.end(), Macro, Equal);
995 Buf.push_back(' ');
Chris Lattner39baafb2009-04-07 06:02:44 +0000996
997 // Per GCC -D semantics, the macro ends at \n if it exists.
998 const char *End = strpbrk(Equal, "\n\r");
Chris Lattner39c610d2009-04-07 18:18:09 +0000999 if (End) {
Chris Lattnerd93f7902009-04-08 03:36:03 +00001000 fprintf(stderr, "warning: macro '%s' contains embedded newline, text "
Chris Lattner39c610d2009-04-07 18:18:09 +00001001 "after the newline is ignored.\n",
1002 std::string(Macro, Equal).c_str());
1003 } else {
1004 End = Equal+strlen(Equal);
1005 }
Chris Lattner39baafb2009-04-07 06:02:44 +00001006
1007 Buf.insert(Buf.end(), Equal+1, End);
Chris Lattner4b009652007-07-25 00:24:17 +00001008 } else {
1009 // Push "macroname 1".
1010 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
1011 Buf.push_back(' ');
1012 Buf.push_back('1');
1013 }
1014 Buf.push_back('\n');
1015}
1016
Daniel Dunbar43b91692009-04-09 00:51:16 +00001017/// Add the quoted name of an implicit include file.
1018static void AddQuotedIncludePath(std::vector<char> &Buf,
1019 const std::string &File) {
1020 // Implicit include paths are relative to the current working
1021 // directory; resolve them now instead of using the normal machinery
1022 // (which would look relative to the input file).
1023 llvm::sys::Path Path(File);
1024 Path.makeAbsolute();
1025
Chris Lattner6ac92a32009-04-08 20:10:57 +00001026 // Escape double quotes etc.
Daniel Dunbar43b91692009-04-09 00:51:16 +00001027 Buf.push_back('"');
1028 std::string EscapedFile = Lexer::Stringify(Path.toString());
Chris Lattner6ac92a32009-04-08 20:10:57 +00001029 Buf.insert(Buf.end(), EscapedFile.begin(), EscapedFile.end());
Chris Lattner008da782008-01-10 01:53:41 +00001030 Buf.push_back('"');
Daniel Dunbar43b91692009-04-09 00:51:16 +00001031}
1032
1033/// AddImplicitInclude - Add an implicit #include of the specified file to the
1034/// predefines buffer.
1035static void AddImplicitInclude(std::vector<char> &Buf,
1036 const std::string &File) {
1037 const char *Inc = "#include ";
1038 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
1039 AddQuotedIncludePath(Buf, File);
Chris Lattner008da782008-01-10 01:53:41 +00001040 Buf.push_back('\n');
1041}
1042
Chris Lattner0e004a12009-04-08 18:24:34 +00001043static void AddImplicitIncludeMacros(std::vector<char> &Buf,
1044 const std::string &File) {
Daniel Dunbar43b91692009-04-09 00:51:16 +00001045 const char *Inc = "#__include_macros ";
Chris Lattner0e004a12009-04-08 18:24:34 +00001046 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
Daniel Dunbar43b91692009-04-09 00:51:16 +00001047 AddQuotedIncludePath(Buf, File);
Chris Lattner0e004a12009-04-08 18:24:34 +00001048 Buf.push_back('\n');
Chris Lattnera6e44112009-04-08 20:53:24 +00001049 // Marker token to stop the __include_macros fetch loop.
1050 const char *Marker = "##\n"; // ##?
1051 Buf.insert(Buf.end(), Marker, Marker+strlen(Marker));
Chris Lattner0e004a12009-04-08 18:24:34 +00001052}
1053
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001054/// AddImplicitIncludePTH - Add an implicit #include using the original file
1055/// used to generate a PTH cache.
Chris Lattner0e004a12009-04-08 18:24:34 +00001056static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor &PP) {
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001057 PTHManager *P = PP.getPTHManager();
1058 assert(P && "No PTHManager.");
1059 const char *OriginalFile = P->getOriginalSourceFile();
1060
1061 if (!OriginalFile) {
1062 assert(!ImplicitIncludePTH.empty());
1063 fprintf(stderr, "error: PTH file '%s' does not designate an original "
1064 "source header file for -include-pth\n",
1065 ImplicitIncludePTH.c_str());
1066 exit (1);
1067 }
1068
1069 AddImplicitInclude(Buf, OriginalFile);
1070}
Chris Lattner4b009652007-07-25 00:24:17 +00001071
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001072/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +00001073/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001074///
Chris Lattner9d818a22008-04-19 23:25:44 +00001075static bool InitializePreprocessor(Preprocessor &PP,
1076 bool InitializeSourceMgr,
1077 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +00001078 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +00001079
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001080 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +00001081 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001082
1083 if (InitializeSourceMgr) {
1084 if (InFile != "-") {
1085 const FileEntry *File = FileMgr.getFile(InFile);
1086 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +00001087 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001088 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1089 << InFile.c_str();
Chris Lattner9d818a22008-04-19 23:25:44 +00001090 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001091 }
1092 } else {
1093 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar99617162009-03-21 17:56:30 +00001094
1095 // If stdin was empty, SB is null. Cons up an empty memory
1096 // buffer now.
1097 if (!SB) {
1098 const char *EmptyStr = "";
1099 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1100 }
1101
1102 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +00001103 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001104 PP.getDiagnostics().Report(FullSourceLoc(),
1105 diag::err_fe_error_reading_stdin);
Chris Lattner9d818a22008-04-19 23:25:44 +00001106 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001107 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001108 }
Chris Lattner4b009652007-07-25 00:24:17 +00001109 }
Sam Bishop61a20782008-04-14 14:41:57 +00001110
Chris Lattner47b6a162008-04-19 23:09:31 +00001111 std::vector<char> PredefineBuffer;
1112
Chris Lattner4b009652007-07-25 00:24:17 +00001113 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +00001114 unsigned d = 0, D = D_macros.size();
1115 unsigned u = 0, U = U_macros.size();
1116 while (d < D || u < U) {
1117 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1118 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
1119 else
1120 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
1121 }
1122
Chris Lattnerb62396d2009-04-08 20:15:42 +00001123 // If -imacros are specified, include them now. These are processed before
1124 // any -include directives.
1125
1126 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1127 AddImplicitIncludeMacros(PredefineBuffer, ImplicitMacroIncludes[i]);
Chris Lattner008da782008-01-10 01:53:41 +00001128
Chris Lattnerb62396d2009-04-08 20:15:42 +00001129 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) {
1130 // We want to add these paths to the predefines buffer in order, make a
1131 // temporary vector to sort by their occurrence.
Chris Lattner0e004a12009-04-08 18:24:34 +00001132 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1133
1134 if (!ImplicitIncludePTH.empty())
1135 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1136 &ImplicitIncludePTH));
1137 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1138 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1139 &ImplicitIncludes[i]));
Chris Lattner0e004a12009-04-08 18:24:34 +00001140 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1141
1142 // Now that they are ordered by position, add to the predefines buffer.
1143 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1144 std::string *Ptr = OrderedPaths[i].second;
1145 if (!ImplicitIncludes.empty() &&
1146 Ptr >= &ImplicitIncludes[0] &&
1147 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1148 AddImplicitInclude(PredefineBuffer, *Ptr);
Chris Lattner0e004a12009-04-08 18:24:34 +00001149 } else {
Chris Lattnerb62396d2009-04-08 20:15:42 +00001150 assert(Ptr == &ImplicitIncludePTH);
1151 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner0e004a12009-04-08 18:24:34 +00001152 }
1153 }
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001154 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001155
Chris Lattner47b6a162008-04-19 23:09:31 +00001156 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001157 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +00001158 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001159
1160 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +00001161 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001162}
1163
1164//===----------------------------------------------------------------------===//
1165// Preprocessor include path information.
1166//===----------------------------------------------------------------------===//
1167
1168// This tool exports a large number of command line options to control how the
1169// preprocessor searches for header files. At root, however, the Preprocessor
1170// object takes a very simple interface: a list of directories to search for
1171//
1172// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001173// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001174//
Chris Lattner4b009652007-07-25 00:24:17 +00001175
1176static llvm::cl::opt<bool>
1177nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1178
1179// Various command line options. These four add directories to each chain.
1180static llvm::cl::list<std::string>
1181F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1182 llvm::cl::desc("Add directory to framework include search path"));
1183static llvm::cl::list<std::string>
1184I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1185 llvm::cl::desc("Add directory to include search path"));
1186static llvm::cl::list<std::string>
1187idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1188 llvm::cl::desc("Add directory to AFTER include search path"));
1189static llvm::cl::list<std::string>
1190iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1191 llvm::cl::desc("Add directory to QUOTE include search path"));
1192static llvm::cl::list<std::string>
1193isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1194 llvm::cl::desc("Add directory to SYSTEM include search path"));
1195
1196// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1197static llvm::cl::list<std::string>
1198iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1199 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1200static llvm::cl::list<std::string>
1201iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1202 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1203static llvm::cl::list<std::string>
1204iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1205 llvm::cl::Prefix,
1206 llvm::cl::desc("Set directory to include search path with prefix"));
1207
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001208static llvm::cl::opt<std::string>
1209isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1210 llvm::cl::desc("Set the system root directory (usually /)"));
1211
Chris Lattner4b009652007-07-25 00:24:17 +00001212// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001213
Chris Lattner4b009652007-07-25 00:24:17 +00001214/// InitializeIncludePaths - Process the -I options and set them in the
1215/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001216void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1217 FileManager &FM, const LangOptions &Lang) {
1218 InitHeaderSearch Init(Headers, Verbose, isysroot);
1219
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001220 // Handle -I... and -F... options, walking the lists in parallel.
1221 unsigned Iidx = 0, Fidx = 0;
1222 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1223 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001224 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001225 ++Iidx;
1226 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001227 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001228 ++Fidx;
1229 }
1230 }
Chris Lattner4b009652007-07-25 00:24:17 +00001231
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001232 // Consume what's left from whatever list was longer.
1233 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001234 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001235 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001236 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001237
1238 // Handle -idirafter... options.
1239 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001240 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1241 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001242
1243 // Handle -iquote... options.
1244 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001245 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001246
1247 // Handle -isystem... options.
1248 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001249 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001250
1251 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1252 // parallel, processing the values in order of occurance to get the right
1253 // prefixes.
1254 {
1255 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1256 unsigned iprefix_idx = 0;
1257 unsigned iwithprefix_idx = 0;
1258 unsigned iwithprefixbefore_idx = 0;
1259 bool iprefix_done = iprefix_vals.empty();
1260 bool iwithprefix_done = iwithprefix_vals.empty();
1261 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1262 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1263 if (!iprefix_done &&
1264 (iwithprefix_done ||
1265 iprefix_vals.getPosition(iprefix_idx) <
1266 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1267 (iwithprefixbefore_done ||
1268 iprefix_vals.getPosition(iprefix_idx) <
1269 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1270 Prefix = iprefix_vals[iprefix_idx];
1271 ++iprefix_idx;
1272 iprefix_done = iprefix_idx == iprefix_vals.size();
1273 } else if (!iwithprefix_done &&
1274 (iwithprefixbefore_done ||
1275 iwithprefix_vals.getPosition(iwithprefix_idx) <
1276 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001277 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1278 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001279 ++iwithprefix_idx;
1280 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1281 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001282 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1283 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001284 ++iwithprefixbefore_idx;
1285 iwithprefixbefore_done =
1286 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1287 }
1288 }
1289 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001290
Nico Weber770e3882008-08-22 09:25:22 +00001291 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001292
Daniel Dunbar4e604292009-02-21 20:52:41 +00001293 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001294 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001295 llvm::sys::Path::GetMainExecutable(Argv0,
1296 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001297 if (!MainExecutablePath.isEmpty()) {
1298 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1299 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001300
1301 // Get foo/lib/clang/1.0/include
1302 //
1303 // FIXME: Don't embed version here.
1304 MainExecutablePath.appendComponent("lib");
1305 MainExecutablePath.appendComponent("clang");
1306 MainExecutablePath.appendComponent("1.0");
1307 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001308
1309 // We pass true to ignore sysroot so that we *always* look for clang headers
1310 // relative to our executable, never relative to -isysroot.
1311 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1312 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001313 }
1314
Nico Weber770e3882008-08-22 09:25:22 +00001315 if (!nostdinc)
1316 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001317
1318 // Now that we have collected all of the include paths, merge them all
1319 // together and tell the preprocessor about them.
1320
Nico Weber770e3882008-08-22 09:25:22 +00001321 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001322}
1323
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001324//===----------------------------------------------------------------------===//
1325// Driver PreprocessorFactory - For lazily generating preprocessors ...
1326//===----------------------------------------------------------------------===//
1327
1328namespace {
1329class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001330 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001331 Diagnostic &Diags;
1332 const LangOptions &LangInfo;
1333 TargetInfo &Target;
1334 SourceManager &SourceMgr;
1335 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001336 bool InitializeSourceMgr;
1337
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001338public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001339 DriverPreprocessorFactory(const std::string &infile,
1340 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001341 TargetInfo &target, SourceManager &SM,
1342 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001343 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1344 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1345
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001346
1347 virtual ~DriverPreprocessorFactory() {}
1348
1349 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001350 llvm::OwningPtr<PTHManager> PTHMgr;
1351
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001352 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1353 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1354 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001355 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001356 }
1357
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001358 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001359 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1360 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001361 PTHMgr.reset(PTHManager::Create(x, &Diags,
1362 TokenCache.empty() ? Diagnostic::Error
1363 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001364 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001365
Ted Kremenek6348cc62009-03-22 06:42:39 +00001366 if (Diags.hasErrorOccurred())
1367 exit(1);
1368
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001369 // Create the Preprocessor.
1370 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1371 SourceMgr, HeaderInfo,
1372 PTHMgr.get()));
1373
1374 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1375 // That argument is used as the IdentifierInfoLookup argument to
1376 // IdentifierTable's ctor.
1377 if (PTHMgr) {
1378 PTHMgr->setPreprocessor(PP.get());
1379 PP->setPTHManager(PTHMgr.take());
1380 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001381
Douglas Gregorab1cef72009-04-10 03:52:48 +00001382 return PP.take();
1383 }
1384
1385 virtual bool FinishInitialization(Preprocessor *PP) {
Chris Lattner9d818a22008-04-19 23:25:44 +00001386 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Douglas Gregorab1cef72009-04-10 03:52:48 +00001387 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001388 }
1389
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001390 /// FIXME: PP can only handle one callback
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001391 if (ProgAction != PrintPreprocessedInput) {
1392 std::string ErrStr;
Douglas Gregorab1cef72009-04-10 03:52:48 +00001393 bool DFG = CreateDependencyFileGen(PP, ErrStr);
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001394 if (!DFG && !ErrStr.empty()) {
1395 fprintf(stderr, "%s", ErrStr.c_str());
Douglas Gregorab1cef72009-04-10 03:52:48 +00001396 return true;
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001397 }
1398 }
1399
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001400 InitializeSourceMgr = false;
Douglas Gregorab1cef72009-04-10 03:52:48 +00001401 return false;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001402 }
1403};
1404}
Chris Lattner4b009652007-07-25 00:24:17 +00001405
Chris Lattner4b009652007-07-25 00:24:17 +00001406//===----------------------------------------------------------------------===//
1407// Basic Parser driver
1408//===----------------------------------------------------------------------===//
1409
Chris Lattner9d818a22008-04-19 23:25:44 +00001410static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001411 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001412 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001413
1414 // Parsing the specified input file.
1415 P.ParseTranslationUnit();
1416 delete PA;
1417}
1418
1419//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001420// Code generation options
1421//===----------------------------------------------------------------------===//
1422
1423static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001424GenerateDebugInfo("g",
1425 llvm::cl::desc("Generate source level debug information"));
1426
Daniel Dunbar9101a632009-02-17 19:47:34 +00001427static llvm::cl::opt<std::string>
1428TargetCPU("mcpu",
1429 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1430
Chris Lattner8a9615c2009-03-16 18:41:18 +00001431static void InitializeCompileOptions(CompileOptions &Opts,
1432 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001433 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001434 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001435 if (OptSize) {
1436 // -Os implies -O2
1437 // FIXME: Diagnose conflicting options.
1438 Opts.OptimizationLevel = 2;
1439 } else {
1440 Opts.OptimizationLevel = OptLevel;
1441 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001442
1443 // FIXME: There are llvm-gcc options to control these selectively.
1444 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1445 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001446 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001447
1448#ifdef NDEBUG
1449 Opts.VerifyModule = 0;
1450#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001451
1452 Opts.CPU = TargetCPU;
1453 Opts.Features.insert(Opts.Features.end(),
1454 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001455
Chris Lattnerf04a7562009-03-26 05:00:52 +00001456 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1457
Chris Lattnere8f70712009-02-18 01:23:44 +00001458 // Handle -ftime-report.
1459 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001460}
1461
1462//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001463// Fix-It Options
1464//===----------------------------------------------------------------------===//
1465static llvm::cl::list<ParsedSourceLocation>
1466FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1467 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1468
1469//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001470// Main driver
1471//===----------------------------------------------------------------------===//
1472
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001473/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001474/// action. These consumers can operate on both ASTs that are freshly
1475/// parsed from source files as well as those deserialized from Bitcode.
1476/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001477static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001478 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001479 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001480 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001481 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001482 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001483 default:
1484 return NULL;
1485
1486 case ASTPrint:
1487 return CreateASTPrinter();
1488
1489 case ASTDump:
1490 return CreateASTDumper();
1491
1492 case ASTView:
1493 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001494
Chris Lattner7f902922009-02-18 01:20:05 +00001495 case PrintDeclContext:
1496 return CreateDeclContextPrinter();
1497
1498 case EmitHTML:
1499 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001500
Chris Lattner7f902922009-02-18 01:20:05 +00001501 case InheritanceView:
1502 return CreateInheritanceViewer(InheritanceViewCls);
1503
1504 case TestSerialization:
1505 return CreateSerializationTest(Diag, FileMgr);
1506
1507 case EmitAssembly:
1508 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001509 case EmitBC:
1510 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001511 BackendAction Act;
1512 if (ProgAction == EmitAssembly)
1513 Act = Backend_EmitAssembly;
1514 else if (ProgAction == EmitLLVM)
1515 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001516 else if (ProgAction == EmitLLVMOnly)
1517 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001518 else
1519 Act = Backend_EmitBC;
1520
1521 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001522 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001523 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001524 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001525 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001526
Chris Lattner7f902922009-02-18 01:20:05 +00001527 case SerializeAST:
1528 // FIXME: Allow user to tailor where the file is written.
1529 return CreateASTSerializer(InFile, OutputFile, Diag);
1530
Douglas Gregorc34897d2009-04-09 22:27:44 +00001531 case GeneratePCH:
1532 return CreatePCHGenerator(Diag, LangOpts, InFile, OutputFile);
1533
Chris Lattner7f902922009-02-18 01:20:05 +00001534 case RewriteObjC:
1535 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001536
Chris Lattner7f902922009-02-18 01:20:05 +00001537 case RewriteBlocks:
1538 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1539
1540 case RunAnalysis:
1541 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001542 }
1543}
1544
Chris Lattner4b009652007-07-25 00:24:17 +00001545/// ProcessInputFile - Process a single input file with the specified state.
1546///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001547static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001548 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001549 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001550 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001551 FixItRewriter *FixItRewrite = 0;
1552
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001553 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001554 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001555 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1556 PP.getFileManager(), PP.getLangOptions(),
1557 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001558
1559 if (!Consumer) {
1560 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001561 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001562 return;
1563 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001564
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001565 break;
1566
Chris Lattneraf669fb2008-10-12 05:03:36 +00001567 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001568 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001569 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001570 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001571 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001572 RawLex.SetKeepWhitespaceMode(true);
1573
1574 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001575 RawLex.LexFromRawLexer(RawTok);
1576 while (RawTok.isNot(tok::eof)) {
1577 PP.DumpToken(RawTok, true);
1578 fprintf(stderr, "\n");
1579 RawLex.LexFromRawLexer(RawTok);
1580 }
1581 ClearSourceMgr = true;
1582 break;
1583 }
Chris Lattner4b009652007-07-25 00:24:17 +00001584 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001585 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001586 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001587 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001588 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001589 do {
1590 PP.Lex(Tok);
1591 PP.DumpToken(Tok, true);
1592 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001593 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001594 ClearSourceMgr = true;
1595 break;
1596 }
1597 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001598 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001599 Token Tok;
1600 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001601 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001602 do {
1603 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001604 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001605 ClearSourceMgr = true;
1606 break;
1607 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001608
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001609 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001610 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001611 CacheTokens(PP, OutputFile);
1612 ClearSourceMgr = true;
1613 break;
1614 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001615
Chris Lattnerefe33382009-02-18 01:51:21 +00001616 case PrintPreprocessedInput: { // -E mode.
1617 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001618 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001619 ClearSourceMgr = true;
1620 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001621 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001622
Chris Lattnerefe33382009-02-18 01:51:21 +00001623 case ParseNoop: { // -parse-noop
1624 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001625 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001626 ClearSourceMgr = true;
1627 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001628 }
Chris Lattner4b009652007-07-25 00:24:17 +00001629
Chris Lattnerefe33382009-02-18 01:51:21 +00001630 case ParsePrintCallbacks: {
1631 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001632 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001633 ClearSourceMgr = true;
1634 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001635 }
1636
1637 case ParseSyntaxOnly: { // -fsyntax-only
1638 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001639 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001640 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001641 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001642
1643 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001644 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001645 ClearSourceMgr = true;
1646 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001647
Chris Lattnerefe33382009-02-18 01:51:21 +00001648 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001649 DoRewriteTest(PP, InFile, OutputFile);
1650 ClearSourceMgr = true;
1651 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001652 }
Douglas Gregor133d2552009-04-02 01:08:08 +00001653
1654 case FixIt:
1655 llvm::TimeRegion Timer(ClangFrontendTimer);
1656 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001657 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Douglas Gregor133d2552009-04-02 01:08:08 +00001658 PP.getSourceManager());
Douglas Gregor133d2552009-04-02 01:08:08 +00001659 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001660 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001661
1662 if (Consumer) {
Chris Lattner143fd6d2009-03-28 01:37:17 +00001663 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner143fd6d2009-03-28 01:37:17 +00001664
Douglas Gregor24b48b02009-04-02 19:05:20 +00001665 if (FixItAtLocations.size() > 0) {
1666 // Even without the "-fixit" flag, with may have some specific
1667 // locations where the user has requested fixes. Process those
1668 // locations now.
1669 if (!FixItRewrite)
1670 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1671 PP.getSourceManager());
1672
1673 bool AddedFixitLocation = false;
1674 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1675 Idx != Last; ++Idx) {
1676 RequestedSourceLocation Requested;
1677 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1678 Requested)) {
1679 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1680 FixItAtLocations[Idx].FileName.c_str());
1681 } else {
1682 FixItRewrite->addFixItLocation(Requested);
1683 AddedFixitLocation = true;
1684 }
1685 }
1686
1687 if (!AddedFixitLocation) {
1688 // All of the fix-it locations were bad. Don't fix anything.
1689 delete FixItRewrite;
1690 FixItRewrite = 0;
1691 }
1692 }
1693
Chris Lattner143fd6d2009-03-28 01:37:17 +00001694 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1695 PP.getSourceManager(),
1696 PP.getTargetInfo(),
1697 PP.getIdentifierTable(),
1698 PP.getSelectorTable(),
1699 /* FreeMemory = */ !DisableFree));
Chris Lattner143fd6d2009-03-28 01:37:17 +00001700
Douglas Gregorc34897d2009-04-09 22:27:44 +00001701 if (!ImplicitIncludePCH.empty()) {
1702 // The user has asked us to include a precompiled header. Load
1703 // the precompiled header into the AST context.
Douglas Gregorab1cef72009-04-10 03:52:48 +00001704 llvm::OwningPtr<PCHReader>
1705 Reader(new clang::PCHReader(PP, *ContextOwner.get()));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001706 if (Reader->ReadPCH(ImplicitIncludePCH))
1707 return;
1708
1709 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
1710 ContextOwner->setExternalSource(Source);
Douglas Gregorab1cef72009-04-10 03:52:48 +00001711
1712 // Finish preprocessor initialization. We do this now (rather
1713 // than earlier) because this initialization creates new source
1714 // location entries in the source manager, which must come after
1715 // the source location entries for the PCH file.
1716 if (PPF.FinishInitialization(&PP))
1717 return;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001718 }
1719
Chris Lattner07b08c02009-03-28 04:13:34 +00001720 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner143fd6d2009-03-28 01:37:17 +00001721
Douglas Gregor133d2552009-04-02 01:08:08 +00001722 if (FixItRewrite)
1723 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1724
Chris Lattner143fd6d2009-03-28 01:37:17 +00001725 // If in -disable-free mode, don't deallocate these when they go out of
1726 // scope.
Chris Lattner07b08c02009-03-28 04:13:34 +00001727 if (DisableFree)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001728 ContextOwner.take();
Ted Kremenek88eebed2009-01-28 04:29:29 +00001729 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001730
1731 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001732 if (CheckDiagnostics(PP))
1733 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001734
Chris Lattner4b009652007-07-25 00:24:17 +00001735 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001736 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001737 PP.PrintStats();
1738 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001739 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001740 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001741 fprintf(stderr, "\n");
1742 }
1743
1744 // For a multi-file compilation, some things are ok with nuking the source
1745 // manager tables, other require stable fileid/macroid's across multiple
1746 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001747 if (ClearSourceMgr)
1748 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001749
1750 if (DisableFree)
1751 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001752}
1753
Ted Kremenek80d53372007-12-12 23:41:08 +00001754static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1755 FileManager& FileMgr) {
1756
1757 if (VerifyDiagnostics) {
1758 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1759 exit (1);
1760 }
1761
1762 llvm::sys::Path Filename(InFile);
1763
1764 if (!Filename.isValid()) {
1765 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1766 exit (1);
1767 }
1768
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001769 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner06459ae2009-03-28 03:49:26 +00001770
1771 // Create the memory buffer that contains the contents of the file.
1772 llvm::OwningPtr<llvm::MemoryBuffer>
1773 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1774
1775 if (MBuffer)
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001776 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001777
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001778 if (!Ctx) {
Ted Kremenek2bd42412007-12-13 18:11:11 +00001779 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1780 InFile.c_str());
1781 exit (1);
1782 }
1783
Ted Kremenekab749372007-12-19 19:27:38 +00001784 // Observe that we use the source file name stored in the deserialized
1785 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001786 llvm::OwningPtr<ASTConsumer>
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001787 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001788 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001789
Ted Kremenek80d53372007-12-12 23:41:08 +00001790 if (!Consumer) {
1791 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1792 exit (1);
1793 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001794
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001795 Consumer->Initialize(*Ctx);
Nico Weberd2a6ac92008-08-10 19:59:06 +00001796
Chris Lattner8d72ee02008-02-06 01:42:25 +00001797 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001798 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001799 for (DeclContext::decl_iterator I = TUD->decls_begin(*Ctx),
1800 E = TUD->decls_end(*Ctx);
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001801 I != E; ++I)
Chris Lattnera17991f2009-03-29 16:50:03 +00001802 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek80d53372007-12-12 23:41:08 +00001803}
1804
1805
Chris Lattner4b009652007-07-25 00:24:17 +00001806static llvm::cl::list<std::string>
1807InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1808
Ted Kremenek80d53372007-12-12 23:41:08 +00001809static bool isSerializedFile(const std::string& InFile) {
1810 if (InFile.size() < 4)
1811 return false;
1812
1813 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00001814 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00001815}
1816
Chris Lattner4b009652007-07-25 00:24:17 +00001817
1818int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001819 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001820 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001821 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001822 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001823
Chris Lattnerefe33382009-02-18 01:51:21 +00001824 if (TimeReport)
1825 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1826
Chris Lattner4b009652007-07-25 00:24:17 +00001827 // If no input was specified, read from stdin.
1828 if (InputFilenames.empty())
1829 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001830
Chris Lattner4b009652007-07-25 00:24:17 +00001831 // Create a file manager object to provide access to and cache the filesystem.
1832 FileManager FileMgr;
1833
Ted Kremenekb240e822007-12-11 23:28:38 +00001834 // Create the diagnostic client for reporting errors or for
1835 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001836 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001837
Ted Kremenek5c341732008-08-07 17:49:57 +00001838 if (!VerifyDiagnostics) {
1839 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001840 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1841 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001842 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00001843 !NoShowLocation,
1844 PrintSourceRangeInfo);
Ted Kremenek5c341732008-08-07 17:49:57 +00001845 } else {
1846 // When checking diagnostics, just buffer them up.
1847 TextDiagClient = new TextDiagnosticBuffer();
1848
1849 if (InputFilenames.size() != 1) {
1850 fprintf(stderr,
1851 "-verify only works on single input files for now.\n");
1852 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001853 }
1854 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001855
Chris Lattner4b009652007-07-25 00:24:17 +00001856 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001857 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1858 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001859 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001860 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001861
Chris Lattner45a56e02007-12-05 23:24:17 +00001862 // -I- is a deprecated GCC feature, scan for it and reject it.
1863 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1864 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001865 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001866 I_dirs.erase(I_dirs.begin()+i);
1867 --i;
1868 }
1869 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001870
1871 // Get information about the target being compiled for.
1872 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001873 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1874
Chris Lattner2c77d852008-03-14 06:12:05 +00001875 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001876 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1877 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001878 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001879 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001880
Daniel Dunbar9c321102009-01-20 23:17:32 +00001881 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001882 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001883
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001884 llvm::OwningPtr<SourceManager> SourceMgr;
1885
Chris Lattner4b009652007-07-25 00:24:17 +00001886 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001887 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001888
Ted Kremenek5c341732008-08-07 17:49:57 +00001889 if (isSerializedFile(InFile)) {
1890 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001891 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00001892 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001893 }
Chris Lattner2b989562009-03-04 21:40:56 +00001894
1895 /// Create a SourceManager object. This tracks and owns all the file
1896 /// buffers allocated to a translation unit.
1897 if (!SourceMgr)
1898 SourceMgr.reset(new SourceManager());
1899 else
1900 SourceMgr->clearIDTables();
1901
1902 // Initialize language options, inferring file types from input filenames.
1903 LangOptions LangInfo;
1904 InitializeBaseLanguage();
1905 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001906 InitializeLangOptions(LangInfo, LK);
Chris Lattner2b989562009-03-04 21:40:56 +00001907 InitializeGCMode(LangInfo);
Fariborz Jahanian49343332009-04-03 03:28:57 +00001908 InitializeSymbolVisibility(LangInfo);
Mike Stumpdb789912009-04-01 20:28:16 +00001909 InitializeOverflowChecking(LangInfo);
Chris Lattner2b989562009-03-04 21:40:56 +00001910 InitializeLanguageStandard(LangInfo, LK, Target.get());
1911
1912 // Process the -I options and set them in the HeaderInfo.
1913 HeaderSearch HeaderInfo(FileMgr);
1914
1915 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1916
1917 // Set up the preprocessor with these options.
1918 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1919 *SourceMgr.get(), HeaderInfo);
1920
1921 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1922
1923 if (!PP)
1924 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001925
Douglas Gregorab1cef72009-04-10 03:52:48 +00001926 if (ImplicitIncludePCH.empty()
1927 && PPFactory.FinishInitialization(PP.get()))
1928 continue;
1929
Chris Lattner2b989562009-03-04 21:40:56 +00001930 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1931 // always reset to using TextDiagClient.
1932 llvm::OwningPtr<DiagnosticClient> TmpClient;
1933
1934 if (!HTMLDiag.empty()) {
1935 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1936 &PPFactory));
1937 Diags.setClient(TmpClient.get());
Ted Kremenek80d53372007-12-12 23:41:08 +00001938 }
Chris Lattner2b989562009-03-04 21:40:56 +00001939 else
1940 Diags.setClient(TextDiagClient);
1941
1942 // Process the source file.
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001943 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattner2b989562009-03-04 21:40:56 +00001944
1945 HeaderInfo.ClearFileInfo();
Chris Lattner4b009652007-07-25 00:24:17 +00001946 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001947
Mike Stump91d01352009-01-28 02:43:35 +00001948 if (Verbose)
1949 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1950 " hosted on " LLVM_HOSTTRIPLE "\n");
1951
Ted Kremenekec6c5252008-08-07 18:13:12 +00001952 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001953 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1954 (NumDiagnostics == 1 ? "" : "s"));
1955
1956 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001957 FileMgr.PrintStats();
1958 fprintf(stderr, "\n");
1959 }
1960
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001961 // If verifying diagnostics and we reached here, all is well.
1962 if (VerifyDiagnostics)
1963 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001964
1965 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001966
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001967 // Managed static deconstruction. Useful for making things like
1968 // -time-passes usable.
1969 llvm::llvm_shutdown();
1970
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001971 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001972}