blob: 0e0a07275892196eef8499cd9a4f9380d3e38628 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Eli Friedman0ec78fa2009-05-19 21:10:40 +000025#include "clang/Frontend/AnalysisConsumer.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000026#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattnere116ccf2009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000036#include "clang/Frontend/Utils.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000037#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000038#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000039#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000040#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000041#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000042#include "clang/AST/ASTContext.h"
43#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000044#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045#include "clang/Parse/Parser.h"
46#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000047#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000048#include "clang/Basic/FileManager.h"
49#include "clang/Basic/SourceManager.h"
50#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000051#include "clang/Basic/Version.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000052#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000053#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000055#include "llvm/ADT/StringMap.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000056#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000057#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000058#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000059#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000060#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000061#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000062#include "llvm/Support/PrettyStackTrace.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000063#include "llvm/Support/Streams.h"
Chris Lattner47099742009-02-18 01:51:21 +000064#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000065#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000066#include "llvm/System/Path.h"
Douglas Gregor44cf08e2009-05-03 03:52:38 +000067#include "llvm/System/Process.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000068#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000069#include "llvm/System/Signals.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000070#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000071#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000072# include <sys/types.h>
73#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000074
Reid Spencer5f016e22007-07-11 17:01:13 +000075using namespace clang;
76
77//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000078// Source Location Parser
79//===----------------------------------------------------------------------===//
80
81/// \brief A source location that has been parsed on the command line.
82struct ParsedSourceLocation {
83 std::string FileName;
84 unsigned Line;
85 unsigned Column;
86
87 /// \brief Try to resolve the file name of a parsed source location.
88 ///
89 /// \returns true if there was an error, false otherwise.
90 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
91};
92
93bool
94ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
95 RequestedSourceLocation &Result) {
96 const FileEntry *File = FileMgr.getFile(FileName);
97 if (!File)
98 return true;
99
100 Result.File = File;
101 Result.Line = Line;
102 Result.Column = Column;
103 return false;
104}
105
106namespace llvm {
107 namespace cl {
108 /// \brief Command-line option parser that parses source locations.
109 ///
110 /// Source locations are of the form filename:line:column.
111 template<>
112 class parser<ParsedSourceLocation>
113 : public basic_parser<ParsedSourceLocation> {
114 public:
115 bool parse(Option &O, const char *ArgName,
116 const std::string &ArgValue,
117 ParsedSourceLocation &Val);
118 };
119
120 bool
121 parser<ParsedSourceLocation>::
122 parse(Option &O, const char *ArgName, const std::string &ArgValue,
123 ParsedSourceLocation &Val) {
124 using namespace clang;
125
126 const char *ExpectedFormat
127 = "source location must be of the form filename:line:column";
128 std::string::size_type SecondColon = ArgValue.rfind(':');
129 if (SecondColon == std::string::npos) {
130 std::fprintf(stderr, "%s\n", ExpectedFormat);
131 return true;
132 }
133 char *EndPtr;
134 long Column
135 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
136 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
137 std::fprintf(stderr, "%s\n", ExpectedFormat);
138 return true;
139 }
140
141 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
142 if (SecondColon == std::string::npos) {
143 std::fprintf(stderr, "%s\n", ExpectedFormat);
144 return true;
145 }
146 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
147 if (EndPtr != ArgValue.c_str() + SecondColon) {
148 std::fprintf(stderr, "%s\n", ExpectedFormat);
149 return true;
150 }
151
152 Val.FileName = ArgValue.substr(0, FirstColon);
153 Val.Line = Line;
154 Val.Column = Column;
155 return false;
156 }
157 }
158}
159
160//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000161// Global options.
162//===----------------------------------------------------------------------===//
163
Chris Lattner47099742009-02-18 01:51:21 +0000164/// ClangFrontendTimer - The front-end activities should charge time to it with
165/// TimeRegion. The -ftime-report option controls whether this will do
166/// anything.
167llvm::Timer *ClangFrontendTimer = 0;
168
Daniel Dunbard3db4012008-10-16 16:54:18 +0000169static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000170
Reid Spencer5f016e22007-07-11 17:01:13 +0000171static llvm::cl::opt<bool>
172Verbose("v", llvm::cl::desc("Enable verbose output"));
173static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +0000174Stats("print-stats",
175 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000176static llvm::cl::opt<bool>
177DisableFree("disable-free",
178 llvm::cl::desc("Disable freeing of memory on exit"),
179 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000180static llvm::cl::opt<bool>
181EmptyInputOnly("empty-input-only",
182 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000183
184enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000185 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000186 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000187 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000188 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000189 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000190 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000191 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000193 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +0000194 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000195 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000196 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000197 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000198 ASTDump, // Parse ASTs and dump them.
199 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000200 PrintDeclContext, // Print DeclContext and their Decls.
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 ParsePrintCallbacks, // Parse and print each callback.
202 ParseSyntaxOnly, // Parse and perform semantic analysis.
203 ParseNoop, // Parse with noop callbacks.
204 RunPreprocessorOnly, // Just lex, no output.
205 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000206 DumpTokens, // Dump out preprocessed tokens.
207 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000208 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000209 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000210 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000211 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000212};
213
214static llvm::cl::opt<ProgActions>
215ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
216 llvm::cl::init(ParseSyntaxOnly),
217 llvm::cl::values(
218 clEnumValN(RunPreprocessorOnly, "Eonly",
219 "Just run preprocessor, no output (for timings)"),
220 clEnumValN(PrintPreprocessedInput, "E",
221 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000222 clEnumValN(DumpRawTokens, "dump-raw-tokens",
223 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000224 clEnumValN(RunAnalysis, "analyze",
225 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000226 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000227 "Run preprocessor, dump internal rep of tokens"),
228 clEnumValN(ParseNoop, "parse-noop",
229 "Run parser with noop callbacks (for timings)"),
230 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
231 "Run parser and perform semantic analysis"),
232 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
233 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000234 clEnumValN(EmitHTML, "emit-html",
235 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000236 clEnumValN(ASTPrint, "ast-print",
237 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000238 clEnumValN(ASTPrintXML, "ast-print-xml",
239 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000240 clEnumValN(ASTDump, "ast-dump",
241 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000242 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000243 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000244 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000245 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000246 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000247 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000248 clEnumValN(GeneratePCH, "emit-pch",
249 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000250 clEnumValN(EmitAssembly, "S",
251 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000253 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000254 clEnumValN(EmitBC, "emit-llvm-bc",
255 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000256 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
257 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000258 clEnumValN(RewriteTest, "rewrite-test",
259 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000260 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000261 "Rewrite ObjC into C (code rewriter example)"),
262 clEnumValN(RewriteMacros, "rewrite-macros",
263 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000264 clEnumValN(RewriteBlocks, "rewrite-blocks",
265 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000266 clEnumValN(FixIt, "fixit",
267 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 clEnumValEnd));
269
Ted Kremenekccc76472007-12-19 19:47:59 +0000270
271static llvm::cl::opt<std::string>
272OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000273 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000274 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000275
Ted Kremenekc2e72992008-12-02 19:57:31 +0000276
277//===----------------------------------------------------------------------===//
278// PTH.
279//===----------------------------------------------------------------------===//
280
281static llvm::cl::opt<std::string>
282TokenCache("token-cache", llvm::cl::value_desc("path"),
283 llvm::cl::desc("Use specified token cache file"));
284
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000285//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000286// Diagnostic Options
287//===----------------------------------------------------------------------===//
288
Ted Kremenek41193e42007-09-26 19:42:19 +0000289static llvm::cl::opt<bool>
290VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000291 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000292
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000293static llvm::cl::opt<std::string>
294HTMLDiag("html-diags",
295 llvm::cl::desc("Generate HTML to report diagnostics"),
296 llvm::cl::value_desc("HTML directory"));
297
Nico Weberfd54ebc2008-08-05 23:33:20 +0000298static llvm::cl::opt<bool>
299NoShowColumn("fno-show-column",
300 llvm::cl::desc("Do not include column number on diagnostics"));
301
302static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000303NoShowLocation("fno-show-source-location",
304 llvm::cl::desc("Do not include source location information with"
305 " diagnostics"));
306
307static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000308NoCaretDiagnostics("fno-caret-diagnostics",
309 llvm::cl::desc("Do not include source line and caret with"
310 " diagnostics"));
311
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000312static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000313NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
314 llvm::cl::desc("Do not include fixit information in"
315 " diagnostics"));
316
317static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000318PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
319 llvm::cl::desc("Print source range spans in numeric form"));
320
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000321static llvm::cl::opt<bool>
322PrintDiagnosticOption("fdiagnostics-show-option",
323 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000324
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000325static llvm::cl::opt<unsigned>
326MessageLength("fmessage-length",
327 llvm::cl::desc("Format message diagnostics so that they fit "
328 "within N columns or fewer, when possible."),
329 llvm::cl::value_desc("N"));
330
Reid Spencer5f016e22007-07-11 17:01:13 +0000331//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000332// C++ Visualization.
333//===----------------------------------------------------------------------===//
334
335static llvm::cl::opt<std::string>
336InheritanceViewCls("cxx-inheritance-view",
337 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000338 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000339
340//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000341// Builtin Options
342//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000343
344static llvm::cl::opt<bool>
345TimeReport("ftime-report",
346 llvm::cl::desc("Print the amount of time each "
347 "phase of compilation takes"));
348
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000349static llvm::cl::opt<bool>
350Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000351 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000352 "freestanding environment"));
353
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000354static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000355AllowBuiltins("fbuiltin", llvm::cl::init(true),
356 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000357
358
359static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000360MathErrno("fmath-errno", llvm::cl::init(true),
361 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000362
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000363//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000364// Language Options
365//===----------------------------------------------------------------------===//
366
367enum LangKind {
368 langkind_unspecified,
369 langkind_c,
370 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000371 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 langkind_cxx,
373 langkind_cxx_cpp,
374 langkind_objc,
375 langkind_objc_cpp,
376 langkind_objcxx,
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000377 langkind_objcxx_cpp
Reid Spencer5f016e22007-07-11 17:01:13 +0000378};
379
Reid Spencer5f016e22007-07-11 17:01:13 +0000380static llvm::cl::opt<LangKind>
381BaseLang("x", llvm::cl::desc("Base language to compile"),
382 llvm::cl::init(langkind_unspecified),
383 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
384 clEnumValN(langkind_cxx, "c++", "C++"),
385 clEnumValN(langkind_objc, "objective-c", "Objective C"),
386 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000387 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000389 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
390 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000392 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
394 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000395 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000397 clEnumValN(langkind_c, "c-header",
398 "C header"),
399 clEnumValN(langkind_objc, "objective-c-header",
400 "Objective-C header"),
401 clEnumValN(langkind_cxx, "c++-header",
402 "C++ header"),
403 clEnumValN(langkind_objcxx, "objective-c++-header",
404 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 clEnumValEnd));
406
407static llvm::cl::opt<bool>
408LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
409 llvm::cl::Hidden);
410static llvm::cl::opt<bool>
411LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
412 llvm::cl::Hidden);
413
Chris Lattner2c78b872009-04-14 23:22:57 +0000414static llvm::cl::opt<bool>
415ObjCExclusiveGC("fobjc-gc-only",
416 llvm::cl::desc("Use GC exclusively for Objective-C related "
417 "memory management"));
418
419static llvm::cl::opt<bool>
420ObjCEnableGC("fobjc-gc",
421 llvm::cl::desc("Enable Objective-C garbage collection"));
422
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000423static llvm::cl::opt<bool>
424ObjCEnableGCBitmapPrint("print-ivar-layout",
425 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
426
Chris Lattner2c78b872009-04-14 23:22:57 +0000427static llvm::cl::opt<LangOptions::VisibilityMode>
428SymbolVisibility("fvisibility",
429 llvm::cl::desc("Set the default symbol visibility:"),
430 llvm::cl::init(LangOptions::Default),
431 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
432 "Use default symbol visibility"),
433 clEnumValN(LangOptions::Hidden, "hidden",
434 "Use hidden symbol visibility"),
435 clEnumValN(LangOptions::Protected,"protected",
436 "Use protected symbol visibility"),
437 clEnumValEnd));
438
439static llvm::cl::opt<bool>
440OverflowChecking("ftrapv",
441 llvm::cl::desc("Trap on integer overflow"),
442 llvm::cl::init(false));
443
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000444static llvm::cl::opt<bool>
445ObjCSenderDispatch("fobjc-sender-dependent-dispatch",
446 llvm::cl::desc("Enable sender-dependent dispatch for"
447 "Objective-C messages"), llvm::cl::init(false));
Chris Lattner2c78b872009-04-14 23:22:57 +0000448
Ted Kremenek8904f152007-12-05 23:49:08 +0000449/// InitializeBaseLanguage - Handle the -x foo options.
450static void InitializeBaseLanguage() {
451 if (LangObjC)
452 BaseLang = langkind_objc;
453 else if (LangObjCXX)
454 BaseLang = langkind_objcxx;
455}
456
457static LangKind GetLanguage(const std::string &Filename) {
458 if (BaseLang != langkind_unspecified)
459 return BaseLang;
460
461 std::string::size_type DotPos = Filename.rfind('.');
462
463 if (DotPos == std::string::npos) {
464 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000465 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 }
467
Ted Kremenek8904f152007-12-05 23:49:08 +0000468 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
469 // C header: .h
470 // C++ header: .hh or .H;
471 // assembler no preprocessing: .s
472 // assembler: .S
473 if (Ext == "c")
474 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000475 else if (Ext == "S" ||
476 // If the compiler is run on a .s file, preprocess it as .S
477 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000478 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000479 else if (Ext == "i")
480 return langkind_c_cpp;
481 else if (Ext == "ii")
482 return langkind_cxx_cpp;
483 else if (Ext == "m")
484 return langkind_objc;
485 else if (Ext == "mi")
486 return langkind_objc_cpp;
487 else if (Ext == "mm" || Ext == "M")
488 return langkind_objcxx;
489 else if (Ext == "mii")
490 return langkind_objcxx_cpp;
491 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
492 Ext == "c++" || Ext == "cp" || Ext == "cxx")
493 return langkind_cxx;
494 else
495 return langkind_c;
496}
497
498
Ted Kremenek85888962008-10-21 00:54:44 +0000499static void InitializeCOptions(LangOptions &Options) {
500 // Do nothing.
501}
502
503static void InitializeObjCOptions(LangOptions &Options) {
504 Options.ObjC1 = Options.ObjC2 = 1;
505}
506
507
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000508static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 // FIXME: implement -fpreprocessed mode.
510 bool NoPreprocess = false;
511
Ted Kremenek8904f152007-12-05 23:49:08 +0000512 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000514 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000515 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000516 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000517 case langkind_c_cpp:
518 NoPreprocess = true;
519 // FALLTHROUGH
520 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000521 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000522 break;
523 case langkind_cxx_cpp:
524 NoPreprocess = true;
525 // FALLTHROUGH
526 case langkind_cxx:
527 Options.CPlusPlus = 1;
528 break;
529 case langkind_objc_cpp:
530 NoPreprocess = true;
531 // FALLTHROUGH
532 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000533 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 break;
535 case langkind_objcxx_cpp:
536 NoPreprocess = true;
537 // FALLTHROUGH
538 case langkind_objcxx:
539 Options.ObjC1 = Options.ObjC2 = 1;
540 Options.CPlusPlus = 1;
541 break;
542 }
Chris Lattner2c78b872009-04-14 23:22:57 +0000543
544 if (ObjCExclusiveGC)
545 Options.setGCMode(LangOptions::GCOnly);
546 else if (ObjCEnableGC)
547 Options.setGCMode(LangOptions::HybridGC);
548
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000549 if (ObjCEnableGCBitmapPrint)
550 Options.ObjCGCBitmapPrint = 1;
551
Chris Lattner2c78b872009-04-14 23:22:57 +0000552 Options.setVisibilityMode(SymbolVisibility);
553 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000554}
555
556/// LangStds - Language standards we support.
557enum LangStds {
558 lang_unspecified,
559 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000560 lang_gnu_START,
561 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000562 lang_cxx98, lang_gnucxx98,
563 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000564};
565
566static llvm::cl::opt<LangStds>
567LangStd("std", llvm::cl::desc("Language standard to compile for"),
568 llvm::cl::init(lang_unspecified),
569 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
570 clEnumValN(lang_c89, "c90", "ISO C 1990"),
571 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
572 clEnumValN(lang_c94, "iso9899:199409",
573 "ISO C 1990 with amendment 1"),
574 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000575 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000577 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000579 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000581 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 clEnumValN(lang_gnu99, "gnu9x",
583 "ISO C 1999 with GNU extensions"),
584 clEnumValN(lang_cxx98, "c++98",
585 "ISO C++ 1998 with amendments"),
586 clEnumValN(lang_gnucxx98, "gnu++98",
587 "ISO C++ 1998 with amendments and GNU "
588 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000589 clEnumValN(lang_cxx0x, "c++0x",
590 "Upcoming ISO C++ 200x with amendments"),
591 clEnumValN(lang_gnucxx0x, "gnu++0x",
592 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000593 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 clEnumValEnd));
595
596static llvm::cl::opt<bool>
597NoOperatorNames("fno-operator-names",
598 llvm::cl::desc("Do not treat C++ operator name keywords as "
599 "synonyms for operators"));
600
Anders Carlssonee98ac52007-10-15 02:50:23 +0000601static llvm::cl::opt<bool>
602PascalStrings("fpascal-strings",
603 llvm::cl::desc("Recognize and construct Pascal-style "
604 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000605
606static llvm::cl::opt<bool>
607MSExtensions("fms-extensions",
608 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000609 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000610
611static llvm::cl::opt<bool>
612WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000613 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000614
615static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000616NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000617 llvm::cl::desc("Disallow implicit conversions between "
618 "vectors with a different number of "
619 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000620
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000621static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000622EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000623
624static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000625EnableHeinousExtensions("fheinous-gnu-extensions",
626 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
627 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
628
629static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000630ObjCNonFragileABI("fobjc-nonfragile-abi",
631 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000632
Daniel Dunbard6884a02009-05-04 05:16:21 +0000633
634static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000635EmitAllDecls("femit-all-decls",
636 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000637
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000638static llvm::cl::opt<bool>
639Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000640 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000641
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000642static llvm::cl::opt<bool>
643GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000644 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000645 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000646
647static llvm::cl::opt<bool>
648NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000649 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000650 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000651
Ted Kremenekea644d82008-09-03 21:22:16 +0000652
653
654static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000655Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000656
Douglas Gregor26dce442009-03-10 00:06:19 +0000657static llvm::cl::opt<unsigned>
658TemplateDepth("ftemplate-depth", llvm::cl::init(99),
659 llvm::cl::desc("Maximum depth of recursive template "
660 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000661static llvm::cl::opt<bool>
662DollarsInIdents("fdollars-in-identifiers",
663 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000664
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000665
666static llvm::cl::opt<bool>
667OptSize("Os", llvm::cl::desc("Optimize for size"));
668
669static llvm::cl::opt<bool>
Daniel Dunbar877db382009-06-02 22:07:45 +0000670DisableLLVMOptimizations("disable-llvm-optzns",
671 llvm::cl::desc("Don't run LLVM optimization passes"));
672
673static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000674NoCommon("fno-common",
675 llvm::cl::desc("Compile common globals like normal definitions"),
676 llvm::cl::ValueDisallowed);
677
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000678static llvm::cl::opt<std::string>
679MainFileName("main-file-name",
680 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000681
Anders Carlssona33d9b42009-05-13 19:49:53 +0000682// FIXME: Also add an "-fno-access-control" option.
683static llvm::cl::opt<bool>
684AccessControl("faccess-control",
685 llvm::cl::desc("Enable C++ access control"));
686
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000687// It might be nice to add bounds to the CommandLine library directly.
688struct OptLevelParser : public llvm::cl::parser<unsigned> {
689 bool parse(llvm::cl::Option &O, const char *ArgName,
690 const std::string &Arg, unsigned &Val) {
691 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
692 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000693 if (Val > 3)
694 return O.error(": '" + Arg + "' invalid optimization level!");
695 return false;
696 }
697};
698static llvm::cl::opt<unsigned, false, OptLevelParser>
699OptLevel("O", llvm::cl::Prefix,
700 llvm::cl::desc("Optimization level"),
701 llvm::cl::init(0));
702
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000703static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000704PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
705
706static llvm::cl::opt<bool>
707StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000708
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000709static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000710 TargetInfo *Target,
711 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000712 // Allow the target to set the default the langauge options as it sees fit.
713 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000714
715 // Pass the map of target features to the target for validation and
716 // processing.
717 Target->HandleTargetFeatures(Features);
Chris Lattner16167a62009-03-02 22:11:07 +0000718
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 if (LangStd == lang_unspecified) {
720 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000721 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000722 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000723 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000724 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 case langkind_c_cpp:
726 case langkind_objc:
727 case langkind_objc_cpp:
728 LangStd = lang_gnu99;
729 break;
730 case langkind_cxx:
731 case langkind_cxx_cpp:
732 case langkind_objcxx:
733 case langkind_objcxx_cpp:
734 LangStd = lang_gnucxx98;
735 break;
736 }
737 }
738
739 switch (LangStd) {
740 default: assert(0 && "Unknown language standard!");
741
742 // Fall through from newer standards to older ones. This isn't really right.
743 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000744 case lang_gnucxx0x:
745 case lang_cxx0x:
746 Options.CPlusPlus0x = 1;
747 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 case lang_gnucxx98:
749 case lang_cxx98:
750 Options.CPlusPlus = 1;
751 Options.CXXOperatorNames = !NoOperatorNames;
752 // FALL THROUGH.
753 case lang_gnu99:
754 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000755 Options.C99 = 1;
756 Options.HexFloats = 1;
757 // FALL THROUGH.
758 case lang_gnu89:
759 Options.BCPLComment = 1; // Only for C99/C++.
760 // FALL THROUGH.
761 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000762 Options.Digraphs = 1; // C94, C99, C++.
763 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 case lang_c89:
765 break;
766 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000767
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000768 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
769 Options.GNUMode = LangStd >= lang_gnu_START;
770
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000771 if (Options.CPlusPlus) {
772 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000773 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000774 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000775
Chris Lattnerd658b562008-04-05 06:32:51 +0000776 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
777 Options.ImplicitInt = 1;
778 else
779 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000780
Daniel Dunbard573d262009-04-07 22:13:21 +0000781 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
782 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000783 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000784 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000785 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000786
Chris Lattner802db9b2008-12-05 00:10:44 +0000787 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
788 // even if they are normally on for the target. In GNU modes (e.g.
789 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000790 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000791 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000792 Options.Blocks = 0;
793
Chris Lattner01638a62009-04-19 07:06:52 +0000794 // Default to not accepting '$' in identifiers when preprocessing assembler,
795 // but do accept when preprocessing C. FIXME: these defaults are right for
796 // darwin, are they right everywhere?
797 Options.DollarIdents = LK != langkind_asm_cpp;
798 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000799 Options.DollarIdents = DollarsInIdents;
800
Chris Lattnerae0ee032008-12-04 23:20:07 +0000801 if (PascalStrings.getPosition())
802 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000803 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000804 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000805 if (NoLaxVectorConversions.getPosition())
806 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000807 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000808 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000809 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000810
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000811 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000812 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000813 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000814 Options.Freestanding = Options.NoBuiltin = 1;
815
Chris Lattner810f6d52009-03-13 17:38:01 +0000816 if (EnableHeinousExtensions)
817 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000818
Anders Carlssona33d9b42009-05-13 19:49:53 +0000819 if (AccessControl)
820 Options.AccessControl = 1;
821
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000822 Options.MathErrno = MathErrno;
823
Douglas Gregor26dce442009-03-10 00:06:19 +0000824 Options.InstantiationDepth = TemplateDepth;
825
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000826 // Override the default runtime if the user requested it.
827 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000828 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000829 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000830 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000831
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000832 if (ObjCNonFragileABI)
833 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000834
835 Options.ObjCSenderDispatch = ObjCSenderDispatch;
Daniel Dunbard6884a02009-05-04 05:16:21 +0000836
Daniel Dunbard604c402009-02-04 21:19:06 +0000837 if (EmitAllDecls)
838 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000839
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000840 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
841 // support.
842 Options.OptimizeSize = 0;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000843
844 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000845 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000846 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000847
848 assert(PICLevel <= 2 && "Invalid value for -pic-level");
849 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000850
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000851 Options.GNUInline = !Options.C99;
Chris Lattner5aeb9e72009-05-06 04:38:30 +0000852 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000853 Options.NoInline = !OptSize && !OptLevel;
854
855 Options.Static = StaticDefine;
856
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000857 if (MainFileName.getPosition())
858 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000859}
860
861//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000862// Target Triple Processing.
863//===----------------------------------------------------------------------===//
864
865static llvm::cl::opt<std::string>
866TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000867 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000868
Chris Lattner42e67372008-03-05 01:18:20 +0000869static llvm::cl::opt<std::string>
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000870MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000871 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000872
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000873// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
874// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000875
876// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000877static void HandleMacOSVersionMin(std::string &Triple) {
878 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
879 if (DarwinDashIdx == std::string::npos) {
880 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000881 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000882 exit(1);
883 }
884 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
885
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000886 // Remove the number.
887 Triple.resize(DarwinNumIdx);
888
889 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
890 bool MacOSVersionMinIsInvalid = false;
891 int VersionNum = 0;
892 if (MacOSVersionMin.size() < 4 ||
893 MacOSVersionMin.substr(0, 3) != "10." ||
894 !isdigit(MacOSVersionMin[3])) {
895 MacOSVersionMinIsInvalid = true;
896 } else {
897 const char *Start = MacOSVersionMin.c_str()+3;
898 char *End = 0;
899 VersionNum = (int)strtol(Start, &End, 10);
900
Chris Lattner079f2c462008-09-30 20:30:12 +0000901 // The version number must be in the range 0-9.
902 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
903
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000904 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
905 Triple += llvm::itostr(VersionNum+4);
906
Chris Lattner079f2c462008-09-30 20:30:12 +0000907 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
908 // Add the period piece (.7) to the end of the triple. This gives us
909 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000910 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000911 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
912 MacOSVersionMinIsInvalid = true;
913 }
914 }
915
916 if (MacOSVersionMinIsInvalid) {
917 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000918 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000919 MacOSVersionMin.c_str());
920 exit(1);
921 }
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000922 else if (VersionNum <= 4 &&
923 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
924 fprintf(stderr,
925 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
926 MacOSVersionMin.c_str());
927 exit(1);
928 }
929
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000930}
931
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000932static llvm::cl::opt<std::string>
933IPhoneOSVersionMin("miphoneos-version-min",
934 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
935
936// If -miphoneos-version-min=2.2 is specified, change the triple from being
937// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
938// 9 as the default major Darwin number, and encode the iPhone OS version
939// number in the minor version and revision.
940
941// FIXME: We should have the driver do this instead.
942static void HandleIPhoneOSVersionMin(std::string &Triple) {
943 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
944 if (DarwinDashIdx == std::string::npos) {
945 fprintf(stderr,
946 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
947 exit(1);
948 }
949 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
950
951 // Remove the number.
952 Triple.resize(DarwinNumIdx);
953
954 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
955 bool IPhoneOSVersionMinIsInvalid = false;
956 int VersionNum = 0;
957 if (IPhoneOSVersionMin.size() < 3 ||
958 !isdigit(IPhoneOSVersionMin[0])) {
959 IPhoneOSVersionMinIsInvalid = true;
960 } else {
961 const char *Start = IPhoneOSVersionMin.c_str();
962 char *End = 0;
963 VersionNum = (int)strtol(Start, &End, 10);
964
965 // The version number must be in the range 0-9.
966 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
967
968 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
969 Triple += "9." + llvm::itostr(VersionNum);
970
971 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
972 // Add the period piece (.2) to the end of the triple. This gives us
973 // something like ...-darwin9.2.2
974 Triple += End;
975 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
976 IPhoneOSVersionMinIsInvalid = true;
977 }
978 }
979
980 if (IPhoneOSVersionMinIsInvalid) {
981 fprintf(stderr,
982 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
983 IPhoneOSVersionMin.c_str());
984 exit(1);
985 }
986}
987
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000988/// CreateTargetTriple - Process the various options that affect the target
989/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000990static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000991 // Initialize base triple. If a -triple option has been specified, use
992 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000993 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000994 if (Triple.empty())
995 Triple = llvm::sys::getHostTriple();
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000996
997 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
998 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000999 if (!MacOSVersionMin.empty())
1000 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +00001001 else if (!IPhoneOSVersionMin.empty())
1002 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenekae360762007-12-03 22:06:55 +00001003
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001004 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +00001005}
1006
1007//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +00001008// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +00001009//===----------------------------------------------------------------------===//
1010
Douglas Gregore1d918e2009-04-10 23:10:45 +00001011static bool InitializeSourceManager(Preprocessor &PP,
1012 const std::string &InFile) {
1013 // Figure out where to get and map in the main file.
1014 SourceManager &SourceMgr = PP.getSourceManager();
1015 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001016
1017 if (EmptyInputOnly) {
1018 const char *EmptyStr = "";
1019 llvm::MemoryBuffer *SB =
1020 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1021 SourceMgr.createMainFileIDForMemBuffer(SB);
1022 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001023 const FileEntry *File = FileMgr.getFile(InFile);
1024 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1025 if (SourceMgr.getMainFileID().isInvalid()) {
1026 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1027 << InFile.c_str();
1028 return true;
1029 }
1030 } else {
1031 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1032
1033 // If stdin was empty, SB is null. Cons up an empty memory
1034 // buffer now.
1035 if (!SB) {
1036 const char *EmptyStr = "";
1037 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1038 }
1039
1040 SourceMgr.createMainFileIDForMemBuffer(SB);
1041 if (SourceMgr.getMainFileID().isInvalid()) {
1042 PP.getDiagnostics().Report(FullSourceLoc(),
1043 diag::err_fe_error_reading_stdin);
1044 return true;
1045 }
1046 }
1047
1048 return false;
1049}
1050
Chris Lattneraa391972008-04-19 23:09:31 +00001051
Chris Lattnere116ccf2009-04-21 05:40:52 +00001052//===----------------------------------------------------------------------===//
1053// Preprocessor Initialization
1054//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001055
Chris Lattnere116ccf2009-04-21 05:40:52 +00001056// FIXME: Preprocessor builtins to support.
1057// -A... - Play with #assertions
1058// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001059
Chris Lattnere116ccf2009-04-21 05:40:52 +00001060static llvm::cl::list<std::string>
1061D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1062 llvm::cl::desc("Predefine the specified macro"));
1063static llvm::cl::list<std::string>
1064U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1065 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001066
Chris Lattnere116ccf2009-04-21 05:40:52 +00001067static llvm::cl::list<std::string>
1068ImplicitIncludes("include", llvm::cl::value_desc("file"),
1069 llvm::cl::desc("Include file before parsing"));
1070static llvm::cl::list<std::string>
1071ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1072 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001073
Chris Lattnere116ccf2009-04-21 05:40:52 +00001074static llvm::cl::opt<std::string>
1075ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1076 llvm::cl::desc("Include precompiled header file"));
1077
1078static llvm::cl::opt<std::string>
1079ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1080 llvm::cl::desc("Include file before parsing"));
1081
Reid Spencer5f016e22007-07-11 17:01:13 +00001082
1083//===----------------------------------------------------------------------===//
1084// Preprocessor include path information.
1085//===----------------------------------------------------------------------===//
1086
1087// This tool exports a large number of command line options to control how the
1088// preprocessor searches for header files. At root, however, the Preprocessor
1089// object takes a very simple interface: a list of directories to search for
1090//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001091// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001092// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001093//
Reid Spencer5f016e22007-07-11 17:01:13 +00001094
1095static llvm::cl::opt<bool>
1096nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1097
1098// Various command line options. These four add directories to each chain.
1099static llvm::cl::list<std::string>
1100F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1101 llvm::cl::desc("Add directory to framework include search path"));
1102static llvm::cl::list<std::string>
1103I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1104 llvm::cl::desc("Add directory to include search path"));
1105static llvm::cl::list<std::string>
1106idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1107 llvm::cl::desc("Add directory to AFTER include search path"));
1108static llvm::cl::list<std::string>
1109iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1110 llvm::cl::desc("Add directory to QUOTE include search path"));
1111static llvm::cl::list<std::string>
1112isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1113 llvm::cl::desc("Add directory to SYSTEM include search path"));
1114
1115// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1116static llvm::cl::list<std::string>
1117iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1118 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1119static llvm::cl::list<std::string>
1120iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1121 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1122static llvm::cl::list<std::string>
1123iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1124 llvm::cl::Prefix,
1125 llvm::cl::desc("Set directory to include search path with prefix"));
1126
Chris Lattner0c946412007-08-26 17:47:35 +00001127static llvm::cl::opt<std::string>
1128isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1129 llvm::cl::desc("Set the system root directory (usually /)"));
1130
Reid Spencer5f016e22007-07-11 17:01:13 +00001131// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001132
Reid Spencer5f016e22007-07-11 17:01:13 +00001133/// InitializeIncludePaths - Process the -I options and set them in the
1134/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001135void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1136 FileManager &FM, const LangOptions &Lang) {
1137 InitHeaderSearch Init(Headers, Verbose, isysroot);
1138
Ted Kremenekf3721112008-05-31 00:27:00 +00001139 // Handle -I... and -F... options, walking the lists in parallel.
1140 unsigned Iidx = 0, Fidx = 0;
1141 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1142 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001143 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001144 ++Iidx;
1145 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001146 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001147 ++Fidx;
1148 }
1149 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001150
Ted Kremenekf3721112008-05-31 00:27:00 +00001151 // Consume what's left from whatever list was longer.
1152 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001153 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001154 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001155 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001156
1157 // Handle -idirafter... options.
1158 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001159 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1160 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001161
1162 // Handle -iquote... options.
1163 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001164 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001165
1166 // Handle -isystem... options.
1167 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001168 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001169
1170 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1171 // parallel, processing the values in order of occurance to get the right
1172 // prefixes.
1173 {
1174 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1175 unsigned iprefix_idx = 0;
1176 unsigned iwithprefix_idx = 0;
1177 unsigned iwithprefixbefore_idx = 0;
1178 bool iprefix_done = iprefix_vals.empty();
1179 bool iwithprefix_done = iwithprefix_vals.empty();
1180 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1181 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1182 if (!iprefix_done &&
1183 (iwithprefix_done ||
1184 iprefix_vals.getPosition(iprefix_idx) <
1185 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1186 (iwithprefixbefore_done ||
1187 iprefix_vals.getPosition(iprefix_idx) <
1188 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1189 Prefix = iprefix_vals[iprefix_idx];
1190 ++iprefix_idx;
1191 iprefix_done = iprefix_idx == iprefix_vals.size();
1192 } else if (!iwithprefix_done &&
1193 (iwithprefixbefore_done ||
1194 iwithprefix_vals.getPosition(iwithprefix_idx) <
1195 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001196 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1197 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 ++iwithprefix_idx;
1199 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1200 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001201 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1202 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 ++iwithprefixbefore_idx;
1204 iwithprefixbefore_done =
1205 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1206 }
1207 }
1208 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001209
Nico Weber0fca0222008-08-22 09:25:22 +00001210 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001211
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001212 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001213 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001214 llvm::sys::Path::GetMainExecutable(Argv0,
1215 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001216 if (!MainExecutablePath.isEmpty()) {
1217 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1218 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001219
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001220 // Get foo/lib/clang/<version>/include
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001221 MainExecutablePath.appendComponent("lib");
1222 MainExecutablePath.appendComponent("clang");
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001223 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001224 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001225
1226 // We pass true to ignore sysroot so that we *always* look for clang headers
1227 // relative to our executable, never relative to -isysroot.
1228 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1229 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001230 }
1231
Nico Weber0fca0222008-08-22 09:25:22 +00001232 if (!nostdinc)
1233 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001234
1235 // Now that we have collected all of the include paths, merge them all
1236 // together and tell the preprocessor about them.
1237
Nico Weber0fca0222008-08-22 09:25:22 +00001238 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001239}
1240
Chris Lattnere116ccf2009-04-21 05:40:52 +00001241void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1242{
1243 // Add macros from the command line.
1244 unsigned d = 0, D = D_macros.size();
1245 unsigned u = 0, U = U_macros.size();
1246 while (d < D || u < U) {
1247 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1248 InitOpts.addMacroDef(D_macros[d++]);
1249 else
1250 InitOpts.addMacroUndef(U_macros[u++]);
1251 }
1252
1253 // If -imacros are specified, include them now. These are processed before
1254 // any -include directives.
1255 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1256 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1257
Douglas Gregorb64c1932009-05-12 01:31:05 +00001258 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1259 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001260 // We want to add these paths to the predefines buffer in order, make a
1261 // temporary vector to sort by their occurrence.
1262 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1263
1264 if (!ImplicitIncludePTH.empty())
1265 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1266 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001267 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1268 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1269 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001270 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1271 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1272 &ImplicitIncludes[i]));
1273 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1274
1275
1276 // Now that they are ordered by position, add to the predefines buffer.
1277 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1278 std::string *Ptr = OrderedPaths[i].second;
1279 if (!ImplicitIncludes.empty() &&
1280 Ptr >= &ImplicitIncludes[0] &&
1281 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1282 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001283 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001284 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001285 } else {
1286 // We end up here when we're producing preprocessed output and
1287 // we loaded a PCH file. In this case, just include the header
1288 // file that was used to build the precompiled header.
1289 assert(Ptr == &ImplicitIncludePCH);
1290 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1291 if (!OriginalFile.empty()) {
1292 InitOpts.addInclude(OriginalFile, false);
1293 ImplicitIncludePCH.clear();
1294 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001295 }
1296 }
1297 }
1298}
1299
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001300//===----------------------------------------------------------------------===//
1301// Driver PreprocessorFactory - For lazily generating preprocessors ...
1302//===----------------------------------------------------------------------===//
1303
1304namespace {
1305class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1306 Diagnostic &Diags;
1307 const LangOptions &LangInfo;
1308 TargetInfo &Target;
1309 SourceManager &SourceMgr;
1310 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001311
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001312public:
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001313 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001314 TargetInfo &target, SourceManager &SM,
1315 HeaderSearch &Headers)
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001316 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001317 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek339b9c22008-04-17 22:31:54 +00001318
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001319
1320 virtual ~DriverPreprocessorFactory() {}
1321
1322 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001323 llvm::OwningPtr<PTHManager> PTHMgr;
1324
Ted Kremenek748d5d62009-03-20 00:26:38 +00001325 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1326 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1327 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001328 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001329 }
1330
Ted Kremenek72b1b152009-01-15 18:47:46 +00001331 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001332 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1333 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001334 PTHMgr.reset(PTHManager::Create(x, &Diags,
1335 TokenCache.empty() ? Diagnostic::Error
1336 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001337 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001338
Ted Kremenek22f0d092009-03-22 06:42:39 +00001339 if (Diags.hasErrorOccurred())
1340 exit(1);
1341
Ted Kremenek72b1b152009-01-15 18:47:46 +00001342 // Create the Preprocessor.
1343 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1344 SourceMgr, HeaderInfo,
1345 PTHMgr.get()));
1346
1347 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1348 // That argument is used as the IdentifierInfoLookup argument to
1349 // IdentifierTable's ctor.
1350 if (PTHMgr) {
1351 PTHMgr->setPreprocessor(PP.get());
1352 PP->setPTHManager(PTHMgr.take());
1353 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001354
Chris Lattnere116ccf2009-04-21 05:40:52 +00001355 PreprocessorInitOptions InitOpts;
1356 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001357 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001358 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001359
Douglas Gregore1d918e2009-04-10 23:10:45 +00001360 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001361 }
1362};
1363}
Reid Spencer5f016e22007-07-11 17:01:13 +00001364
Reid Spencer5f016e22007-07-11 17:01:13 +00001365//===----------------------------------------------------------------------===//
1366// Basic Parser driver
1367//===----------------------------------------------------------------------===//
1368
Chris Lattner51574ea2008-04-19 23:25:44 +00001369static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001371 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001372
1373 // Parsing the specified input file.
1374 P.ParseTranslationUnit();
1375 delete PA;
1376}
1377
1378//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001379// Code generation options
1380//===----------------------------------------------------------------------===//
1381
1382static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001383GenerateDebugInfo("g",
1384 llvm::cl::desc("Generate source level debug information"));
1385
Daniel Dunbara034ba82009-02-17 19:47:34 +00001386static llvm::cl::opt<std::string>
1387TargetCPU("mcpu",
1388 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1389
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001390static llvm::cl::list<std::string>
1391TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1392
1393/// ComputeTargetFeatures - Recompute the target feature list to only
1394/// be the list of things that are enabled, based on the target cpu
1395/// and feature list.
1396static void ComputeFeatureMap(TargetInfo *Target,
1397 llvm::StringMap<bool> &Features) {
1398 assert(Features.empty() && "invalid map");
1399
1400 // Initialize the feature map based on the target.
1401 Target->getDefaultFeatures(TargetCPU, Features);
1402
1403 // Apply the user specified deltas.
1404 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1405 ie = TargetFeatures.end(); it != ie; ++it) {
1406 const char *Name = it->c_str();
1407
1408 // FIXME: Don't handle errors like this.
1409 if (Name[0] != '-' && Name[0] != '+') {
1410 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1411 Name);
1412 exit(1);
1413 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001414 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1415 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1416 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001417 exit(1);
1418 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001419 }
1420}
1421
Chris Lattner7afae712009-03-16 18:41:18 +00001422static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001423 const LangOptions &LangOpts,
1424 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001425 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001426 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001427
1428 if (DisableLLVMOptimizations) {
1429 Opts.OptimizationLevel = 0;
1430 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001431 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001432 if (OptSize) {
1433 // -Os implies -O2
1434 Opts.OptimizationLevel = 2;
1435 } else {
1436 Opts.OptimizationLevel = OptLevel;
1437 }
1438
1439 // We must always run at least the always inlining pass.
1440 if (Opts.OptimizationLevel > 1)
1441 Opts.Inlining = CompileOptions::NormalInlining;
1442 else
1443 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001444 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001445
1446 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001447 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001448 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001449
1450#ifdef NDEBUG
1451 Opts.VerifyModule = 0;
1452#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001453
1454 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001455 Opts.Features.clear();
1456 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1457 ie = Features.end(); it != ie; ++it) {
1458 // FIXME: If we are completely confident that we have the right
1459 // set, we only need to pass the minuses.
1460 std::string Name(it->second ? "+" : "-");
1461 Name += it->first();
1462 Opts.Features.push_back(Name);
1463 }
Chris Lattner44502662009-02-18 01:23:44 +00001464
Chris Lattnerbd360642009-03-26 05:00:52 +00001465 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1466
Chris Lattner44502662009-02-18 01:23:44 +00001467 // Handle -ftime-report.
1468 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001469}
1470
1471//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001472// Fix-It Options
1473//===----------------------------------------------------------------------===//
1474static llvm::cl::list<ParsedSourceLocation>
1475FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1476 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1477
1478//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001479// ObjC Rewriter Options
1480//===----------------------------------------------------------------------===//
1481static llvm::cl::opt<bool>
1482SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1483 llvm::cl::desc("Silence ObjC rewriting warnings"));
1484
1485//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001486// Warning Options
1487//===----------------------------------------------------------------------===//
1488
1489// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1490// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1491// -Wextra, so we don't need to worry about it.
1492static llvm::cl::list<std::string>
1493OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1494
1495static llvm::cl::opt<bool> OptPedantic("pedantic");
1496static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1497static llvm::cl::opt<bool> OptNoWarnings("w");
1498
1499//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001500// Preprocessing (-E mode) Options
1501//===----------------------------------------------------------------------===//
1502static llvm::cl::opt<bool>
1503DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1504static llvm::cl::opt<bool>
1505EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1506static llvm::cl::opt<bool>
1507EnableMacroCommentOutput("CC",
1508 llvm::cl::desc("Enable comment output in -E mode, "
1509 "even from macro expansions"));
1510static llvm::cl::opt<bool>
1511DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1512 " normal output"));
1513static llvm::cl::opt<bool>
1514DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1515 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001516
1517//===----------------------------------------------------------------------===//
1518// Dependency file options
1519//===----------------------------------------------------------------------===//
1520static llvm::cl::opt<std::string>
1521DependencyFile("dependency-file",
1522 llvm::cl::desc("Filename (or -) to write dependency output to"));
1523
1524static llvm::cl::opt<bool>
1525DependenciesIncludeSystemHeaders("sys-header-deps",
1526 llvm::cl::desc("Include system headers in dependency output"));
1527
1528static llvm::cl::list<std::string>
1529DependencyTargets("MT",
1530 llvm::cl::desc("Specify target for dependency"));
1531
1532// FIXME: Implement feature
1533static llvm::cl::opt<bool>
1534PhonyDependencyTarget("MP",
1535 llvm::cl::desc("Create phony target for each dependency "
1536 "(other than main file)"));
1537
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001538//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001539// Analysis options
1540//===----------------------------------------------------------------------===//
1541
1542static llvm::cl::list<Analyses>
1543AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1544llvm::cl::values(
1545#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1546clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001547#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001548clEnumValEnd));
1549
1550static llvm::cl::opt<AnalysisStores>
1551AnalysisStoreOpt("analyzer-store",
1552 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1553 llvm::cl::init(BasicStoreModel),
1554 llvm::cl::values(
1555#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1556clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001557#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001558clEnumValEnd));
1559
1560static llvm::cl::opt<AnalysisConstraints>
1561AnalysisConstraintsOpt("analyzer-constraints",
1562 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1563 llvm::cl::init(RangeConstraintsModel),
1564 llvm::cl::values(
1565#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1566clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001567#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001568clEnumValEnd));
1569
1570static llvm::cl::opt<AnalysisDiagClients>
1571AnalysisDiagOpt("analyzer-output",
1572 llvm::cl::desc("Source Code Analysis - Output Options"),
1573 llvm::cl::init(PD_HTML),
1574 llvm::cl::values(
1575#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1576clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001577#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001578clEnumValEnd));
1579
1580static llvm::cl::opt<bool>
1581VisualizeEGDot("analyzer-viz-egraph-graphviz",
1582 llvm::cl::desc("Display exploded graph using GraphViz"));
1583
1584static llvm::cl::opt<bool>
1585VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1586 llvm::cl::desc("Display exploded graph using Ubigraph"));
1587
1588static llvm::cl::opt<bool>
1589AnalyzeAll("analyzer-opt-analyze-headers",
1590 llvm::cl::desc("Force the static analyzer to analyze "
1591 "functions defined in header files"));
1592
1593static llvm::cl::opt<bool>
1594AnalyzerDisplayProgress("analyzer-display-progress",
1595 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1596
1597static llvm::cl::opt<bool>
1598PurgeDead("analyzer-purge-dead",
1599 llvm::cl::init(true),
1600 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1601 " processing a statement."));
1602
1603static llvm::cl::opt<bool>
1604EagerlyAssume("analyzer-eagerly-assume",
1605 llvm::cl::init(false),
1606 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1607 "symbolic constraints."));
1608
1609static llvm::cl::opt<std::string>
1610AnalyzeSpecificFunction("analyze-function",
1611 llvm::cl::desc("Run analysis on specific function"));
1612
1613static llvm::cl::opt<bool>
1614TrimGraph("trim-egraph",
1615 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1616
1617static AnalyzerOptions ReadAnalyzerOptions() {
1618 AnalyzerOptions Opts;
1619 Opts.AnalysisList = AnalysisList;
1620 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1621 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1622 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1623 Opts.VisualizeEGDot = VisualizeEGDot;
1624 Opts.VisualizeEGUbi = VisualizeEGUbi;
1625 Opts.AnalyzeAll = AnalyzeAll;
1626 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1627 Opts.PurgeDead = PurgeDead;
1628 Opts.EagerlyAssume = EagerlyAssume;
1629 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1630 Opts.TrimGraph = TrimGraph;
1631 return Opts;
1632}
1633
1634//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001635// -dump-build-information Stuff
1636//===----------------------------------------------------------------------===//
1637
1638static llvm::cl::opt<std::string>
1639DumpBuildInformation("dump-build-information",
1640 llvm::cl::value_desc("filename"),
1641 llvm::cl::desc("output a dump of some build information to a file"));
1642
1643static llvm::raw_ostream *BuildLogFile = 0;
1644
1645/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1646/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1647namespace {
1648class LoggingDiagnosticClient : public DiagnosticClient {
1649 llvm::OwningPtr<DiagnosticClient> Chain1;
1650 llvm::OwningPtr<DiagnosticClient> Chain2;
1651public:
1652
1653 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1654 // Output diags both where requested...
1655 Chain1.reset(Normal);
1656 // .. and to our log file.
1657 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1658 !NoShowColumn,
1659 !NoCaretDiagnostics,
1660 !NoShowLocation,
1661 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001662 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001663 !NoDiagnosticsFixIt,
1664 MessageLength));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001665 }
1666
1667 virtual void setLangOptions(const LangOptions *LO) {
1668 Chain1->setLangOptions(LO);
1669 Chain2->setLangOptions(LO);
1670 }
1671
1672 virtual bool IncludeInDiagnosticCounts() const {
1673 return Chain1->IncludeInDiagnosticCounts();
1674 }
1675
1676 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1677 const DiagnosticInfo &Info) {
1678 Chain1->HandleDiagnostic(DiagLevel, Info);
1679 Chain2->HandleDiagnostic(DiagLevel, Info);
1680 }
1681};
1682} // end anonymous namespace.
1683
1684static void SetUpBuildDumpLog(unsigned argc, char **argv,
1685 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1686
1687 std::string ErrorInfo;
1688 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1689 ErrorInfo);
1690
1691 if (!ErrorInfo.empty()) {
1692 llvm::errs() << "error opening -dump-build-information file '"
1693 << DumpBuildInformation << "', option ignored!\n";
1694 delete BuildLogFile;
1695 BuildLogFile = 0;
1696 DumpBuildInformation = "";
1697 return;
1698 }
1699
1700 (*BuildLogFile) << "clang-cc command line arguments: ";
1701 for (unsigned i = 0; i != argc; ++i)
1702 (*BuildLogFile) << argv[i] << ' ';
1703 (*BuildLogFile) << '\n';
1704
1705 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1706 // the diagnostic producers and the normal receiver.
1707 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1708}
1709
1710
1711
1712//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001713// Main driver
1714//===----------------------------------------------------------------------===//
1715
Eli Friedman66d6f042009-05-18 22:20:00 +00001716static llvm::raw_ostream* ComputeOutFile(const std::string& InFile,
1717 const char* Extension,
1718 bool Binary,
1719 llvm::sys::Path& OutPath) {
1720 llvm::raw_ostream* Ret;
1721 bool UseStdout = false;
1722 std::string OutFile;
1723 if (OutputFile == "-" || (OutputFile.empty() && InFile == "-")) {
1724 UseStdout = true;
1725 } else if (!OutputFile.empty()) {
1726 OutFile = OutputFile;
1727 } else if (Extension) {
1728 llvm::sys::Path Path(InFile);
1729 Path.eraseSuffix();
1730 Path.appendSuffix(Extension);
1731 OutFile = Path.toString();
1732 } else {
1733 UseStdout = true;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001734 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001735
Eli Friedman66d6f042009-05-18 22:20:00 +00001736 if (UseStdout) {
1737 Ret = new llvm::raw_stdout_ostream();
1738 if (Binary)
1739 llvm::sys::Program::ChangeStdoutToBinary();
1740 } else {
1741 std::string Error;
1742 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Binary, Error);
1743 if (!Error.empty()) {
1744 // FIXME: Don't fail this way.
1745 llvm::cerr << "ERROR: " << Error << "\n";
1746 ::exit(1);
1747 }
1748 OutPath = OutFile;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001749 }
Eli Friedman66d6f042009-05-18 22:20:00 +00001750
1751 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001752}
1753
Reid Spencer5f016e22007-07-11 17:01:13 +00001754/// ProcessInputFile - Process a single input file with the specified state.
1755///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001756static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001757 const std::string &InFile, ProgActions PA,
1758 const llvm::StringMap<bool> &Features) {
Eli Friedman66d6f042009-05-18 22:20:00 +00001759 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001760 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001761 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001762 FixItRewriter *FixItRewrite = 0;
Douglas Gregorf807fe02009-04-14 16:27:31 +00001763 bool CompleteTranslationUnit = true;
Eli Friedman66d6f042009-05-18 22:20:00 +00001764 llvm::sys::Path OutPath;
Douglas Gregor558cb562009-04-02 01:08:08 +00001765
Ted Kremenek85888962008-10-21 00:54:44 +00001766 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 default:
Eli Friedman66d6f042009-05-18 22:20:00 +00001768 fprintf(stderr, "Unexpected program action!\n");
1769 HadErrors = true;
1770 return;
1771
1772 case ASTPrint:
1773 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1774 Consumer.reset(CreateASTPrinter(OS.get()));
1775 break;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001776
Douglas Gregoree75c052009-05-21 20:55:50 +00001777 case ASTPrintXML:
1778 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
1779 Consumer.reset(CreateASTPrinterXML(OS.get()));
1780 break;
1781
Eli Friedman66d6f042009-05-18 22:20:00 +00001782 case ASTDump:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001783 Consumer.reset(CreateASTDumper());
Eli Friedman66d6f042009-05-18 22:20:00 +00001784 break;
1785
Eli Friedman66d6f042009-05-18 22:20:00 +00001786 case ASTView:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001787 Consumer.reset(CreateASTViewer());
Eli Friedman66d6f042009-05-18 22:20:00 +00001788 break;
1789
1790 case PrintDeclContext:
1791 Consumer.reset(CreateDeclContextPrinter());
1792 break;
1793
1794 case EmitHTML:
1795 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1796 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1797 break;
1798
1799 case InheritanceView:
1800 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1801 break;
1802
1803 case EmitAssembly:
1804 case EmitLLVM:
1805 case EmitBC:
1806 case EmitLLVMOnly: {
1807 BackendAction Act;
1808 if (ProgAction == EmitAssembly) {
1809 Act = Backend_EmitAssembly;
1810 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1811 } else if (ProgAction == EmitLLVM) {
1812 Act = Backend_EmitLL;
1813 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1814 } else if (ProgAction == EmitLLVMOnly) {
1815 Act = Backend_EmitNothing;
1816 } else {
1817 Act = Backend_EmitBC;
1818 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001819 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001820
Eli Friedman66d6f042009-05-18 22:20:00 +00001821 CompileOptions Opts;
1822 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1823 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1824 PP.getLangOptions(), Opts, InFile,
1825 OS.get()));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001826 break;
Eli Friedman66d6f042009-05-18 22:20:00 +00001827 }
1828
1829 case GeneratePCH:
1830 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1831 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
1832 CompleteTranslationUnit = false;
1833 break;
1834
1835 case RewriteObjC:
1836 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedmanbce831b2009-05-18 22:29:17 +00001837 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001838 PP.getLangOptions(),
1839 SilenceRewriteMacroWarning));
Eli Friedman66d6f042009-05-18 22:20:00 +00001840 break;
1841
1842 case RewriteBlocks:
1843 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1844 PP.getLangOptions()));
1845 break;
1846
Eli Friedmane71b85f2009-05-19 10:18:02 +00001847 case RunAnalysis: {
Eli Friedman66d6f042009-05-18 22:20:00 +00001848 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedmane71b85f2009-05-19 10:18:02 +00001849 PP.getLangOptions(), OutputFile,
1850 ReadAnalyzerOptions()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001851 break;
Eli Friedmane71b85f2009-05-19 10:18:02 +00001852 }
Eli Friedman66d6f042009-05-18 22:20:00 +00001853
Chris Lattnerc106c102008-10-12 05:03:36 +00001854 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001855 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001856 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001857 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001858 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001859 RawLex.SetKeepWhitespaceMode(true);
1860
1861 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001862 RawLex.LexFromRawLexer(RawTok);
1863 while (RawTok.isNot(tok::eof)) {
1864 PP.DumpToken(RawTok, true);
1865 fprintf(stderr, "\n");
1866 RawLex.LexFromRawLexer(RawTok);
1867 }
1868 ClearSourceMgr = true;
1869 break;
1870 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001872 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001873 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001874 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001875 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 do {
1877 PP.Lex(Tok);
1878 PP.DumpToken(Tok, true);
1879 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001880 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001881 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001882 break;
1883 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001884 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 break;
Ted Kremenek85888962008-10-21 00:54:44 +00001886
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001887 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001888 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001889 if (OutputFile.empty() || OutputFile == "-") {
1890 // FIXME: Don't fail this way.
1891 // FIXME: Verify that we can actually seek in the given file.
1892 llvm::cerr << "ERROR: PTH requires an seekable file for output!\n";
1893 ::exit(1);
1894 }
1895 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1896 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001897 ClearSourceMgr = true;
1898 break;
1899 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001900
Chris Lattnercc7dea82009-04-27 22:02:30 +00001901 case PrintPreprocessedInput:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001902 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001903 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001904
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001905 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 break;
1907
Chris Lattner47099742009-02-18 01:51:21 +00001908 case ParsePrintCallbacks: {
1909 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001910 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1911 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001912 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 break;
Chris Lattner47099742009-02-18 01:51:21 +00001914 }
1915
1916 case ParseSyntaxOnly: { // -fsyntax-only
1917 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001918 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001919 break;
Chris Lattner47099742009-02-18 01:51:21 +00001920 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001921
1922 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001923 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1924 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001925 ClearSourceMgr = true;
1926 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001927
Eli Friedmanf54fce82009-05-19 01:02:07 +00001928 case RewriteTest:
1929 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1930 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001931 ClearSourceMgr = true;
1932 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001933
1934 case FixIt:
1935 llvm::TimeRegion Timer(ClangFrontendTimer);
1936 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001937 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001938 PP.getSourceManager(),
1939 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001940 break;
Chris Lattner47099742009-02-18 01:51:21 +00001941 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001942
Chris Lattner1aee61a2009-04-27 21:25:27 +00001943 if (FixItAtLocations.size() > 0) {
1944 // Even without the "-fixit" flag, with may have some specific
1945 // locations where the user has requested fixes. Process those
1946 // locations now.
1947 if (!FixItRewrite)
1948 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1949 PP.getSourceManager(),
1950 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001951
Chris Lattner1aee61a2009-04-27 21:25:27 +00001952 bool AddedFixitLocation = false;
1953 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1954 Idx != Last; ++Idx) {
1955 RequestedSourceLocation Requested;
1956 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1957 Requested)) {
1958 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1959 FixItAtLocations[Idx].FileName.c_str());
1960 } else {
1961 FixItRewrite->addFixItLocation(Requested);
1962 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001963 }
1964 }
1965
Chris Lattner1aee61a2009-04-27 21:25:27 +00001966 if (!AddedFixitLocation) {
1967 // All of the fix-it locations were bad. Don't fix anything.
1968 delete FixItRewrite;
1969 FixItRewrite = 0;
1970 }
1971 }
1972
1973 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001974 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001975 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1976 PP.getSourceManager(),
1977 PP.getTargetInfo(),
1978 PP.getIdentifierTable(),
1979 PP.getSelectorTable(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001980 /* FreeMemory = */ !DisableFree,
1981 /* size_reserve = */0,
1982 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattnercc7dea82009-04-27 22:02:30 +00001983 llvm::OwningPtr<PCHReader> Reader;
1984 llvm::OwningPtr<ExternalASTSource> Source;
1985
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001986 if (!ImplicitIncludePCH.empty()) {
Chris Lattnercc7dea82009-04-27 22:02:30 +00001987 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1988
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001989 // The user has asked us to include a precompiled header. Load
1990 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001991 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1992 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00001993 // Set the predefines buffer as suggested by the PCH
1994 // reader. Typically, the predefines buffer will be empty.
1995 PP.setPredefines(Reader->getSuggestedPredefines());
1996
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001997 // Attach the PCH reader to the AST context as an external AST
1998 // source, so that declarations will be deserialized from the
1999 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00002000 if (ContextOwner) {
2001 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00002002 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002003 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002004 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002005 }
2006
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002007 case PCHReader::Failure:
2008 // Unrecoverable failure: don't even try to process the input
2009 // file.
2010 return;
2011
2012 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002013 // No suitable PCH file could be found. Return an error.
2014 return;
2015
2016#if 0
2017 // FIXME: We can recover from failed attempts to load PCH
2018 // files. This code will do so, if we ever want to enable it.
2019
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002020 // We delayed the initialization of builtins in the hope of
2021 // loading the PCH file. Since the PCH file could not be
2022 // loaded, initialize builtins now.
2023 if (ContextOwner)
2024 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002025#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002026 }
2027
2028 // Finish preprocessor initialization. We do this now (rather
2029 // than earlier) because this initialization creates new source
2030 // location entries in the source manager, which must come after
2031 // the source location entries for the PCH file.
2032 if (InitializeSourceManager(PP, InFile))
2033 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00002034 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002035
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002036
2037 // If we have an ASTConsumer, run the parser with it.
2038 if (Consumer)
2039 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2040 CompleteTranslationUnit);
2041
2042 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2043 llvm::TimeRegion Timer(ClangFrontendTimer);
2044 Token Tok;
2045 // Start parsing the specified input file.
2046 PP.EnterMainSourceFile();
2047 do {
2048 PP.Lex(Tok);
2049 } while (Tok.isNot(tok::eof));
2050 ClearSourceMgr = true;
2051 } else if (PA == ParseNoop) { // -parse-noop
2052 llvm::TimeRegion Timer(ClangFrontendTimer);
2053 ParseFile(PP, new MinimalAction(PP));
2054 ClearSourceMgr = true;
Chris Lattnercc7dea82009-04-27 22:02:30 +00002055 } else if (PA == PrintPreprocessedInput){ // -E mode.
2056 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002057 if (DumpMacros)
2058 DoPrintMacros(PP, OS.get());
2059 else
2060 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2061 EnableMacroCommentOutput,
2062 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002063 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002064 }
2065
Chris Lattner1aee61a2009-04-27 21:25:27 +00002066 if (FixItRewrite)
2067 FixItRewrite->WriteFixedFile(InFile, OutputFile);
2068
2069 // If in -disable-free mode, don't deallocate ASTContext.
2070 if (DisableFree)
2071 ContextOwner.take();
2072 else
2073 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002074
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002075 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002076 if (CheckDiagnostics(PP))
2077 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002078
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002080 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 PP.PrintStats();
2082 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002083 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002084 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 fprintf(stderr, "\n");
2086 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002087
2088 // For a multi-file compilation, some things are ok with nuking the source
2089 // manager tables, other require stable fileid/macroid's across multiple
2090 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002091 if (ClearSourceMgr)
2092 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002093
2094 if (DisableFree)
2095 Consumer.take();
Eli Friedman66d6f042009-05-18 22:20:00 +00002096 else
2097 Consumer.reset();
2098
2099 // Always delete the output stream because we don't want to leak file
2100 // handles. Also, we don't want to try to erase an open file.
2101 OS.reset();
2102
2103 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2104 !OutPath.isEmpty()) {
2105 // If we had errors, try to erase the output file.
2106 OutPath.eraseFromDisk();
2107 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002108}
2109
2110static llvm::cl::list<std::string>
2111InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2112
Reid Spencer5f016e22007-07-11 17:01:13 +00002113int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002115 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00002116 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00002117 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002118
Chris Lattner47099742009-02-18 01:51:21 +00002119 if (TimeReport)
2120 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2121
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002122 if (Verbose)
2123 fprintf(stderr, "clang-cc version 1.0 based upon " PACKAGE_STRING
2124 " hosted on " LLVM_HOSTTRIPLE "\n");
2125
Reid Spencer5f016e22007-07-11 17:01:13 +00002126 // If no input was specified, read from stdin.
2127 if (InputFilenames.empty())
2128 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002129
Ted Kremenek31e703b2007-12-11 23:28:38 +00002130 // Create the diagnostic client for reporting errors or for
2131 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002132 llvm::OwningPtr<DiagnosticClient> DiagClient;
2133 if (VerifyDiagnostics) {
2134 // When checking diagnostics, just buffer them up.
2135 DiagClient.reset(new TextDiagnosticBuffer());
2136 if (InputFilenames.size() != 1) {
2137 fprintf(stderr, "-verify only works on single input files for now.\n");
2138 return 1;
2139 }
2140 if (!HTMLDiag.empty()) {
2141 fprintf(stderr, "-verify and -html-diags don't work together\n");
2142 return 1;
2143 }
2144 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002145 // Print diagnostics to stderr by default.
Douglas Gregor68a0d782009-05-02 00:03:46 +00002146
2147 // If -fmessage-length=N was not specified, determine whether this
2148 // is a terminal and, if so, implicitly define -fmessage-length
2149 // appropriately.
2150 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregor67187ce2009-05-11 18:06:49 +00002151 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor68a0d782009-05-02 00:03:46 +00002152
Chris Lattner409d4e72009-04-17 20:40:01 +00002153 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00002154 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00002155 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00002156 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00002157 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00002158 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00002159 !NoDiagnosticsFixIt,
2160 MessageLength));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002161 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00002162 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00002163 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002164
2165 if (!DumpBuildInformation.empty()) {
2166 if (!HTMLDiag.empty()) {
2167 fprintf(stderr,
2168 "-dump-build-information and -html-diags don't work together\n");
2169 return 1;
2170 }
2171
2172 SetUpBuildDumpLog(argc, argv, DiagClient);
2173 }
2174
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002175
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002177 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002178 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2179 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002180 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002181
Chris Lattner4f037832007-12-05 23:24:17 +00002182 // -I- is a deprecated GCC feature, scan for it and reject it.
2183 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2184 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00002185 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00002186 I_dirs.erase(I_dirs.begin()+i);
2187 --i;
2188 }
2189 }
Chris Lattner11215192008-03-14 06:12:05 +00002190
2191 // Get information about the target being compiled for.
2192 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00002193 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2194
Chris Lattner11215192008-03-14 06:12:05 +00002195 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00002196 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2197 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002198 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002199 }
Chris Lattner4f037832007-12-05 23:24:17 +00002200
Daniel Dunbard4270232009-01-20 23:17:32 +00002201 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002202 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002203
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00002204 llvm::OwningPtr<SourceManager> SourceMgr;
2205
Chris Lattner2c78b872009-04-14 23:22:57 +00002206 // Create a file manager object to provide access to and cache the filesystem.
2207 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002208
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002209 // Compute the feature set, unfortunately this effects the language!
2210 llvm::StringMap<bool> Features;
2211 ComputeFeatureMap(Target.get(), Features);
2212
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002214 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00002215
Chris Lattnerf63aea32009-03-04 21:40:56 +00002216 /// Create a SourceManager object. This tracks and owns all the file
2217 /// buffers allocated to a translation unit.
2218 if (!SourceMgr)
2219 SourceMgr.reset(new SourceManager());
2220 else
2221 SourceMgr->clearIDTables();
2222
2223 // Initialize language options, inferring file types from input filenames.
2224 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002225 DiagClient->setLangOptions(&LangInfo);
Chris Lattner2c78b872009-04-14 23:22:57 +00002226
Chris Lattnerf63aea32009-03-04 21:40:56 +00002227 InitializeBaseLanguage();
2228 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002229 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002230 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002231
2232 // Process the -I options and set them in the HeaderInfo.
2233 HeaderSearch HeaderInfo(FileMgr);
2234
Chris Lattner2c78b872009-04-14 23:22:57 +00002235
Chris Lattnerf63aea32009-03-04 21:40:56 +00002236 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2237
2238 // Set up the preprocessor with these options.
Eli Friedmanf086e3b2009-05-18 07:39:39 +00002239 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattnerf63aea32009-03-04 21:40:56 +00002240 *SourceMgr.get(), HeaderInfo);
2241
2242 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2243
2244 if (!PP)
2245 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002246
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002247 // Handle generating dependencies, if requested
2248 if (!DependencyFile.empty()) {
2249 llvm::raw_ostream *DependencyOS;
2250 if (DependencyTargets.empty()) {
2251 // FIXME: Use a proper diagnostic
2252 llvm::cerr << "-dependency-file requires at least one -MT option\n";
2253 HadErrors = true;
2254 continue;
2255 }
2256 std::string ErrStr;
2257 DependencyOS =
2258 new llvm::raw_fd_ostream(DependencyFile.c_str(), false, ErrStr);
2259 if (!ErrStr.empty()) {
2260 // FIXME: Use a proper diagnostic
2261 llvm::cerr << "unable to open dependency file: " + ErrStr;
2262 HadErrors = true;
2263 continue;
2264 }
2265
2266 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2267 DependenciesIncludeSystemHeaders,
2268 PhonyDependencyTarget);
2269 }
2270
Douglas Gregore1d918e2009-04-10 23:10:45 +00002271 if (ImplicitIncludePCH.empty() &&
2272 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregor14f79002009-04-10 03:52:48 +00002273 continue;
2274
Chris Lattner409d4e72009-04-17 20:40:01 +00002275 if (!HTMLDiag.empty())
2276 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002277
2278 // Process the source file.
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002279 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002280
Chris Lattner40469652009-04-17 20:16:08 +00002281 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002282 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002283 }
Chris Lattner11215192008-03-14 06:12:05 +00002284
Mike Stumpfc0fed32009-04-28 01:19:10 +00002285 if (!NoCaretDiagnostics)
2286 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2287 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2288 (NumDiagnostics == 1 ? "" : "s"));
Reid Spencer5f016e22007-07-11 17:01:13 +00002289
2290 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002291 FileMgr.PrintStats();
2292 fprintf(stderr, "\n");
2293 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002294
2295 delete ClangFrontendTimer;
2296 delete BuildLogFile;
Reid Spencer5f016e22007-07-11 17:01:13 +00002297
Daniel Dunbar276373d2008-10-27 22:10:13 +00002298 // If verifying diagnostics and we reached here, all is well.
2299 if (VerifyDiagnostics)
2300 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00002301
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002302 // Managed static deconstruction. Useful for making things like
2303 // -time-passes usable.
2304 llvm::llvm_shutdown();
2305
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002306 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002307}