blob: cc4c0615b1b51cf1ea0d5d57c810020ac5c3122e [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>
Chris Lattner041bd732009-04-19 07:44:08 +0000303NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
304 llvm::cl::desc("Do not include fixit information in"
305 " diagnostics"));
306
307static llvm::cl::opt<bool>
Chris Lattner13bac9e2009-04-21 05:34:31 +0000308PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
309 llvm::cl::desc("Print source range spans in numeric form"));
310
311static llvm::cl::alias
312PrintSourceRangeInfo2("fprint-source-range-info",
313 llvm::cl::desc("Print source range spans in numeric form [deprecated]"),
314 llvm::cl::aliasopt(PrintSourceRangeInfo));
Chris Lattner695a4f52009-03-13 01:08:23 +0000315
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000316static llvm::cl::opt<bool>
317PrintDiagnosticOption("fdiagnostics-show-option",
318 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weber0e13eaa2008-08-05 23:33:20 +0000319
Chris Lattner4b009652007-07-25 00:24:17 +0000320//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000321// C++ Visualization.
322//===----------------------------------------------------------------------===//
323
324static llvm::cl::opt<std::string>
325InheritanceViewCls("cxx-inheritance-view",
326 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000327 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000328
329//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000330// Builtin Options
331//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000332
333static llvm::cl::opt<bool>
334TimeReport("ftime-report",
335 llvm::cl::desc("Print the amount of time each "
336 "phase of compilation takes"));
337
Douglas Gregor23d23262009-02-14 20:49:29 +0000338static llvm::cl::opt<bool>
339Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000340 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000341 "freestanding environment"));
342
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000343static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000344AllowBuiltins("fbuiltin", llvm::cl::init(true),
345 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000346
347
348static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000349MathErrno("fmath-errno", llvm::cl::init(true),
350 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000351
Douglas Gregor23d23262009-02-14 20:49:29 +0000352//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000353// Language Options
354//===----------------------------------------------------------------------===//
355
356enum LangKind {
357 langkind_unspecified,
358 langkind_c,
359 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000360 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000361 langkind_cxx,
362 langkind_cxx_cpp,
363 langkind_objc,
364 langkind_objc_cpp,
365 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000366 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000367};
368
Chris Lattner4b009652007-07-25 00:24:17 +0000369static llvm::cl::opt<LangKind>
370BaseLang("x", llvm::cl::desc("Base language to compile"),
371 llvm::cl::init(langkind_unspecified),
372 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
373 clEnumValN(langkind_cxx, "c++", "C++"),
374 clEnumValN(langkind_objc, "objective-c", "Objective C"),
375 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000376 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000377 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000378 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
379 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000380 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000381 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000382 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
383 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000384 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000385 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000386 clEnumValN(langkind_c, "c-header",
387 "C header"),
388 clEnumValN(langkind_objc, "objective-c-header",
389 "Objective-C header"),
390 clEnumValN(langkind_cxx, "c++-header",
391 "C++ header"),
392 clEnumValN(langkind_objcxx, "objective-c++-header",
393 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000394 clEnumValEnd));
395
396static llvm::cl::opt<bool>
397LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
398 llvm::cl::Hidden);
399static llvm::cl::opt<bool>
400LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
401 llvm::cl::Hidden);
402
Chris Lattnere1be6022009-04-14 23:22:57 +0000403static llvm::cl::opt<bool>
404ObjCExclusiveGC("fobjc-gc-only",
405 llvm::cl::desc("Use GC exclusively for Objective-C related "
406 "memory management"));
407
408static llvm::cl::opt<bool>
409ObjCEnableGC("fobjc-gc",
410 llvm::cl::desc("Enable Objective-C garbage collection"));
411
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000412static llvm::cl::opt<bool>
413ObjCEnableGCBitmapPrint("print-ivar-layout",
414 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
415
Chris Lattnere1be6022009-04-14 23:22:57 +0000416static llvm::cl::opt<LangOptions::VisibilityMode>
417SymbolVisibility("fvisibility",
418 llvm::cl::desc("Set the default symbol visibility:"),
419 llvm::cl::init(LangOptions::Default),
420 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
421 "Use default symbol visibility"),
422 clEnumValN(LangOptions::Hidden, "hidden",
423 "Use hidden symbol visibility"),
424 clEnumValN(LangOptions::Protected,"protected",
425 "Use protected symbol visibility"),
426 clEnumValEnd));
427
428static llvm::cl::opt<bool>
429OverflowChecking("ftrapv",
430 llvm::cl::desc("Trap on integer overflow"),
431 llvm::cl::init(false));
432
433
Ted Kremenek11ad8952007-12-05 23:49:08 +0000434/// InitializeBaseLanguage - Handle the -x foo options.
435static void InitializeBaseLanguage() {
436 if (LangObjC)
437 BaseLang = langkind_objc;
438 else if (LangObjCXX)
439 BaseLang = langkind_objcxx;
440}
441
442static LangKind GetLanguage(const std::string &Filename) {
443 if (BaseLang != langkind_unspecified)
444 return BaseLang;
445
446 std::string::size_type DotPos = Filename.rfind('.');
447
448 if (DotPos == std::string::npos) {
449 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000450 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000451 }
452
Ted Kremenek11ad8952007-12-05 23:49:08 +0000453 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
454 // C header: .h
455 // C++ header: .hh or .H;
456 // assembler no preprocessing: .s
457 // assembler: .S
458 if (Ext == "c")
459 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000460 else if (Ext == "S" ||
461 // If the compiler is run on a .s file, preprocess it as .S
462 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000463 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000464 else if (Ext == "i")
465 return langkind_c_cpp;
466 else if (Ext == "ii")
467 return langkind_cxx_cpp;
468 else if (Ext == "m")
469 return langkind_objc;
470 else if (Ext == "mi")
471 return langkind_objc_cpp;
472 else if (Ext == "mm" || Ext == "M")
473 return langkind_objcxx;
474 else if (Ext == "mii")
475 return langkind_objcxx_cpp;
476 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
477 Ext == "c++" || Ext == "cp" || Ext == "cxx")
478 return langkind_cxx;
479 else
480 return langkind_c;
481}
482
483
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000484static void InitializeCOptions(LangOptions &Options) {
485 // Do nothing.
486}
487
488static void InitializeObjCOptions(LangOptions &Options) {
489 Options.ObjC1 = Options.ObjC2 = 1;
490}
491
492
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000493static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000494 // FIXME: implement -fpreprocessed mode.
495 bool NoPreprocess = false;
496
Ted Kremenek11ad8952007-12-05 23:49:08 +0000497 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000498 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000499 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000500 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000501 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000502 case langkind_c_cpp:
503 NoPreprocess = true;
504 // FALLTHROUGH
505 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000506 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000507 break;
508 case langkind_cxx_cpp:
509 NoPreprocess = true;
510 // FALLTHROUGH
511 case langkind_cxx:
512 Options.CPlusPlus = 1;
513 break;
514 case langkind_objc_cpp:
515 NoPreprocess = true;
516 // FALLTHROUGH
517 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000518 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000519 break;
520 case langkind_objcxx_cpp:
521 NoPreprocess = true;
522 // FALLTHROUGH
523 case langkind_objcxx:
524 Options.ObjC1 = Options.ObjC2 = 1;
525 Options.CPlusPlus = 1;
526 break;
527 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000528
529 if (ObjCExclusiveGC)
530 Options.setGCMode(LangOptions::GCOnly);
531 else if (ObjCEnableGC)
532 Options.setGCMode(LangOptions::HybridGC);
533
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000534 if (ObjCEnableGCBitmapPrint)
535 Options.ObjCGCBitmapPrint = 1;
536
Chris Lattnere1be6022009-04-14 23:22:57 +0000537 Options.setVisibilityMode(SymbolVisibility);
538 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000539}
540
541/// LangStds - Language standards we support.
542enum LangStds {
543 lang_unspecified,
544 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000545 lang_gnu_START,
546 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000547 lang_cxx98, lang_gnucxx98,
548 lang_cxx0x, lang_gnucxx0x
549};
550
551static llvm::cl::opt<LangStds>
552LangStd("std", llvm::cl::desc("Language standard to compile for"),
553 llvm::cl::init(lang_unspecified),
554 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
555 clEnumValN(lang_c89, "c90", "ISO C 1990"),
556 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
557 clEnumValN(lang_c94, "iso9899:199409",
558 "ISO C 1990 with amendment 1"),
559 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000560 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000561 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000562 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000563 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000564 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000565 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000566 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000567 clEnumValN(lang_gnu99, "gnu9x",
568 "ISO C 1999 with GNU extensions"),
569 clEnumValN(lang_cxx98, "c++98",
570 "ISO C++ 1998 with amendments"),
571 clEnumValN(lang_gnucxx98, "gnu++98",
572 "ISO C++ 1998 with amendments and GNU "
573 "extensions (default for C++)"),
574 clEnumValN(lang_cxx0x, "c++0x",
575 "Upcoming ISO C++ 200x with amendments"),
576 clEnumValN(lang_gnucxx0x, "gnu++0x",
577 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000578 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000579 clEnumValEnd));
580
581static llvm::cl::opt<bool>
582NoOperatorNames("fno-operator-names",
583 llvm::cl::desc("Do not treat C++ operator name keywords as "
584 "synonyms for operators"));
585
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000586static llvm::cl::opt<bool>
587PascalStrings("fpascal-strings",
588 llvm::cl::desc("Recognize and construct Pascal-style "
589 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000590
591static llvm::cl::opt<bool>
592MSExtensions("fms-extensions",
593 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000594 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000595
596static llvm::cl::opt<bool>
597WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000598 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000599
600static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000601NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000602 llvm::cl::desc("Disallow implicit conversions between "
603 "vectors with a different number of "
604 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000605
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000606static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000607EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000608
609static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000610EnableHeinousExtensions("fheinous-gnu-extensions",
611 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
612 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
613
614static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000615ObjCNonFragileABI("fobjc-nonfragile-abi",
616 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000617
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000618static llvm::cl::opt<bool>
619EmitAllDecls("femit-all-decls",
620 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000621
Daniel Dunbar91692d92008-08-11 17:36:14 +0000622// FIXME: This (and all GCC -f options) really come in -f... and
623// -fno-... forms, and additionally support automagic behavior when
624// they are not defined. For example, -fexceptions defaults to on or
625// off depending on the language. We should support this behavior in
626// some form (perhaps just add a facility for distinguishing when an
627// has its default value from when it has been set to its default
628// value).
629static llvm::cl::opt<bool>
630Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000631 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000632
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000633static llvm::cl::opt<bool>
634GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000635 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000636 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000637
638static llvm::cl::opt<bool>
639NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000640 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000641 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000642
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000643
644
645static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000646Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000647
Chris Lattner738d3f62009-03-02 22:11:07 +0000648static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000649TargetFeatures("mattr", llvm::cl::CommaSeparated,
650 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
651
Douglas Gregor375733c2009-03-10 00:06:19 +0000652static llvm::cl::opt<unsigned>
653TemplateDepth("ftemplate-depth", llvm::cl::init(99),
654 llvm::cl::desc("Maximum depth of recursive template "
655 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000656static llvm::cl::opt<bool>
657DollarsInIdents("fdollars-in-identifiers",
658 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000659
Anders Carlssondfd77642009-04-06 17:37:10 +0000660
661static llvm::cl::opt<bool>
662OptSize("Os", llvm::cl::desc("Optimize for size"));
663
664static llvm::cl::opt<bool>
665NoCommon("fno-common",
666 llvm::cl::desc("Compile common globals like normal definitions"),
667 llvm::cl::ValueDisallowed);
668
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000669static llvm::cl::opt<std::string>
670MainFileName("main-file-name",
671 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000672
673// It might be nice to add bounds to the CommandLine library directly.
674struct OptLevelParser : public llvm::cl::parser<unsigned> {
675 bool parse(llvm::cl::Option &O, const char *ArgName,
676 const std::string &Arg, unsigned &Val) {
677 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
678 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000679 if (Val > 3)
680 return O.error(": '" + Arg + "' invalid optimization level!");
681 return false;
682 }
683};
684static llvm::cl::opt<unsigned, false, OptLevelParser>
685OptLevel("O", llvm::cl::Prefix,
686 llvm::cl::desc("Optimization level"),
687 llvm::cl::init(0));
688
Daniel Dunbare079c712009-04-08 03:03:23 +0000689static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000690PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
691
692static llvm::cl::opt<bool>
693StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000694
Daniel Dunbar34542952008-08-23 08:43:39 +0000695static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
696 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000697 // Allow the target to set the default the langauge options as it sees fit.
698 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000699
Chris Lattnerf6790a82009-03-03 19:56:18 +0000700 // If there are any -mattr options, pass them to the target for validation and
701 // processing. The driver should have already consolidated all the
702 // target-feature settings and passed them to us in the -mattr list. The
703 // -mattr list is treated by the code generator as a diff against the -mcpu
704 // setting, but the driver should pass all enabled options as "+" settings.
705 // This means that the target should only look at + settings.
Chris Lattner880d38e2009-04-13 06:33:49 +0000706 if (!TargetFeatures.empty()) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000707 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000708 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
709 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000710 if (Opt != -1) {
711 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000712 fprintf(stderr, "invalid feature '%s'\n",
713 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000714 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000715 fprintf(stderr, "feature '%s': %s\n",
716 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000717 exit(1);
718 }
719 }
720
Chris Lattner4b009652007-07-25 00:24:17 +0000721 if (LangStd == lang_unspecified) {
722 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000723 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000724 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000725 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000726 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000727 case langkind_c_cpp:
728 case langkind_objc:
729 case langkind_objc_cpp:
730 LangStd = lang_gnu99;
731 break;
732 case langkind_cxx:
733 case langkind_cxx_cpp:
734 case langkind_objcxx:
735 case langkind_objcxx_cpp:
736 LangStd = lang_gnucxx98;
737 break;
738 }
739 }
740
741 switch (LangStd) {
742 default: assert(0 && "Unknown language standard!");
743
744 // Fall through from newer standards to older ones. This isn't really right.
745 // FIXME: Enable specifically the right features based on the language stds.
746 case lang_gnucxx0x:
747 case lang_cxx0x:
748 Options.CPlusPlus0x = 1;
749 // FALL THROUGH
750 case lang_gnucxx98:
751 case lang_cxx98:
752 Options.CPlusPlus = 1;
753 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000754 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000755 // FALL THROUGH.
756 case lang_gnu99:
757 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000758 Options.C99 = 1;
759 Options.HexFloats = 1;
760 // FALL THROUGH.
761 case lang_gnu89:
762 Options.BCPLComment = 1; // Only for C99/C++.
763 // FALL THROUGH.
764 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000765 Options.Digraphs = 1; // C94, C99, C++.
766 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000767 case lang_c89:
768 break;
769 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000770
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000771 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
772 Options.GNUMode = LangStd >= lang_gnu_START;
773
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000774 if (Options.CPlusPlus) {
775 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000776 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000777 }
Chris Lattner4b009652007-07-25 00:24:17 +0000778
Chris Lattner6ab935b2008-04-05 06:32:51 +0000779 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
780 Options.ImplicitInt = 1;
781 else
782 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000783
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000784 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
785 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000786 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000787 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000788 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000789
Chris Lattner58d5ba52008-12-05 00:10:44 +0000790 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
791 // even if they are normally on for the target. In GNU modes (e.g.
792 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000793 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000794 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000795 Options.Blocks = 0;
796
Chris Lattner284784c2009-04-19 07:06:52 +0000797 // Default to not accepting '$' in identifiers when preprocessing assembler,
798 // but do accept when preprocessing C. FIXME: these defaults are right for
799 // darwin, are they right everywhere?
800 Options.DollarIdents = LK != langkind_asm_cpp;
801 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner77c04832009-04-19 07:00:02 +0000802 Options.DollarIdents = DollarsInIdents;
803
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000804 if (PascalStrings.getPosition())
805 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000806 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000807 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000808 if (NoLaxVectorConversions.getPosition())
809 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000810 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000811 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000812 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000813
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000814 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000815 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000816 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000817 Options.Freestanding = Options.NoBuiltin = 1;
818
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000819 if (EnableHeinousExtensions)
820 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000821
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000822 Options.MathErrno = MathErrno;
823
Douglas Gregor375733c2009-03-10 00:06:19 +0000824 Options.InstantiationDepth = TemplateDepth;
825
Chris Lattnerddae7102008-12-04 22:54:33 +0000826 // Override the default runtime if the user requested it.
827 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000828 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000829 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000830 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000831
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000832 if (ObjCNonFragileABI)
833 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000834
835 if (EmitAllDecls)
836 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000837
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000838 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
839 // support.
840 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000841
842 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000843 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000844 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000845
846 assert(PICLevel <= 2 && "Invalid value for -pic-level");
847 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000848
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000849 Options.GNUInline = !Options.C99;
850 // FIXME: This is affected by other options (-fno-inline).
851 Options.NoInline = !OptSize && !OptLevel;
852
853 Options.Static = StaticDefine;
854
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000855 if (MainFileName.getPosition())
856 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000857}
858
859//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000860// Target Triple Processing.
861//===----------------------------------------------------------------------===//
862
863static llvm::cl::opt<std::string>
864TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000865 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000866
Chris Lattnerfc457002008-03-05 01:18:20 +0000867static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000868Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000869
Chris Lattner2b168e02008-09-30 01:13:12 +0000870static llvm::cl::opt<std::string>
871MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000872 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000873
Chris Lattner01de9c82008-09-30 20:16:56 +0000874// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
875// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000876
877// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000878static void HandleMacOSVersionMin(std::string &Triple) {
879 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
880 if (DarwinDashIdx == std::string::npos) {
881 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000882 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000883 exit(1);
884 }
885 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
886
Chris Lattner01de9c82008-09-30 20:16:56 +0000887 // Remove the number.
888 Triple.resize(DarwinNumIdx);
889
890 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
891 bool MacOSVersionMinIsInvalid = false;
892 int VersionNum = 0;
893 if (MacOSVersionMin.size() < 4 ||
894 MacOSVersionMin.substr(0, 3) != "10." ||
895 !isdigit(MacOSVersionMin[3])) {
896 MacOSVersionMinIsInvalid = true;
897 } else {
898 const char *Start = MacOSVersionMin.c_str()+3;
899 char *End = 0;
900 VersionNum = (int)strtol(Start, &End, 10);
901
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000902 // The version number must be in the range 0-9.
903 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
904
Chris Lattner01de9c82008-09-30 20:16:56 +0000905 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
906 Triple += llvm::itostr(VersionNum+4);
907
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000908 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
909 // Add the period piece (.7) to the end of the triple. This gives us
910 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000911 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000912 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
913 MacOSVersionMinIsInvalid = true;
914 }
915 }
916
917 if (MacOSVersionMinIsInvalid) {
918 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000919 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000920 MacOSVersionMin.c_str());
921 exit(1);
922 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000923 else if (VersionNum <= 4 &&
924 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
925 fprintf(stderr,
926 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
927 MacOSVersionMin.c_str());
928 exit(1);
929 }
930
Chris Lattner01de9c82008-09-30 20:16:56 +0000931}
932
Daniel Dunbar93f64532009-04-10 19:52:24 +0000933static llvm::cl::opt<std::string>
934IPhoneOSVersionMin("miphoneos-version-min",
935 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
936
937// If -miphoneos-version-min=2.2 is specified, change the triple from being
938// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
939// 9 as the default major Darwin number, and encode the iPhone OS version
940// number in the minor version and revision.
941
942// FIXME: We should have the driver do this instead.
943static void HandleIPhoneOSVersionMin(std::string &Triple) {
944 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
945 if (DarwinDashIdx == std::string::npos) {
946 fprintf(stderr,
947 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
948 exit(1);
949 }
950 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
951
952 // Remove the number.
953 Triple.resize(DarwinNumIdx);
954
955 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
956 bool IPhoneOSVersionMinIsInvalid = false;
957 int VersionNum = 0;
958 if (IPhoneOSVersionMin.size() < 3 ||
959 !isdigit(IPhoneOSVersionMin[0])) {
960 IPhoneOSVersionMinIsInvalid = true;
961 } else {
962 const char *Start = IPhoneOSVersionMin.c_str();
963 char *End = 0;
964 VersionNum = (int)strtol(Start, &End, 10);
965
966 // The version number must be in the range 0-9.
967 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
968
969 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
970 Triple += "9." + llvm::itostr(VersionNum);
971
972 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
973 // Add the period piece (.2) to the end of the triple. This gives us
974 // something like ...-darwin9.2.2
975 Triple += End;
976 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
977 IPhoneOSVersionMinIsInvalid = true;
978 }
979 }
980
981 if (IPhoneOSVersionMinIsInvalid) {
982 fprintf(stderr,
983 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
984 IPhoneOSVersionMin.c_str());
985 exit(1);
986 }
987}
988
Chris Lattner01de9c82008-09-30 20:16:56 +0000989/// CreateTargetTriple - Process the various options that affect the target
990/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000991static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000992 // Initialize base triple. If a -triple option has been specified, use
993 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000994 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000995 if (Triple.empty())
996 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000997
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000998 // If -arch foo was specified, remove the architecture from the triple we have
999 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +00001000
1001 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +00001002 if (!Arch.empty()) {
1003 // Decompose the base triple into "arch" and suffix.
1004 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +00001005
Chris Lattner2b168e02008-09-30 01:13:12 +00001006 if (FirstDashIdx == std::string::npos) {
1007 fprintf(stderr,
1008 "Malformed target triple: \"%s\" ('-' could not be found).\n",
1009 Triple.c_str());
1010 exit(1);
1011 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +00001012
1013 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1014 if (Arch == "ppc")
1015 Arch = "powerpc";
1016 else if (Arch == "ppc64")
1017 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +00001018
Chris Lattner2b168e02008-09-30 01:13:12 +00001019 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1020 }
1021
1022 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1023 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +00001024 if (!MacOSVersionMin.empty())
1025 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +00001026 else if (!IPhoneOSVersionMin.empty())
1027 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +00001028
Chris Lattner2b168e02008-09-30 01:13:12 +00001029 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001030}
1031
1032//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001033// Preprocessor Initialization
1034//===----------------------------------------------------------------------===//
1035
1036// FIXME: Preprocessor builtins to support.
1037// -A... - Play with #assertions
1038// -undef - Undefine all predefined macros
1039
Chris Lattner695a4f52009-03-13 01:08:23 +00001040// FIXME: -imacros
1041
Chris Lattner4b009652007-07-25 00:24:17 +00001042static llvm::cl::list<std::string>
1043D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1044 llvm::cl::desc("Predefine the specified macro"));
1045static llvm::cl::list<std::string>
1046U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1047 llvm::cl::desc("Undefine the specified macro"));
1048
Chris Lattner008da782008-01-10 01:53:41 +00001049static llvm::cl::list<std::string>
1050ImplicitIncludes("include", llvm::cl::value_desc("file"),
1051 llvm::cl::desc("Include file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001052static llvm::cl::list<std::string>
1053ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1054 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner008da782008-01-10 01:53:41 +00001055
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001056static llvm::cl::opt<std::string>
1057ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1058 llvm::cl::desc("Include file before parsing"));
1059
Douglas Gregorc34897d2009-04-09 22:27:44 +00001060static llvm::cl::opt<std::string>
1061ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1062 llvm::cl::desc("Include precompiled header file"));
1063
Chris Lattner4b009652007-07-25 00:24:17 +00001064// Append a #define line to Buf for Macro. Macro should be of the form XXX,
1065// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
1066// "#define XXX Y z W". To get a #define with no value, use "XXX=".
1067static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
1068 const char *Command = "#define ") {
1069 Buf.insert(Buf.end(), Command, Command+strlen(Command));
1070 if (const char *Equal = strchr(Macro, '=')) {
1071 // Turn the = into ' '.
1072 Buf.insert(Buf.end(), Macro, Equal);
1073 Buf.push_back(' ');
Chris Lattner39baafb2009-04-07 06:02:44 +00001074
1075 // Per GCC -D semantics, the macro ends at \n if it exists.
1076 const char *End = strpbrk(Equal, "\n\r");
Chris Lattner39c610d2009-04-07 18:18:09 +00001077 if (End) {
Chris Lattnerd93f7902009-04-08 03:36:03 +00001078 fprintf(stderr, "warning: macro '%s' contains embedded newline, text "
Chris Lattner39c610d2009-04-07 18:18:09 +00001079 "after the newline is ignored.\n",
1080 std::string(Macro, Equal).c_str());
1081 } else {
1082 End = Equal+strlen(Equal);
1083 }
Chris Lattner39baafb2009-04-07 06:02:44 +00001084
1085 Buf.insert(Buf.end(), Equal+1, End);
Chris Lattner4b009652007-07-25 00:24:17 +00001086 } else {
1087 // Push "macroname 1".
1088 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
1089 Buf.push_back(' ');
1090 Buf.push_back('1');
1091 }
1092 Buf.push_back('\n');
1093}
1094
Daniel Dunbar43b91692009-04-09 00:51:16 +00001095/// Add the quoted name of an implicit include file.
1096static void AddQuotedIncludePath(std::vector<char> &Buf,
1097 const std::string &File) {
1098 // Implicit include paths are relative to the current working
1099 // directory; resolve them now instead of using the normal machinery
1100 // (which would look relative to the input file).
1101 llvm::sys::Path Path(File);
1102 Path.makeAbsolute();
1103
Chris Lattner6ac92a32009-04-08 20:10:57 +00001104 // Escape double quotes etc.
Daniel Dunbar43b91692009-04-09 00:51:16 +00001105 Buf.push_back('"');
1106 std::string EscapedFile = Lexer::Stringify(Path.toString());
Chris Lattner6ac92a32009-04-08 20:10:57 +00001107 Buf.insert(Buf.end(), EscapedFile.begin(), EscapedFile.end());
Chris Lattner008da782008-01-10 01:53:41 +00001108 Buf.push_back('"');
Daniel Dunbar43b91692009-04-09 00:51:16 +00001109}
1110
1111/// AddImplicitInclude - Add an implicit #include of the specified file to the
1112/// predefines buffer.
1113static void AddImplicitInclude(std::vector<char> &Buf,
1114 const std::string &File) {
1115 const char *Inc = "#include ";
1116 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
1117 AddQuotedIncludePath(Buf, File);
Chris Lattner008da782008-01-10 01:53:41 +00001118 Buf.push_back('\n');
1119}
1120
Chris Lattner0e004a12009-04-08 18:24:34 +00001121static void AddImplicitIncludeMacros(std::vector<char> &Buf,
1122 const std::string &File) {
Daniel Dunbar43b91692009-04-09 00:51:16 +00001123 const char *Inc = "#__include_macros ";
Chris Lattner0e004a12009-04-08 18:24:34 +00001124 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
Daniel Dunbar43b91692009-04-09 00:51:16 +00001125 AddQuotedIncludePath(Buf, File);
Chris Lattner0e004a12009-04-08 18:24:34 +00001126 Buf.push_back('\n');
Chris Lattnera6e44112009-04-08 20:53:24 +00001127 // Marker token to stop the __include_macros fetch loop.
1128 const char *Marker = "##\n"; // ##?
1129 Buf.insert(Buf.end(), Marker, Marker+strlen(Marker));
Chris Lattner0e004a12009-04-08 18:24:34 +00001130}
1131
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001132/// AddImplicitIncludePTH - Add an implicit #include using the original file
1133/// used to generate a PTH cache.
Chris Lattner0e004a12009-04-08 18:24:34 +00001134static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor &PP) {
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001135 PTHManager *P = PP.getPTHManager();
1136 assert(P && "No PTHManager.");
1137 const char *OriginalFile = P->getOriginalSourceFile();
1138
1139 if (!OriginalFile) {
1140 assert(!ImplicitIncludePTH.empty());
1141 fprintf(stderr, "error: PTH file '%s' does not designate an original "
1142 "source header file for -include-pth\n",
1143 ImplicitIncludePTH.c_str());
1144 exit (1);
1145 }
1146
1147 AddImplicitInclude(Buf, OriginalFile);
1148}
Chris Lattner4b009652007-07-25 00:24:17 +00001149
Chris Lattnera9a0dd52009-04-10 21:58:23 +00001150/// PickFP - This is used to pick a value based on the FP semantics of the
1151/// specified FP model.
1152template <typename T>
1153static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
1154 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
1155 if (Sem == &llvm::APFloat::IEEEsingle)
1156 return IEEESingleVal;
1157 if (Sem == &llvm::APFloat::IEEEdouble)
1158 return IEEEDoubleVal;
1159 if (Sem == &llvm::APFloat::x87DoubleExtended)
1160 return X87DoubleExtendedVal;
1161 assert(Sem == &llvm::APFloat::PPCDoubleDouble);
1162 return PPCDoubleDoubleVal;
1163}
1164
1165static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
1166 const llvm::fltSemantics *Sem) {
1167 const char *DenormMin, *Epsilon, *Max, *Min;
1168 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
1169 "3.64519953188247460253e-4951L",
1170 "4.94065645841246544176568792868221e-324L");
1171 int Digits = PickFP(Sem, 6, 15, 18, 31);
1172 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
1173 "1.08420217248550443401e-19L",
1174 "4.94065645841246544176568792868221e-324L");
1175 int HasInifinity = 1, HasQuietNaN = 1;
1176 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106);
1177 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291);
1178 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308);
1179 int MinExp = PickFP(Sem, -125, -1021, -16381, -968);
1180 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024);
1181 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
1182 "3.36210314311209350626e-4932L",
1183 "2.00416836000897277799610805135016e-292L");
1184 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
1185 "1.18973149535723176502e+4932L",
1186 "1.79769313486231580793728971405301e+308L");
1187
1188 char MacroBuf[60];
1189 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
1190 DefineBuiltinMacro(Buf, MacroBuf);
1191 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
1192 DefineBuiltinMacro(Buf, MacroBuf);
1193 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
1194 DefineBuiltinMacro(Buf, MacroBuf);
1195 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
1196 DefineBuiltinMacro(Buf, MacroBuf);
1197 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
1198 DefineBuiltinMacro(Buf, MacroBuf);
1199 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
1200 DefineBuiltinMacro(Buf, MacroBuf);
1201 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
1202 DefineBuiltinMacro(Buf, MacroBuf);
1203 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
1204 DefineBuiltinMacro(Buf, MacroBuf);
1205 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
1206 DefineBuiltinMacro(Buf, MacroBuf);
1207 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
1208 DefineBuiltinMacro(Buf, MacroBuf);
1209 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
1210 DefineBuiltinMacro(Buf, MacroBuf);
1211 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
1212 DefineBuiltinMacro(Buf, MacroBuf);
1213 sprintf(MacroBuf, "__%s_HAS_DENORM__=1", Prefix);
1214 DefineBuiltinMacro(Buf, MacroBuf);
1215}
1216
1217
1218/// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
1219/// named MacroName with the max value for a type with width 'TypeWidth' a
1220/// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
1221static void DefineTypeSize(const char *MacroName, unsigned TypeWidth,
1222 const char *ValSuffix, bool isSigned,
1223 std::vector<char> &Buf) {
1224 char MacroBuf[60];
1225 long long MaxVal;
1226 if (isSigned)
1227 MaxVal = (1LL << (TypeWidth - 1)) - 1;
1228 else
1229 MaxVal = ~0LL >> (64-TypeWidth);
1230
1231 sprintf(MacroBuf, "%s=%llu%s", MacroName, MaxVal, ValSuffix);
1232 DefineBuiltinMacro(Buf, MacroBuf);
1233}
1234
1235static void DefineType(const char *MacroName, TargetInfo::IntType Ty,
1236 std::vector<char> &Buf) {
1237 char MacroBuf[60];
1238 sprintf(MacroBuf, "%s=%s", MacroName, TargetInfo::getTypeName(Ty));
1239 DefineBuiltinMacro(Buf, MacroBuf);
1240}
1241
1242
1243static void InitializePredefinedMacros(const TargetInfo &TI,
1244 const LangOptions &LangOpts,
1245 std::vector<char> &Buf) {
1246 char MacroBuf[60];
1247 // Compiler version introspection macros.
1248 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
1249 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
1250
1251 // Currently claim to be compatible with GCC 4.2.1-5621.
1252 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
1253 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
1254 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
1255 DefineBuiltinMacro(Buf, "__GNUC__=4");
1256 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
1257 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 Compatible Clang Compiler\"");
1258
1259
1260 // Initialize language-specific preprocessor defines.
1261
1262 // These should all be defined in the preprocessor according to the
1263 // current language configuration.
1264 if (!LangOpts.Microsoft)
1265 DefineBuiltinMacro(Buf, "__STDC__=1");
1266 if (LangOpts.AsmPreprocessor)
1267 DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
1268 if (LangOpts.C99 && !LangOpts.CPlusPlus)
1269 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
1270 else if (0) // STDC94 ?
1271 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
1272
1273 // Standard conforming mode?
1274 if (!LangOpts.GNUMode)
1275 DefineBuiltinMacro(Buf, "__STRICT_ANSI__=1");
1276
1277 if (LangOpts.CPlusPlus0x)
1278 DefineBuiltinMacro(Buf, "__GXX_EXPERIMENTAL_CXX0X__");
1279
1280 if (LangOpts.Freestanding)
1281 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=0");
1282 else
1283 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
1284
1285 if (LangOpts.ObjC1) {
1286 DefineBuiltinMacro(Buf, "__OBJC__=1");
1287 if (LangOpts.ObjCNonFragileABI) {
1288 DefineBuiltinMacro(Buf, "__OBJC2__=1");
1289 DefineBuiltinMacro(Buf, "OBJC_ZEROCOST_EXCEPTIONS=1");
1290 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
1291 }
1292
1293 if (LangOpts.getGCMode() != LangOptions::NonGC)
1294 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
1295
1296 if (LangOpts.NeXTRuntime)
1297 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
1298 }
1299
1300 // darwin_constant_cfstrings controls this. This is also dependent
1301 // on other things like the runtime I believe. This is set even for C code.
1302 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
1303
1304 if (LangOpts.ObjC2)
1305 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
1306
1307 if (LangOpts.PascalStrings)
1308 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
1309
1310 if (LangOpts.Blocks) {
1311 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
1312 DefineBuiltinMacro(Buf, "__BLOCKS__=1");
1313 }
1314
1315 if (LangOpts.CPlusPlus) {
1316 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
1317 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
1318 DefineBuiltinMacro(Buf, "__GNUG__=4");
1319 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
1320 DefineBuiltinMacro(Buf, "__cplusplus=1");
1321 DefineBuiltinMacro(Buf, "__private_extern__=extern");
1322 }
1323
1324 // Filter out some microsoft extensions when trying to parse in ms-compat
1325 // mode.
1326 if (LangOpts.Microsoft) {
1327 DefineBuiltinMacro(Buf, "_cdecl=__cdecl");
1328 DefineBuiltinMacro(Buf, "__int8=__INT8_TYPE__");
1329 DefineBuiltinMacro(Buf, "__int16=__INT16_TYPE__");
1330 DefineBuiltinMacro(Buf, "__int32=__INT32_TYPE__");
1331 DefineBuiltinMacro(Buf, "__int64=__INT64_TYPE__");
1332 }
1333
1334 if (LangOpts.Optimize)
1335 DefineBuiltinMacro(Buf, "__OPTIMIZE__=1");
1336 if (LangOpts.OptimizeSize)
1337 DefineBuiltinMacro(Buf, "__OPTIMIZE_SIZE__=1");
1338
1339 // Initialize target-specific preprocessor defines.
1340
1341 // Define type sizing macros based on the target properties.
1342 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
1343 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
1344
1345 unsigned IntMaxWidth;
1346 const char *IntMaxSuffix;
1347 if (TI.getIntMaxType() == TargetInfo::SignedLongLong) {
1348 IntMaxWidth = TI.getLongLongWidth();
1349 IntMaxSuffix = "LL";
1350 } else if (TI.getIntMaxType() == TargetInfo::SignedLong) {
1351 IntMaxWidth = TI.getLongWidth();
1352 IntMaxSuffix = "L";
1353 } else {
1354 assert(TI.getIntMaxType() == TargetInfo::SignedInt);
1355 IntMaxWidth = TI.getIntWidth();
1356 IntMaxSuffix = "";
1357 }
1358
1359 DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Buf);
1360 DefineTypeSize("__SHRT_MAX__", TI.getShortWidth(), "", true, Buf);
1361 DefineTypeSize("__INT_MAX__", TI.getIntWidth(), "", true, Buf);
1362 DefineTypeSize("__LONG_MAX__", TI.getLongWidth(), "L", true, Buf);
1363 DefineTypeSize("__LONG_LONG_MAX__", TI.getLongLongWidth(), "LL", true, Buf);
1364 DefineTypeSize("__WCHAR_MAX__", TI.getWCharWidth(), "", true, Buf);
1365 DefineTypeSize("__INTMAX_MAX__", IntMaxWidth, IntMaxSuffix, true, Buf);
1366
1367 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Buf);
1368 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Buf);
1369 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Buf);
1370 DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Buf);
1371 DefineType("__SIZE_TYPE__", TI.getSizeType(), Buf);
1372 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Buf);
1373 // FIXME: TargetInfo hookize __WINT_TYPE__.
1374 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
1375
1376 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
1377 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
1378 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
1379
1380 // Define a __POINTER_WIDTH__ macro for stdint.h.
1381 sprintf(MacroBuf, "__POINTER_WIDTH__=%d", (int)TI.getPointerWidth(0));
1382 DefineBuiltinMacro(Buf, MacroBuf);
1383
1384 if (!TI.isCharSigned())
1385 DefineBuiltinMacro(Buf, "__CHAR_UNSIGNED__");
1386
1387 // Define fixed-sized integer types for stdint.h
1388 assert(TI.getCharWidth() == 8 && "unsupported target types");
1389 assert(TI.getShortWidth() == 16 && "unsupported target types");
1390 DefineBuiltinMacro(Buf, "__INT8_TYPE__=char");
1391 DefineBuiltinMacro(Buf, "__INT16_TYPE__=short");
1392
1393 if (TI.getIntWidth() == 32)
1394 DefineBuiltinMacro(Buf, "__INT32_TYPE__=int");
1395 else {
1396 assert(TI.getLongLongWidth() == 32 && "unsupported target types");
1397 DefineBuiltinMacro(Buf, "__INT32_TYPE__=long long");
1398 }
1399
1400 // 16-bit targets doesn't necessarily have a 64-bit type.
1401 if (TI.getLongLongWidth() == 64)
1402 DefineBuiltinMacro(Buf, "__INT64_TYPE__=long long");
1403
1404 // Add __builtin_va_list typedef.
1405 {
1406 const char *VAList = TI.getVAListDeclaration();
1407 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
1408 Buf.push_back('\n');
1409 }
1410
1411 if (const char *Prefix = TI.getUserLabelPrefix()) {
1412 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
1413 DefineBuiltinMacro(Buf, MacroBuf);
1414 }
1415
1416 // Build configuration options. FIXME: these should be controlled by
1417 // command line options or something.
1418 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
1419
1420 if (LangOpts.Static)
1421 DefineBuiltinMacro(Buf, "__STATIC__=1");
1422 else
1423 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
1424
1425 if (LangOpts.GNUInline)
1426 DefineBuiltinMacro(Buf, "__GNUC_GNU_INLINE__=1");
1427 else
1428 DefineBuiltinMacro(Buf, "__GNUC_STDC_INLINE__=1");
1429
1430 if (LangOpts.NoInline)
1431 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
1432
1433 if (unsigned PICLevel = LangOpts.PICLevel) {
1434 sprintf(MacroBuf, "__PIC__=%d", PICLevel);
1435 DefineBuiltinMacro(Buf, MacroBuf);
1436
1437 sprintf(MacroBuf, "__pic__=%d", PICLevel);
1438 DefineBuiltinMacro(Buf, MacroBuf);
1439 }
1440
1441 // Macros to control C99 numerics and <float.h>
1442 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
1443 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
1444 sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
1445 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33));
1446 DefineBuiltinMacro(Buf, MacroBuf);
1447
1448 // Get other target #defines.
1449 TI.getTargetDefines(LangOpts, Buf);
1450}
1451
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001452static bool InitializeSourceManager(Preprocessor &PP,
1453 const std::string &InFile) {
1454 // Figure out where to get and map in the main file.
1455 SourceManager &SourceMgr = PP.getSourceManager();
1456 FileManager &FileMgr = PP.getFileManager();
1457
1458 if (InFile != "-") {
1459 const FileEntry *File = FileMgr.getFile(InFile);
1460 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1461 if (SourceMgr.getMainFileID().isInvalid()) {
1462 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1463 << InFile.c_str();
1464 return true;
1465 }
1466 } else {
1467 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1468
1469 // If stdin was empty, SB is null. Cons up an empty memory
1470 // buffer now.
1471 if (!SB) {
1472 const char *EmptyStr = "";
1473 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1474 }
1475
1476 SourceMgr.createMainFileIDForMemBuffer(SB);
1477 if (SourceMgr.getMainFileID().isInvalid()) {
1478 PP.getDiagnostics().Report(FullSourceLoc(),
1479 diag::err_fe_error_reading_stdin);
1480 return true;
1481 }
1482 }
1483
1484 return false;
1485}
1486
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001487/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +00001488/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001489///
Chris Lattner9d818a22008-04-19 23:25:44 +00001490static bool InitializePreprocessor(Preprocessor &PP,
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001491 const std::string &InFile) {
Chris Lattner47b6a162008-04-19 23:09:31 +00001492 std::vector<char> PredefineBuffer;
Chris Lattnera9a0dd52009-04-10 21:58:23 +00001493
1494 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
1495 InitializePredefinedMacros(PP.getTargetInfo(), PP.getLangOptions(),
1496 PredefineBuffer);
1497
1498 // Add on the predefines from the driver. Wrap in a #line directive to report
1499 // that they come from the command line.
1500 const char *LineDirective = "# 1 \"<command line>\" 1\n";
1501 PredefineBuffer.insert(PredefineBuffer.end(),
1502 LineDirective, LineDirective+strlen(LineDirective));
1503
Chris Lattner47b6a162008-04-19 23:09:31 +00001504
Chris Lattner4b009652007-07-25 00:24:17 +00001505 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +00001506 unsigned d = 0, D = D_macros.size();
1507 unsigned u = 0, U = U_macros.size();
1508 while (d < D || u < U) {
1509 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1510 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
1511 else
1512 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
1513 }
1514
Chris Lattnerb62396d2009-04-08 20:15:42 +00001515 // If -imacros are specified, include them now. These are processed before
1516 // any -include directives.
1517
1518 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1519 AddImplicitIncludeMacros(PredefineBuffer, ImplicitMacroIncludes[i]);
Chris Lattner008da782008-01-10 01:53:41 +00001520
Chris Lattnerb62396d2009-04-08 20:15:42 +00001521 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) {
1522 // We want to add these paths to the predefines buffer in order, make a
1523 // temporary vector to sort by their occurrence.
Chris Lattner0e004a12009-04-08 18:24:34 +00001524 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1525
1526 if (!ImplicitIncludePTH.empty())
1527 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1528 &ImplicitIncludePTH));
1529 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1530 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1531 &ImplicitIncludes[i]));
Chris Lattner0e004a12009-04-08 18:24:34 +00001532 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1533
1534 // Now that they are ordered by position, add to the predefines buffer.
1535 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1536 std::string *Ptr = OrderedPaths[i].second;
1537 if (!ImplicitIncludes.empty() &&
1538 Ptr >= &ImplicitIncludes[0] &&
1539 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1540 AddImplicitInclude(PredefineBuffer, *Ptr);
Chris Lattner0e004a12009-04-08 18:24:34 +00001541 } else {
Chris Lattnerb62396d2009-04-08 20:15:42 +00001542 assert(Ptr == &ImplicitIncludePTH);
1543 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner0e004a12009-04-08 18:24:34 +00001544 }
1545 }
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001546 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001547
Chris Lattnera9a0dd52009-04-10 21:58:23 +00001548 LineDirective = "# 2 \"<built-in>\" 2\n";
1549 PredefineBuffer.insert(PredefineBuffer.end(),
1550 LineDirective, LineDirective+strlen(LineDirective));
1551
Chris Lattner47b6a162008-04-19 23:09:31 +00001552 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001553 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +00001554 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001555
1556 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +00001557 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001558}
1559
1560//===----------------------------------------------------------------------===//
1561// Preprocessor include path information.
1562//===----------------------------------------------------------------------===//
1563
1564// This tool exports a large number of command line options to control how the
1565// preprocessor searches for header files. At root, however, the Preprocessor
1566// object takes a very simple interface: a list of directories to search for
1567//
1568// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001569// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001570//
Chris Lattner4b009652007-07-25 00:24:17 +00001571
1572static llvm::cl::opt<bool>
1573nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1574
1575// Various command line options. These four add directories to each chain.
1576static llvm::cl::list<std::string>
1577F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1578 llvm::cl::desc("Add directory to framework include search path"));
1579static llvm::cl::list<std::string>
1580I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1581 llvm::cl::desc("Add directory to include search path"));
1582static llvm::cl::list<std::string>
1583idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1584 llvm::cl::desc("Add directory to AFTER include search path"));
1585static llvm::cl::list<std::string>
1586iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1587 llvm::cl::desc("Add directory to QUOTE include search path"));
1588static llvm::cl::list<std::string>
1589isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1590 llvm::cl::desc("Add directory to SYSTEM include search path"));
1591
1592// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1593static llvm::cl::list<std::string>
1594iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1595 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1596static llvm::cl::list<std::string>
1597iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1598 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1599static llvm::cl::list<std::string>
1600iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1601 llvm::cl::Prefix,
1602 llvm::cl::desc("Set directory to include search path with prefix"));
1603
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001604static llvm::cl::opt<std::string>
1605isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1606 llvm::cl::desc("Set the system root directory (usually /)"));
1607
Chris Lattner4b009652007-07-25 00:24:17 +00001608// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001609
Chris Lattner4b009652007-07-25 00:24:17 +00001610/// InitializeIncludePaths - Process the -I options and set them in the
1611/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001612void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1613 FileManager &FM, const LangOptions &Lang) {
1614 InitHeaderSearch Init(Headers, Verbose, isysroot);
1615
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001616 // Handle -I... and -F... options, walking the lists in parallel.
1617 unsigned Iidx = 0, Fidx = 0;
1618 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1619 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001620 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001621 ++Iidx;
1622 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001623 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001624 ++Fidx;
1625 }
1626 }
Chris Lattner4b009652007-07-25 00:24:17 +00001627
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001628 // Consume what's left from whatever list was longer.
1629 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001630 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001631 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001632 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001633
1634 // Handle -idirafter... options.
1635 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001636 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1637 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001638
1639 // Handle -iquote... options.
1640 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001641 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001642
1643 // Handle -isystem... options.
1644 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001645 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001646
1647 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1648 // parallel, processing the values in order of occurance to get the right
1649 // prefixes.
1650 {
1651 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1652 unsigned iprefix_idx = 0;
1653 unsigned iwithprefix_idx = 0;
1654 unsigned iwithprefixbefore_idx = 0;
1655 bool iprefix_done = iprefix_vals.empty();
1656 bool iwithprefix_done = iwithprefix_vals.empty();
1657 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1658 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1659 if (!iprefix_done &&
1660 (iwithprefix_done ||
1661 iprefix_vals.getPosition(iprefix_idx) <
1662 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1663 (iwithprefixbefore_done ||
1664 iprefix_vals.getPosition(iprefix_idx) <
1665 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1666 Prefix = iprefix_vals[iprefix_idx];
1667 ++iprefix_idx;
1668 iprefix_done = iprefix_idx == iprefix_vals.size();
1669 } else if (!iwithprefix_done &&
1670 (iwithprefixbefore_done ||
1671 iwithprefix_vals.getPosition(iwithprefix_idx) <
1672 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001673 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1674 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001675 ++iwithprefix_idx;
1676 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1677 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001678 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1679 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001680 ++iwithprefixbefore_idx;
1681 iwithprefixbefore_done =
1682 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1683 }
1684 }
1685 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001686
Nico Weber770e3882008-08-22 09:25:22 +00001687 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001688
Daniel Dunbar4e604292009-02-21 20:52:41 +00001689 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001690 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001691 llvm::sys::Path::GetMainExecutable(Argv0,
1692 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001693 if (!MainExecutablePath.isEmpty()) {
1694 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1695 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001696
1697 // Get foo/lib/clang/1.0/include
1698 //
1699 // FIXME: Don't embed version here.
1700 MainExecutablePath.appendComponent("lib");
1701 MainExecutablePath.appendComponent("clang");
1702 MainExecutablePath.appendComponent("1.0");
1703 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001704
1705 // We pass true to ignore sysroot so that we *always* look for clang headers
1706 // relative to our executable, never relative to -isysroot.
1707 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1708 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001709 }
1710
Nico Weber770e3882008-08-22 09:25:22 +00001711 if (!nostdinc)
1712 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001713
1714 // Now that we have collected all of the include paths, merge them all
1715 // together and tell the preprocessor about them.
1716
Nico Weber770e3882008-08-22 09:25:22 +00001717 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001718}
1719
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001720//===----------------------------------------------------------------------===//
1721// Driver PreprocessorFactory - For lazily generating preprocessors ...
1722//===----------------------------------------------------------------------===//
1723
1724namespace {
1725class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001726 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001727 Diagnostic &Diags;
1728 const LangOptions &LangInfo;
1729 TargetInfo &Target;
1730 SourceManager &SourceMgr;
1731 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001732
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001733public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001734 DriverPreprocessorFactory(const std::string &infile,
1735 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001736 TargetInfo &target, SourceManager &SM,
1737 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001738 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001739 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001740
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001741
1742 virtual ~DriverPreprocessorFactory() {}
1743
1744 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001745 llvm::OwningPtr<PTHManager> PTHMgr;
1746
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001747 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1748 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1749 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001750 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001751 }
1752
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001753 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001754 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1755 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001756 PTHMgr.reset(PTHManager::Create(x, &Diags,
1757 TokenCache.empty() ? Diagnostic::Error
1758 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001759 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001760
Ted Kremenek6348cc62009-03-22 06:42:39 +00001761 if (Diags.hasErrorOccurred())
1762 exit(1);
1763
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001764 // Create the Preprocessor.
1765 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1766 SourceMgr, HeaderInfo,
1767 PTHMgr.get()));
1768
1769 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1770 // That argument is used as the IdentifierInfoLookup argument to
1771 // IdentifierTable's ctor.
1772 if (PTHMgr) {
1773 PTHMgr->setPreprocessor(PP.get());
1774 PP->setPTHManager(PTHMgr.take());
1775 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001776
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001777 if (InitializePreprocessor(*PP, InFile))
1778 return 0;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001779
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001780 /// FIXME: PP can only handle one callback
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001781 if (ProgAction != PrintPreprocessedInput) {
1782 std::string ErrStr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001783 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001784 if (!DFG && !ErrStr.empty()) {
1785 fprintf(stderr, "%s", ErrStr.c_str());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001786 return 0;
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001787 }
1788 }
1789
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001790 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001791 }
1792};
1793}
Chris Lattner4b009652007-07-25 00:24:17 +00001794
Chris Lattner4b009652007-07-25 00:24:17 +00001795//===----------------------------------------------------------------------===//
1796// Basic Parser driver
1797//===----------------------------------------------------------------------===//
1798
Chris Lattner9d818a22008-04-19 23:25:44 +00001799static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001800 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001801 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001802
1803 // Parsing the specified input file.
1804 P.ParseTranslationUnit();
1805 delete PA;
1806}
1807
1808//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001809// Code generation options
1810//===----------------------------------------------------------------------===//
1811
1812static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001813GenerateDebugInfo("g",
1814 llvm::cl::desc("Generate source level debug information"));
1815
Daniel Dunbar9101a632009-02-17 19:47:34 +00001816static llvm::cl::opt<std::string>
1817TargetCPU("mcpu",
1818 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1819
Chris Lattner8a9615c2009-03-16 18:41:18 +00001820static void InitializeCompileOptions(CompileOptions &Opts,
1821 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001822 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001823 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001824 if (OptSize) {
1825 // -Os implies -O2
1826 // FIXME: Diagnose conflicting options.
1827 Opts.OptimizationLevel = 2;
1828 } else {
1829 Opts.OptimizationLevel = OptLevel;
1830 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001831
1832 // FIXME: There are llvm-gcc options to control these selectively.
1833 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1834 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001835 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001836
1837#ifdef NDEBUG
1838 Opts.VerifyModule = 0;
1839#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001840
1841 Opts.CPU = TargetCPU;
1842 Opts.Features.insert(Opts.Features.end(),
1843 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001844
Chris Lattnerf04a7562009-03-26 05:00:52 +00001845 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1846
Chris Lattnere8f70712009-02-18 01:23:44 +00001847 // Handle -ftime-report.
1848 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001849}
1850
1851//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001852// Fix-It Options
1853//===----------------------------------------------------------------------===//
1854static llvm::cl::list<ParsedSourceLocation>
1855FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1856 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1857
1858//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001859// -dump-build-information Stuff
1860//===----------------------------------------------------------------------===//
1861
1862static llvm::cl::opt<std::string>
1863DumpBuildInformation("dump-build-information",
1864 llvm::cl::value_desc("filename"),
1865 llvm::cl::desc("output a dump of some build information to a file"));
1866
1867static llvm::raw_ostream *BuildLogFile = 0;
1868
1869/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1870/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1871namespace {
1872class LoggingDiagnosticClient : public DiagnosticClient {
1873 llvm::OwningPtr<DiagnosticClient> Chain1;
1874 llvm::OwningPtr<DiagnosticClient> Chain2;
1875public:
1876
1877 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1878 // Output diags both where requested...
1879 Chain1.reset(Normal);
1880 // .. and to our log file.
1881 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1882 !NoShowColumn,
1883 !NoCaretDiagnostics,
1884 !NoShowLocation,
1885 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001886 PrintDiagnosticOption,
1887 !NoDiagnosticsFixIt));
Chris Lattner94859302009-04-17 21:05:01 +00001888 }
1889
1890 virtual void setLangOptions(const LangOptions *LO) {
1891 Chain1->setLangOptions(LO);
1892 Chain2->setLangOptions(LO);
1893 }
1894
1895 virtual bool IncludeInDiagnosticCounts() const {
1896 return Chain1->IncludeInDiagnosticCounts();
1897 }
1898
1899 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1900 const DiagnosticInfo &Info) {
1901 Chain1->HandleDiagnostic(DiagLevel, Info);
1902 Chain2->HandleDiagnostic(DiagLevel, Info);
1903 }
1904};
1905} // end anonymous namespace.
1906
1907static void SetUpBuildDumpLog(unsigned argc, char **argv,
1908 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1909
1910 std::string ErrorInfo;
1911 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1912 ErrorInfo);
1913
1914 if (!ErrorInfo.empty()) {
1915 llvm::errs() << "error opening -dump-build-information file '"
1916 << DumpBuildInformation << "', option ignored!\n";
1917 delete BuildLogFile;
1918 BuildLogFile = 0;
1919 DumpBuildInformation = "";
1920 return;
1921 }
1922
1923 (*BuildLogFile) << "clang-cc command line arguments: ";
1924 for (unsigned i = 0; i != argc; ++i)
1925 (*BuildLogFile) << argv[i] << ' ';
1926 (*BuildLogFile) << '\n';
1927
1928 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1929 // the diagnostic producers and the normal receiver.
1930 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1931}
1932
1933
1934
1935//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001936// Main driver
1937//===----------------------------------------------------------------------===//
1938
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001939/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001940/// action. These consumers can operate on both ASTs that are freshly
1941/// parsed from source files as well as those deserialized from Bitcode.
1942/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001943static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001944 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001945 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001946 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001947 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001948 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001949 default:
1950 return NULL;
1951
1952 case ASTPrint:
1953 return CreateASTPrinter();
1954
1955 case ASTDump:
1956 return CreateASTDumper();
1957
1958 case ASTView:
1959 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001960
Chris Lattner7f902922009-02-18 01:20:05 +00001961 case PrintDeclContext:
1962 return CreateDeclContextPrinter();
1963
1964 case EmitHTML:
1965 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001966
Chris Lattner7f902922009-02-18 01:20:05 +00001967 case InheritanceView:
1968 return CreateInheritanceViewer(InheritanceViewCls);
1969
1970 case TestSerialization:
1971 return CreateSerializationTest(Diag, FileMgr);
1972
1973 case EmitAssembly:
1974 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001975 case EmitBC:
1976 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001977 BackendAction Act;
1978 if (ProgAction == EmitAssembly)
1979 Act = Backend_EmitAssembly;
1980 else if (ProgAction == EmitLLVM)
1981 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001982 else if (ProgAction == EmitLLVMOnly)
1983 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001984 else
1985 Act = Backend_EmitBC;
1986
1987 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001988 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001989 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001990 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001991 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001992
Chris Lattner7f902922009-02-18 01:20:05 +00001993 case SerializeAST:
1994 // FIXME: Allow user to tailor where the file is written.
1995 return CreateASTSerializer(InFile, OutputFile, Diag);
1996
Douglas Gregorc34897d2009-04-09 22:27:44 +00001997 case GeneratePCH:
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001998 assert(PP && "Generate PCH doesn't work from serialized file yet");
1999 return CreatePCHGenerator(*PP, OutputFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +00002000
Chris Lattner7f902922009-02-18 01:20:05 +00002001 case RewriteObjC:
2002 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00002003
Chris Lattner7f902922009-02-18 01:20:05 +00002004 case RewriteBlocks:
2005 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
2006
2007 case RunAnalysis:
2008 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00002009 }
2010}
2011
Chris Lattner4b009652007-07-25 00:24:17 +00002012/// ProcessInputFile - Process a single input file with the specified state.
2013///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00002014static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00002015 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00002016 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00002017 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00002018 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00002019 bool CompleteTranslationUnit = true;
Douglas Gregor133d2552009-04-02 01:08:08 +00002020
Ted Kremenek71c6cc62008-10-21 00:54:44 +00002021 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00002022 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00002023 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
2024 PP.getFileManager(), PP.getLangOptions(),
2025 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00002026
2027 if (!Consumer) {
2028 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002029 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00002030 return;
2031 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00002032
Douglas Gregore0d5c562009-04-14 16:27:31 +00002033 if (ProgAction == GeneratePCH)
2034 CompleteTranslationUnit = false;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00002035 break;
2036
Chris Lattneraf669fb2008-10-12 05:03:36 +00002037 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00002038 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00002039 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00002040 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00002041 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00002042 RawLex.SetKeepWhitespaceMode(true);
2043
2044 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00002045 RawLex.LexFromRawLexer(RawTok);
2046 while (RawTok.isNot(tok::eof)) {
2047 PP.DumpToken(RawTok, true);
2048 fprintf(stderr, "\n");
2049 RawLex.LexFromRawLexer(RawTok);
2050 }
2051 ClearSourceMgr = true;
2052 break;
2053 }
Chris Lattner4b009652007-07-25 00:24:17 +00002054 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00002055 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00002056 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00002057 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00002058 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00002059 do {
2060 PP.Lex(Tok);
2061 PP.DumpToken(Tok, true);
2062 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00002063 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00002064 ClearSourceMgr = true;
2065 break;
2066 }
2067 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00002068 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00002069 Token Tok;
2070 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00002071 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00002072 do {
2073 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00002074 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00002075 ClearSourceMgr = true;
2076 break;
2077 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00002078
Douglas Gregor2a0e8742009-04-02 23:43:50 +00002079 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00002080 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00002081 CacheTokens(PP, OutputFile);
2082 ClearSourceMgr = true;
2083 break;
2084 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002085
Chris Lattnerefe33382009-02-18 01:51:21 +00002086 case PrintPreprocessedInput: { // -E mode.
2087 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00002088 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00002089 ClearSourceMgr = true;
2090 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002091 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00002092
Chris Lattnerefe33382009-02-18 01:51:21 +00002093 case ParseNoop: { // -parse-noop
2094 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00002095 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00002096 ClearSourceMgr = true;
2097 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002098 }
Chris Lattner4b009652007-07-25 00:24:17 +00002099
Chris Lattnerefe33382009-02-18 01:51:21 +00002100 case ParsePrintCallbacks: {
2101 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00002102 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00002103 ClearSourceMgr = true;
2104 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002105 }
2106
2107 case ParseSyntaxOnly: { // -fsyntax-only
2108 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00002109 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00002110 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002111 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00002112
2113 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00002114 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00002115 ClearSourceMgr = true;
2116 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00002117
Chris Lattnerefe33382009-02-18 01:51:21 +00002118 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00002119 DoRewriteTest(PP, InFile, OutputFile);
2120 ClearSourceMgr = true;
2121 break;
Chris Lattner129758d2007-09-16 19:46:59 +00002122 }
Douglas Gregor133d2552009-04-02 01:08:08 +00002123
2124 case FixIt:
2125 llvm::TimeRegion Timer(ClangFrontendTimer);
2126 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00002127 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00002128 PP.getSourceManager(),
2129 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00002130 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002131 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00002132
2133 if (Consumer) {
Chris Lattner143fd6d2009-03-28 01:37:17 +00002134 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner143fd6d2009-03-28 01:37:17 +00002135
Douglas Gregor24b48b02009-04-02 19:05:20 +00002136 if (FixItAtLocations.size() > 0) {
2137 // Even without the "-fixit" flag, with may have some specific
2138 // locations where the user has requested fixes. Process those
2139 // locations now.
2140 if (!FixItRewrite)
2141 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00002142 PP.getSourceManager(),
2143 PP.getLangOptions());
Douglas Gregor24b48b02009-04-02 19:05:20 +00002144
2145 bool AddedFixitLocation = false;
2146 for (unsigned Idx = 0, Last = FixItAtLocations.size();
2147 Idx != Last; ++Idx) {
2148 RequestedSourceLocation Requested;
2149 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
2150 Requested)) {
2151 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
2152 FixItAtLocations[Idx].FileName.c_str());
2153 } else {
2154 FixItRewrite->addFixItLocation(Requested);
2155 AddedFixitLocation = true;
2156 }
2157 }
2158
2159 if (!AddedFixitLocation) {
2160 // All of the fix-it locations were bad. Don't fix anything.
2161 delete FixItRewrite;
2162 FixItRewrite = 0;
2163 }
2164 }
2165
Chris Lattner143fd6d2009-03-28 01:37:17 +00002166 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
2167 PP.getSourceManager(),
2168 PP.getTargetInfo(),
2169 PP.getIdentifierTable(),
2170 PP.getSelectorTable(),
2171 /* FreeMemory = */ !DisableFree));
Chris Lattner143fd6d2009-03-28 01:37:17 +00002172
Douglas Gregorc34897d2009-04-09 22:27:44 +00002173 if (!ImplicitIncludePCH.empty()) {
2174 // The user has asked us to include a precompiled header. Load
2175 // the precompiled header into the AST context.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002176 llvm::OwningPtr<PCHReader> Reader(new PCHReader(PP, *ContextOwner.get()));
2177 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
2178 case PCHReader::Success: {
2179 // Attach the PCH reader to the AST context as an external AST
2180 // source, so that declarations will be deserialized from the
2181 // PCH file as needed.
2182 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
2183 ContextOwner->setExternalSource(Source);
2184
2185 // Clear out the predefines buffer, because all of the
2186 // predefines are already in the PCH file.
2187 PP.setPredefines("");
2188 break;
2189 }
2190
2191 case PCHReader::Failure:
2192 // Unrecoverable failure: don't even try to process the input
2193 // file.
Douglas Gregorc34897d2009-04-09 22:27:44 +00002194 return;
2195
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002196 case PCHReader::IgnorePCH:
2197 // No suitable PCH file could be found. Just ignore the
2198 // -include-pch option entirely.
2199 break;
2200 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00002201
2202 // Finish preprocessor initialization. We do this now (rather
2203 // than earlier) because this initialization creates new source
2204 // location entries in the source manager, which must come after
2205 // the source location entries for the PCH file.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002206 if (InitializeSourceManager(PP, InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002207 return;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002208 }
2209
Douglas Gregore0d5c562009-04-14 16:27:31 +00002210 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2211 CompleteTranslationUnit);
Chris Lattner143fd6d2009-03-28 01:37:17 +00002212
Douglas Gregor133d2552009-04-02 01:08:08 +00002213 if (FixItRewrite)
2214 FixItRewrite->WriteFixedFile(InFile, OutputFile);
2215
Chris Lattner143fd6d2009-03-28 01:37:17 +00002216 // If in -disable-free mode, don't deallocate these when they go out of
2217 // scope.
Chris Lattner07b08c02009-03-28 04:13:34 +00002218 if (DisableFree)
Chris Lattner143fd6d2009-03-28 01:37:17 +00002219 ContextOwner.take();
Ted Kremenek88eebed2009-01-28 04:29:29 +00002220 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002221
2222 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002223 if (CheckDiagnostics(PP))
2224 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00002225
Chris Lattner4b009652007-07-25 00:24:17 +00002226 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00002227 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00002228 PP.PrintStats();
2229 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00002230 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00002231 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00002232 fprintf(stderr, "\n");
2233 }
2234
2235 // For a multi-file compilation, some things are ok with nuking the source
2236 // manager tables, other require stable fileid/macroid's across multiple
2237 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00002238 if (ClearSourceMgr)
2239 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00002240
2241 if (DisableFree)
2242 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00002243}
2244
Ted Kremenek80d53372007-12-12 23:41:08 +00002245static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
2246 FileManager& FileMgr) {
2247
2248 if (VerifyDiagnostics) {
2249 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
2250 exit (1);
2251 }
2252
2253 llvm::sys::Path Filename(InFile);
2254
2255 if (!Filename.isValid()) {
2256 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
2257 exit (1);
2258 }
2259
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002260 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner06459ae2009-03-28 03:49:26 +00002261
2262 // Create the memory buffer that contains the contents of the file.
2263 llvm::OwningPtr<llvm::MemoryBuffer>
2264 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
2265
2266 if (MBuffer)
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002267 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00002268
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002269 if (!Ctx) {
Ted Kremenek2bd42412007-12-13 18:11:11 +00002270 fprintf(stderr, "error: file '%s' could not be deserialized\n",
2271 InFile.c_str());
2272 exit (1);
2273 }
2274
Ted Kremenekab749372007-12-19 19:27:38 +00002275 // Observe that we use the source file name stored in the deserialized
2276 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00002277 llvm::OwningPtr<ASTConsumer>
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002278 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00002279 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00002280
Ted Kremenek80d53372007-12-12 23:41:08 +00002281 if (!Consumer) {
2282 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
2283 exit (1);
2284 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00002285
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002286 Consumer->Initialize(*Ctx);
Nico Weberd2a6ac92008-08-10 19:59:06 +00002287
Chris Lattner8d72ee02008-02-06 01:42:25 +00002288 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002289 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002290 for (DeclContext::decl_iterator I = TUD->decls_begin(*Ctx),
2291 E = TUD->decls_end(*Ctx);
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002292 I != E; ++I)
Chris Lattnera17991f2009-03-29 16:50:03 +00002293 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek80d53372007-12-12 23:41:08 +00002294}
2295
2296
Chris Lattner4b009652007-07-25 00:24:17 +00002297static llvm::cl::list<std::string>
2298InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2299
Ted Kremenek80d53372007-12-12 23:41:08 +00002300static bool isSerializedFile(const std::string& InFile) {
2301 if (InFile.size() < 4)
2302 return false;
2303
2304 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00002305 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00002306}
2307
Chris Lattner4b009652007-07-25 00:24:17 +00002308
2309int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00002310 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00002311 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00002312 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00002313 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00002314
Chris Lattnerefe33382009-02-18 01:51:21 +00002315 if (TimeReport)
2316 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2317
Chris Lattner4b009652007-07-25 00:24:17 +00002318 // If no input was specified, read from stdin.
2319 if (InputFilenames.empty())
2320 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00002321
Ted Kremenekb240e822007-12-11 23:28:38 +00002322 // Create the diagnostic client for reporting errors or for
2323 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00002324 llvm::OwningPtr<DiagnosticClient> DiagClient;
2325 if (VerifyDiagnostics) {
2326 // When checking diagnostics, just buffer them up.
2327 DiagClient.reset(new TextDiagnosticBuffer());
2328 if (InputFilenames.size() != 1) {
2329 fprintf(stderr, "-verify only works on single input files for now.\n");
2330 return 1;
2331 }
2332 if (!HTMLDiag.empty()) {
2333 fprintf(stderr, "-verify and -html-diags don't work together\n");
2334 return 1;
2335 }
2336 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00002337 // Print diagnostics to stderr by default.
Chris Lattner5f7937d2009-04-17 20:40:01 +00002338 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00002339 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00002340 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00002341 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00002342 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00002343 PrintDiagnosticOption,
2344 !NoDiagnosticsFixIt));
Ted Kremenek5c341732008-08-07 17:49:57 +00002345 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00002346 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00002347 }
Chris Lattner94859302009-04-17 21:05:01 +00002348
2349 if (!DumpBuildInformation.empty()) {
2350 if (!HTMLDiag.empty()) {
2351 fprintf(stderr,
2352 "-dump-build-information and -html-diags don't work together\n");
2353 return 1;
2354 }
2355
2356 SetUpBuildDumpLog(argc, argv, DiagClient);
2357 }
2358
Ted Kremenek5c341732008-08-07 17:49:57 +00002359
Chris Lattner4b009652007-07-25 00:24:17 +00002360 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00002361 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002362 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00002363 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00002364
Chris Lattner45a56e02007-12-05 23:24:17 +00002365 // -I- is a deprecated GCC feature, scan for it and reject it.
2366 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2367 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00002368 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00002369 I_dirs.erase(I_dirs.begin()+i);
2370 --i;
2371 }
2372 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002373
2374 // Get information about the target being compiled for.
2375 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00002376 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2377
Chris Lattner2c77d852008-03-14 06:12:05 +00002378 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00002379 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2380 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002381 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00002382 }
Chris Lattner45a56e02007-12-05 23:24:17 +00002383
Daniel Dunbar9c321102009-01-20 23:17:32 +00002384 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00002385 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00002386
Ted Kremenek2a4224a2008-06-06 22:42:39 +00002387 llvm::OwningPtr<SourceManager> SourceMgr;
2388
Chris Lattnere1be6022009-04-14 23:22:57 +00002389 // Create a file manager object to provide access to and cache the filesystem.
2390 FileManager FileMgr;
2391
Chris Lattner4b009652007-07-25 00:24:17 +00002392 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00002393 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00002394
Ted Kremenek5c341732008-08-07 17:49:57 +00002395 if (isSerializedFile(InFile)) {
Ted Kremenek80d53372007-12-12 23:41:08 +00002396 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00002397 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002398 }
Chris Lattner2b989562009-03-04 21:40:56 +00002399
2400 /// Create a SourceManager object. This tracks and owns all the file
2401 /// buffers allocated to a translation unit.
2402 if (!SourceMgr)
2403 SourceMgr.reset(new SourceManager());
2404 else
2405 SourceMgr->clearIDTables();
2406
2407 // Initialize language options, inferring file types from input filenames.
2408 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00002409 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00002410
Chris Lattner2b989562009-03-04 21:40:56 +00002411 InitializeBaseLanguage();
2412 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002413 InitializeLangOptions(LangInfo, LK);
Chris Lattner2b989562009-03-04 21:40:56 +00002414 InitializeLanguageStandard(LangInfo, LK, Target.get());
2415
2416 // Process the -I options and set them in the HeaderInfo.
2417 HeaderSearch HeaderInfo(FileMgr);
2418
Chris Lattnere1be6022009-04-14 23:22:57 +00002419
Chris Lattner2b989562009-03-04 21:40:56 +00002420 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2421
2422 // Set up the preprocessor with these options.
2423 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
2424 *SourceMgr.get(), HeaderInfo);
2425
2426 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2427
2428 if (!PP)
2429 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002430
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002431 if (ImplicitIncludePCH.empty() &&
2432 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002433 continue;
2434
Chris Lattner5f7937d2009-04-17 20:40:01 +00002435 if (!HTMLDiag.empty())
2436 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00002437
2438 // Process the source file.
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002439 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattner2b989562009-03-04 21:40:56 +00002440
Chris Lattner2961dc52009-04-17 20:16:08 +00002441 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00002442 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00002443 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002444
Mike Stump91d01352009-01-28 02:43:35 +00002445 if (Verbose)
2446 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2447 " hosted on " LLVM_HOSTTRIPLE "\n");
2448
Ted Kremenekec6c5252008-08-07 18:13:12 +00002449 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00002450 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2451 (NumDiagnostics == 1 ? "" : "s"));
2452
2453 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002454 FileMgr.PrintStats();
2455 fprintf(stderr, "\n");
2456 }
Chris Lattner94859302009-04-17 21:05:01 +00002457
2458 delete ClangFrontendTimer;
2459 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002460
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002461 // If verifying diagnostics and we reached here, all is well.
2462 if (VerifyDiagnostics)
2463 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002464
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002465 // Managed static deconstruction. Useful for making things like
2466 // -time-passes usable.
2467 llvm::llvm_shutdown();
2468
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002469 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002470}