blob: 1f1ae8588a48786296e0494015cf36e4fd45f907 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattner39fb14e2009-02-18 01:17:01 +000020// -Wfatal-errors
Chris Lattner4b009652007-07-25 00:24:17 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Eli Friedman7efefa52009-05-19 21:10:40 +000025#include "clang/Frontend/AnalysisConsumer.h"
Eli Friedmanbc821a42009-05-18 23:02:01 +000026#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor133d2552009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattner94269d72009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Eli Friedman7e1d6372009-05-19 04:14:29 +000036#include "clang/Frontend/Utils.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000037#include "clang/Analysis/PathDiagnostic.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000038#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000039#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000040#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000041#include "clang/AST/ASTConsumer.h"
Chris Lattnerfc318192009-03-28 04:31:31 +000042#include "clang/AST/ASTContext.h"
43#include "clang/AST/Decl.h"
Chris Lattnera17991f2009-03-29 16:50:03 +000044#include "clang/AST/DeclGroup.h"
Chris Lattner4b009652007-07-25 00:24:17 +000045#include "clang/Parse/Parser.h"
46#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000047#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000048#include "clang/Basic/FileManager.h"
49#include "clang/Basic/SourceManager.h"
50#include "clang/Basic/TargetInfo.h"
Daniel Dunbarae81a792009-05-06 04:07:06 +000051#include "clang/Basic/Version.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000052#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000053#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000054#include "llvm/ADT/StringExtras.h"
Daniel Dunbar07181d72009-05-06 03:16:41 +000055#include "llvm/ADT/StringMap.h"
Chris Lattner0e004a12009-04-08 18:24:34 +000056#include "llvm/ADT/STLExtras.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000057#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000058#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000059#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000060#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000061#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000062#include "llvm/Support/PrettyStackTrace.h"
Eli Friedmana9c310842009-05-18 22:20:00 +000063#include "llvm/Support/Streams.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000064#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000065#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000066#include "llvm/System/Path.h"
Douglas Gregor3dd11e82009-05-03 03:52:38 +000067#include "llvm/System/Process.h"
Eli Friedmana9c310842009-05-18 22:20:00 +000068#include "llvm/System/Program.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000069#include "llvm/System/Signals.h"
Chris Lattner4d495682009-06-17 17:25:50 +000070#include "llvm/Target/TargetSelect.h"
Douglas Gregor24b48b02009-04-02 19:05:20 +000071#include <cstdlib>
Douglas Gregor3dd11e82009-05-03 03:52:38 +000072#if HAVE_SYS_TYPES_H
Douglas Gregor965a13c2009-05-02 00:03:46 +000073# include <sys/types.h>
74#endif
Douglas Gregor24b48b02009-04-02 19:05:20 +000075
Chris Lattner4b009652007-07-25 00:24:17 +000076using namespace clang;
77
78//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000079// Source Location Parser
80//===----------------------------------------------------------------------===//
81
82/// \brief A source location that has been parsed on the command line.
83struct ParsedSourceLocation {
84 std::string FileName;
85 unsigned Line;
86 unsigned Column;
87
88 /// \brief Try to resolve the file name of a parsed source location.
89 ///
90 /// \returns true if there was an error, false otherwise.
91 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
92};
93
94bool
95ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
96 RequestedSourceLocation &Result) {
97 const FileEntry *File = FileMgr.getFile(FileName);
98 if (!File)
99 return true;
100
101 Result.File = File;
102 Result.Line = Line;
103 Result.Column = Column;
104 return false;
105}
106
107namespace llvm {
108 namespace cl {
109 /// \brief Command-line option parser that parses source locations.
110 ///
111 /// Source locations are of the form filename:line:column.
112 template<>
113 class parser<ParsedSourceLocation>
114 : public basic_parser<ParsedSourceLocation> {
115 public:
116 bool parse(Option &O, const char *ArgName,
117 const std::string &ArgValue,
118 ParsedSourceLocation &Val);
119 };
120
121 bool
122 parser<ParsedSourceLocation>::
123 parse(Option &O, const char *ArgName, const std::string &ArgValue,
124 ParsedSourceLocation &Val) {
125 using namespace clang;
126
127 const char *ExpectedFormat
128 = "source location must be of the form filename:line:column";
129 std::string::size_type SecondColon = ArgValue.rfind(':');
130 if (SecondColon == std::string::npos) {
131 std::fprintf(stderr, "%s\n", ExpectedFormat);
132 return true;
133 }
134 char *EndPtr;
135 long Column
136 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
137 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
138 std::fprintf(stderr, "%s\n", ExpectedFormat);
139 return true;
140 }
141
142 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
143 if (SecondColon == std::string::npos) {
144 std::fprintf(stderr, "%s\n", ExpectedFormat);
145 return true;
146 }
147 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
148 if (EndPtr != ArgValue.c_str() + SecondColon) {
149 std::fprintf(stderr, "%s\n", ExpectedFormat);
150 return true;
151 }
152
153 Val.FileName = ArgValue.substr(0, FirstColon);
154 Val.Line = Line;
155 Val.Column = Column;
156 return false;
157 }
158 }
159}
160
161//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000162// Global options.
163//===----------------------------------------------------------------------===//
164
Chris Lattnerefe33382009-02-18 01:51:21 +0000165/// ClangFrontendTimer - The front-end activities should charge time to it with
166/// TimeRegion. The -ftime-report option controls whether this will do
167/// anything.
168llvm::Timer *ClangFrontendTimer = 0;
169
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000170static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000171
Chris Lattner4b009652007-07-25 00:24:17 +0000172static llvm::cl::opt<bool>
173Verbose("v", llvm::cl::desc("Enable verbose output"));
174static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000175Stats("print-stats",
176 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000177static llvm::cl::opt<bool>
178DisableFree("disable-free",
179 llvm::cl::desc("Disable freeing of memory on exit"),
180 llvm::cl::init(false));
Daniel Dunbarbb56def2009-04-27 21:19:07 +0000181static llvm::cl::opt<bool>
182EmptyInputOnly("empty-input-only",
183 llvm::cl::desc("Force running on an empty input file"));
Chris Lattner4b009652007-07-25 00:24:17 +0000184
185enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000186 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000187 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000188 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000189 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000190 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000191 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000192 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000193 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000194 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000195 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek24612ae2008-03-18 21:19:49 +0000196 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000197 ASTPrint, // Parse ASTs and print them.
Douglas Gregor8987c032009-05-21 20:55:50 +0000198 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000199 ASTDump, // Parse ASTs and dump them.
200 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000201 PrintDeclContext, // Print DeclContext and their Decls.
Chris Lattner4b009652007-07-25 00:24:17 +0000202 ParsePrintCallbacks, // Parse and print each callback.
203 ParseSyntaxOnly, // Parse and perform semantic analysis.
204 ParseNoop, // Parse with noop callbacks.
205 RunPreprocessorOnly, // Just lex, no output.
206 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000207 DumpTokens, // Dump out preprocessed tokens.
208 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000209 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000210 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000211 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000212 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000213};
214
215static llvm::cl::opt<ProgActions>
216ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
217 llvm::cl::init(ParseSyntaxOnly),
218 llvm::cl::values(
219 clEnumValN(RunPreprocessorOnly, "Eonly",
220 "Just run preprocessor, no output (for timings)"),
221 clEnumValN(PrintPreprocessedInput, "E",
222 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000223 clEnumValN(DumpRawTokens, "dump-raw-tokens",
224 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000225 clEnumValN(RunAnalysis, "analyze",
226 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000227 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000228 "Run preprocessor, dump internal rep of tokens"),
229 clEnumValN(ParseNoop, "parse-noop",
230 "Run parser with noop callbacks (for timings)"),
231 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
232 "Run parser and perform semantic analysis"),
233 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
234 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000235 clEnumValN(EmitHTML, "emit-html",
236 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000237 clEnumValN(ASTPrint, "ast-print",
238 "Build ASTs and then pretty-print them"),
Douglas Gregor8987c032009-05-21 20:55:50 +0000239 clEnumValN(ASTPrintXML, "ast-print-xml",
240 "Build ASTs and then print them in XML format"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000241 clEnumValN(ASTDump, "ast-dump",
242 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000243 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000244 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000245 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000246 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000247 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000248 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000249 clEnumValN(GeneratePCH, "emit-pch",
250 "Generate pre-compiled header file"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000251 clEnumValN(EmitAssembly, "S",
252 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000253 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000254 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000255 clEnumValN(EmitBC, "emit-llvm-bc",
256 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000257 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
258 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000259 clEnumValN(RewriteTest, "rewrite-test",
260 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000261 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000262 "Rewrite ObjC into C (code rewriter example)"),
263 clEnumValN(RewriteMacros, "rewrite-macros",
264 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000265 clEnumValN(RewriteBlocks, "rewrite-blocks",
266 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000267 clEnumValN(FixIt, "fixit",
268 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000269 clEnumValEnd));
270
Ted Kremenekd01eae62007-12-19 19:47:59 +0000271
272static llvm::cl::opt<std::string>
273OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000274 llvm::cl::value_desc("path"),
Douglas Gregor608ff622009-04-22 21:45:53 +0000275 llvm::cl::desc("Specify output file"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000276
Ted Kremenek57f25b22008-12-02 19:57:31 +0000277
278//===----------------------------------------------------------------------===//
279// PTH.
280//===----------------------------------------------------------------------===//
281
282static llvm::cl::opt<std::string>
283TokenCache("token-cache", llvm::cl::value_desc("path"),
284 llvm::cl::desc("Use specified token cache file"));
285
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000286//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000287// Diagnostic Options
288//===----------------------------------------------------------------------===//
289
Ted Kremenek10389cf2007-09-26 19:42:19 +0000290static llvm::cl::opt<bool>
291VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000292 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000293
Ted Kremenekfd75e312008-03-27 06:17:42 +0000294static llvm::cl::opt<std::string>
295HTMLDiag("html-diags",
296 llvm::cl::desc("Generate HTML to report diagnostics"),
297 llvm::cl::value_desc("HTML directory"));
298
Nico Weber0e13eaa2008-08-05 23:33:20 +0000299static llvm::cl::opt<bool>
300NoShowColumn("fno-show-column",
301 llvm::cl::desc("Do not include column number on diagnostics"));
302
303static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000304NoShowLocation("fno-show-source-location",
305 llvm::cl::desc("Do not include source location information with"
306 " diagnostics"));
307
308static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000309NoCaretDiagnostics("fno-caret-diagnostics",
310 llvm::cl::desc("Do not include source line and caret with"
311 " diagnostics"));
312
Chris Lattner695a4f52009-03-13 01:08:23 +0000313static llvm::cl::opt<bool>
Chris Lattner041bd732009-04-19 07:44:08 +0000314NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
315 llvm::cl::desc("Do not include fixit information in"
316 " diagnostics"));
317
318static llvm::cl::opt<bool>
Chris Lattner13bac9e2009-04-21 05:34:31 +0000319PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
320 llvm::cl::desc("Print source range spans in numeric form"));
321
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000322static llvm::cl::opt<bool>
323PrintDiagnosticOption("fdiagnostics-show-option",
324 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weber0e13eaa2008-08-05 23:33:20 +0000325
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000326static llvm::cl::opt<unsigned>
327MessageLength("fmessage-length",
328 llvm::cl::desc("Format message diagnostics so that they fit "
329 "within N columns or fewer, when possible."),
330 llvm::cl::value_desc("N"));
331
Edwin Törökeff37122009-06-04 07:18:23 +0000332static llvm::cl::opt<bool>
Edwin Törökcca1e502009-06-04 07:27:53 +0000333NoColorDiagnostic("fno-color-diagnostics",
Edwin Törökeff37122009-06-04 07:18:23 +0000334 llvm::cl::desc("Don't use colors when showing diagnostics "
335 "(automatically turned off if output is not a "
336 "terminal)."));
Chris Lattner4b009652007-07-25 00:24:17 +0000337//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000338// C++ Visualization.
339//===----------------------------------------------------------------------===//
340
341static llvm::cl::opt<std::string>
342InheritanceViewCls("cxx-inheritance-view",
343 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000344 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000345
346//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000347// Builtin Options
348//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000349
350static llvm::cl::opt<bool>
351TimeReport("ftime-report",
352 llvm::cl::desc("Print the amount of time each "
353 "phase of compilation takes"));
354
Douglas Gregor23d23262009-02-14 20:49:29 +0000355static llvm::cl::opt<bool>
356Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000357 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000358 "freestanding environment"));
359
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000360static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000361AllowBuiltins("fbuiltin", llvm::cl::init(true),
362 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000363
364
365static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000366MathErrno("fmath-errno", llvm::cl::init(true),
367 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000368
Douglas Gregor23d23262009-02-14 20:49:29 +0000369//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000370// Language Options
371//===----------------------------------------------------------------------===//
372
373enum LangKind {
374 langkind_unspecified,
375 langkind_c,
376 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000377 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000378 langkind_cxx,
379 langkind_cxx_cpp,
380 langkind_objc,
381 langkind_objc_cpp,
382 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000383 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000384};
385
Chris Lattner4b009652007-07-25 00:24:17 +0000386static llvm::cl::opt<LangKind>
387BaseLang("x", llvm::cl::desc("Base language to compile"),
388 llvm::cl::init(langkind_unspecified),
389 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
390 clEnumValN(langkind_cxx, "c++", "C++"),
391 clEnumValN(langkind_objc, "objective-c", "Objective C"),
392 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000393 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000394 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000395 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
396 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000397 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000398 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000399 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
400 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000401 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000402 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000403 clEnumValN(langkind_c, "c-header",
404 "C header"),
405 clEnumValN(langkind_objc, "objective-c-header",
406 "Objective-C header"),
407 clEnumValN(langkind_cxx, "c++-header",
408 "C++ header"),
409 clEnumValN(langkind_objcxx, "objective-c++-header",
410 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000411 clEnumValEnd));
412
413static llvm::cl::opt<bool>
414LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
415 llvm::cl::Hidden);
416static llvm::cl::opt<bool>
417LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
418 llvm::cl::Hidden);
419
Chris Lattnere1be6022009-04-14 23:22:57 +0000420static llvm::cl::opt<bool>
421ObjCExclusiveGC("fobjc-gc-only",
422 llvm::cl::desc("Use GC exclusively for Objective-C related "
423 "memory management"));
424
425static llvm::cl::opt<bool>
426ObjCEnableGC("fobjc-gc",
427 llvm::cl::desc("Enable Objective-C garbage collection"));
428
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000429static llvm::cl::opt<bool>
430ObjCEnableGCBitmapPrint("print-ivar-layout",
431 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
432
Chris Lattnere1be6022009-04-14 23:22:57 +0000433static llvm::cl::opt<LangOptions::VisibilityMode>
434SymbolVisibility("fvisibility",
435 llvm::cl::desc("Set the default symbol visibility:"),
436 llvm::cl::init(LangOptions::Default),
437 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
438 "Use default symbol visibility"),
439 clEnumValN(LangOptions::Hidden, "hidden",
440 "Use hidden symbol visibility"),
441 clEnumValN(LangOptions::Protected,"protected",
442 "Use protected symbol visibility"),
443 clEnumValEnd));
444
445static llvm::cl::opt<bool>
446OverflowChecking("ftrapv",
447 llvm::cl::desc("Trap on integer overflow"),
448 llvm::cl::init(false));
449
Fariborz Jahanianfefd5e82009-05-22 20:17:16 +0000450static llvm::cl::opt<bool>
451ObjCSenderDispatch("fobjc-sender-dependent-dispatch",
452 llvm::cl::desc("Enable sender-dependent dispatch for"
453 "Objective-C messages"), llvm::cl::init(false));
Chris Lattnere1be6022009-04-14 23:22:57 +0000454
Ted Kremenek11ad8952007-12-05 23:49:08 +0000455/// InitializeBaseLanguage - Handle the -x foo options.
456static void InitializeBaseLanguage() {
457 if (LangObjC)
458 BaseLang = langkind_objc;
459 else if (LangObjCXX)
460 BaseLang = langkind_objcxx;
461}
462
463static LangKind GetLanguage(const std::string &Filename) {
464 if (BaseLang != langkind_unspecified)
465 return BaseLang;
466
467 std::string::size_type DotPos = Filename.rfind('.');
468
469 if (DotPos == std::string::npos) {
470 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000471 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000472 }
473
Ted Kremenek11ad8952007-12-05 23:49:08 +0000474 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
475 // C header: .h
476 // C++ header: .hh or .H;
477 // assembler no preprocessing: .s
478 // assembler: .S
479 if (Ext == "c")
480 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000481 else if (Ext == "S" ||
482 // If the compiler is run on a .s file, preprocess it as .S
483 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000484 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000485 else if (Ext == "i")
486 return langkind_c_cpp;
487 else if (Ext == "ii")
488 return langkind_cxx_cpp;
489 else if (Ext == "m")
490 return langkind_objc;
491 else if (Ext == "mi")
492 return langkind_objc_cpp;
493 else if (Ext == "mm" || Ext == "M")
494 return langkind_objcxx;
495 else if (Ext == "mii")
496 return langkind_objcxx_cpp;
497 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
498 Ext == "c++" || Ext == "cp" || Ext == "cxx")
499 return langkind_cxx;
500 else
501 return langkind_c;
502}
503
504
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000505static void InitializeCOptions(LangOptions &Options) {
506 // Do nothing.
507}
508
509static void InitializeObjCOptions(LangOptions &Options) {
510 Options.ObjC1 = Options.ObjC2 = 1;
511}
512
513
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000514static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000515 // FIXME: implement -fpreprocessed mode.
516 bool NoPreprocess = false;
517
Ted Kremenek11ad8952007-12-05 23:49:08 +0000518 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000519 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000520 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000521 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000522 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000523 case langkind_c_cpp:
524 NoPreprocess = true;
525 // FALLTHROUGH
526 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000527 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000528 break;
529 case langkind_cxx_cpp:
530 NoPreprocess = true;
531 // FALLTHROUGH
532 case langkind_cxx:
533 Options.CPlusPlus = 1;
534 break;
535 case langkind_objc_cpp:
536 NoPreprocess = true;
537 // FALLTHROUGH
538 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000539 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000540 break;
541 case langkind_objcxx_cpp:
542 NoPreprocess = true;
543 // FALLTHROUGH
544 case langkind_objcxx:
545 Options.ObjC1 = Options.ObjC2 = 1;
546 Options.CPlusPlus = 1;
547 break;
548 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000549
550 if (ObjCExclusiveGC)
551 Options.setGCMode(LangOptions::GCOnly);
552 else if (ObjCEnableGC)
553 Options.setGCMode(LangOptions::HybridGC);
554
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000555 if (ObjCEnableGCBitmapPrint)
556 Options.ObjCGCBitmapPrint = 1;
557
Chris Lattnere1be6022009-04-14 23:22:57 +0000558 Options.setVisibilityMode(SymbolVisibility);
559 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000560}
561
562/// LangStds - Language standards we support.
563enum LangStds {
564 lang_unspecified,
565 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000566 lang_gnu_START,
567 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000568 lang_cxx98, lang_gnucxx98,
569 lang_cxx0x, lang_gnucxx0x
570};
571
572static llvm::cl::opt<LangStds>
573LangStd("std", llvm::cl::desc("Language standard to compile for"),
574 llvm::cl::init(lang_unspecified),
575 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
576 clEnumValN(lang_c89, "c90", "ISO C 1990"),
577 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
578 clEnumValN(lang_c94, "iso9899:199409",
579 "ISO C 1990 with amendment 1"),
580 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000581 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000582 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000583 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000584 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000585 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000586 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000587 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000588 clEnumValN(lang_gnu99, "gnu9x",
589 "ISO C 1999 with GNU extensions"),
590 clEnumValN(lang_cxx98, "c++98",
591 "ISO C++ 1998 with amendments"),
592 clEnumValN(lang_gnucxx98, "gnu++98",
593 "ISO C++ 1998 with amendments and GNU "
594 "extensions (default for C++)"),
595 clEnumValN(lang_cxx0x, "c++0x",
596 "Upcoming ISO C++ 200x with amendments"),
597 clEnumValN(lang_gnucxx0x, "gnu++0x",
598 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000599 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000600 clEnumValEnd));
601
602static llvm::cl::opt<bool>
603NoOperatorNames("fno-operator-names",
604 llvm::cl::desc("Do not treat C++ operator name keywords as "
605 "synonyms for operators"));
606
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000607static llvm::cl::opt<bool>
608PascalStrings("fpascal-strings",
609 llvm::cl::desc("Recognize and construct Pascal-style "
610 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000611
612static llvm::cl::opt<bool>
613MSExtensions("fms-extensions",
614 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000615 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000616
617static llvm::cl::opt<bool>
618WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000619 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000620
621static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000622NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000623 llvm::cl::desc("Disallow implicit conversions between "
624 "vectors with a different number of "
625 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000626
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000627static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000628EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000629
630static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000631EnableHeinousExtensions("fheinous-gnu-extensions",
632 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
633 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
634
635static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000636ObjCNonFragileABI("fobjc-nonfragile-abi",
637 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000638
Daniel Dunbar5523e862009-05-04 05:16:21 +0000639
640static llvm::cl::opt<bool>
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000641EmitAllDecls("femit-all-decls",
642 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000643
Daniel Dunbar91692d92008-08-11 17:36:14 +0000644static llvm::cl::opt<bool>
645Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000646 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000647
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000648static llvm::cl::opt<bool>
649GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000650 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000651 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000652
653static llvm::cl::opt<bool>
654NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000655 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000656 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000657
Eli Friedman449eb692009-06-05 07:12:17 +0000658static llvm::cl::opt<bool>
659CharIsSigned("fsigned-char",
660 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000661
662
663static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000664Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000665
Douglas Gregor375733c2009-03-10 00:06:19 +0000666static llvm::cl::opt<unsigned>
667TemplateDepth("ftemplate-depth", llvm::cl::init(99),
668 llvm::cl::desc("Maximum depth of recursive template "
669 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000670static llvm::cl::opt<bool>
671DollarsInIdents("fdollars-in-identifiers",
672 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000673
Anders Carlssondfd77642009-04-06 17:37:10 +0000674
675static llvm::cl::opt<bool>
676OptSize("Os", llvm::cl::desc("Optimize for size"));
677
678static llvm::cl::opt<bool>
Daniel Dunbard27b66b2009-06-02 22:07:45 +0000679DisableLLVMOptimizations("disable-llvm-optzns",
680 llvm::cl::desc("Don't run LLVM optimization passes"));
681
682static llvm::cl::opt<bool>
Anders Carlssondfd77642009-04-06 17:37:10 +0000683NoCommon("fno-common",
684 llvm::cl::desc("Compile common globals like normal definitions"),
685 llvm::cl::ValueDisallowed);
686
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000687static llvm::cl::opt<std::string>
688MainFileName("main-file-name",
689 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000690
Anders Carlssonf2310142009-05-13 19:49:53 +0000691// FIXME: Also add an "-fno-access-control" option.
692static llvm::cl::opt<bool>
693AccessControl("faccess-control",
694 llvm::cl::desc("Enable C++ access control"));
695
Anders Carlssondfd77642009-04-06 17:37:10 +0000696// It might be nice to add bounds to the CommandLine library directly.
697struct OptLevelParser : public llvm::cl::parser<unsigned> {
698 bool parse(llvm::cl::Option &O, const char *ArgName,
699 const std::string &Arg, unsigned &Val) {
700 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
701 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000702 if (Val > 3)
703 return O.error(": '" + Arg + "' invalid optimization level!");
704 return false;
705 }
706};
707static llvm::cl::opt<unsigned, false, OptLevelParser>
708OptLevel("O", llvm::cl::Prefix,
709 llvm::cl::desc("Optimization level"),
710 llvm::cl::init(0));
711
Daniel Dunbare079c712009-04-08 03:03:23 +0000712static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000713PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
714
715static llvm::cl::opt<bool>
716StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000717
Daniel Dunbar34542952008-08-23 08:43:39 +0000718static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar07181d72009-05-06 03:16:41 +0000719 TargetInfo *Target,
720 const llvm::StringMap<bool> &Features) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000721 // Allow the target to set the default the langauge options as it sees fit.
722 Target->getDefaultLangOptions(Options);
Daniel Dunbar07181d72009-05-06 03:16:41 +0000723
724 // Pass the map of target features to the target for validation and
725 // processing.
726 Target->HandleTargetFeatures(Features);
Chris Lattner738d3f62009-03-02 22:11:07 +0000727
Chris Lattner4b009652007-07-25 00:24:17 +0000728 if (LangStd == lang_unspecified) {
729 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000730 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000731 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000732 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000733 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000734 case langkind_c_cpp:
735 case langkind_objc:
736 case langkind_objc_cpp:
737 LangStd = lang_gnu99;
738 break;
739 case langkind_cxx:
740 case langkind_cxx_cpp:
741 case langkind_objcxx:
742 case langkind_objcxx_cpp:
743 LangStd = lang_gnucxx98;
744 break;
745 }
746 }
747
748 switch (LangStd) {
749 default: assert(0 && "Unknown language standard!");
750
751 // Fall through from newer standards to older ones. This isn't really right.
752 // FIXME: Enable specifically the right features based on the language stds.
753 case lang_gnucxx0x:
754 case lang_cxx0x:
755 Options.CPlusPlus0x = 1;
756 // FALL THROUGH
757 case lang_gnucxx98:
758 case lang_cxx98:
759 Options.CPlusPlus = 1;
760 Options.CXXOperatorNames = !NoOperatorNames;
761 // FALL THROUGH.
762 case lang_gnu99:
763 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000764 Options.C99 = 1;
765 Options.HexFloats = 1;
766 // FALL THROUGH.
767 case lang_gnu89:
768 Options.BCPLComment = 1; // Only for C99/C++.
769 // FALL THROUGH.
770 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000771 Options.Digraphs = 1; // C94, C99, C++.
772 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000773 case lang_c89:
774 break;
775 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000776
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000777 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
778 Options.GNUMode = LangStd >= lang_gnu_START;
779
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000780 if (Options.CPlusPlus) {
781 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000782 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000783 }
Chris Lattner4b009652007-07-25 00:24:17 +0000784
Chris Lattner6ab935b2008-04-05 06:32:51 +0000785 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
786 Options.ImplicitInt = 1;
787 else
788 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000789
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000790 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
791 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000792 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000793 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000794 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000795
Chris Lattner58d5ba52008-12-05 00:10:44 +0000796 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
797 // even if they are normally on for the target. In GNU modes (e.g.
798 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000799 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000800 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000801 Options.Blocks = 0;
802
Chris Lattner284784c2009-04-19 07:06:52 +0000803 // Default to not accepting '$' in identifiers when preprocessing assembler,
804 // but do accept when preprocessing C. FIXME: these defaults are right for
805 // darwin, are they right everywhere?
806 Options.DollarIdents = LK != langkind_asm_cpp;
807 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner77c04832009-04-19 07:00:02 +0000808 Options.DollarIdents = DollarsInIdents;
809
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000810 if (PascalStrings.getPosition())
811 Options.PascalStrings = PascalStrings;
Eli Friedman6b6ca942009-06-08 06:11:14 +0000812 if (MSExtensions.getPosition())
813 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000814 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000815 if (NoLaxVectorConversions.getPosition())
816 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000817 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000818 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000819 Options.Blocks = EnableBlocks;
Eli Friedman449eb692009-06-05 07:12:17 +0000820 if (CharIsSigned.getPosition())
821 Options.CharIsSigned = CharIsSigned;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000822
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000823 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000824 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000825 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000826 Options.Freestanding = Options.NoBuiltin = 1;
827
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000828 if (EnableHeinousExtensions)
829 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000830
Anders Carlssonf2310142009-05-13 19:49:53 +0000831 if (AccessControl)
832 Options.AccessControl = 1;
833
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000834 Options.MathErrno = MathErrno;
835
Douglas Gregor375733c2009-03-10 00:06:19 +0000836 Options.InstantiationDepth = TemplateDepth;
837
Chris Lattnerddae7102008-12-04 22:54:33 +0000838 // Override the default runtime if the user requested it.
839 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000840 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000841 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000842 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000843
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000844 if (ObjCNonFragileABI)
845 Options.ObjCNonFragileABI = 1;
Fariborz Jahanianfefd5e82009-05-22 20:17:16 +0000846
847 Options.ObjCSenderDispatch = ObjCSenderDispatch;
Daniel Dunbar5523e862009-05-04 05:16:21 +0000848
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000849 if (EmitAllDecls)
850 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000851
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000852 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
853 // support.
854 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000855
856 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000857 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000858 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000859
860 assert(PICLevel <= 2 && "Invalid value for -pic-level");
861 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000862
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000863 Options.GNUInline = !Options.C99;
Chris Lattnerd7f00522009-05-06 04:38:30 +0000864 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000865 Options.NoInline = !OptSize && !OptLevel;
866
867 Options.Static = StaticDefine;
868
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000869 if (MainFileName.getPosition())
870 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000871}
872
873//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000874// Target Triple Processing.
875//===----------------------------------------------------------------------===//
876
877static llvm::cl::opt<std::string>
878TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000879 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000880
Chris Lattnerfc457002008-03-05 01:18:20 +0000881static llvm::cl::opt<std::string>
Chris Lattner2b168e02008-09-30 01:13:12 +0000882MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000883 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000884
Chris Lattner01de9c82008-09-30 20:16:56 +0000885// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
886// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000887
888// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000889static void HandleMacOSVersionMin(std::string &Triple) {
890 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
891 if (DarwinDashIdx == std::string::npos) {
892 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000893 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000894 exit(1);
895 }
896 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
897
Chris Lattner01de9c82008-09-30 20:16:56 +0000898 // Remove the number.
899 Triple.resize(DarwinNumIdx);
900
901 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
902 bool MacOSVersionMinIsInvalid = false;
903 int VersionNum = 0;
904 if (MacOSVersionMin.size() < 4 ||
905 MacOSVersionMin.substr(0, 3) != "10." ||
906 !isdigit(MacOSVersionMin[3])) {
907 MacOSVersionMinIsInvalid = true;
908 } else {
909 const char *Start = MacOSVersionMin.c_str()+3;
910 char *End = 0;
911 VersionNum = (int)strtol(Start, &End, 10);
912
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000913 // The version number must be in the range 0-9.
914 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
915
Chris Lattner01de9c82008-09-30 20:16:56 +0000916 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
917 Triple += llvm::itostr(VersionNum+4);
918
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000919 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
920 // Add the period piece (.7) to the end of the triple. This gives us
921 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000922 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000923 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
924 MacOSVersionMinIsInvalid = true;
925 }
926 }
927
928 if (MacOSVersionMinIsInvalid) {
929 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000930 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000931 MacOSVersionMin.c_str());
932 exit(1);
933 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000934 else if (VersionNum <= 4 &&
935 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
936 fprintf(stderr,
937 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
938 MacOSVersionMin.c_str());
939 exit(1);
940 }
941
Chris Lattner01de9c82008-09-30 20:16:56 +0000942}
943
Daniel Dunbar93f64532009-04-10 19:52:24 +0000944static llvm::cl::opt<std::string>
945IPhoneOSVersionMin("miphoneos-version-min",
946 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
947
948// If -miphoneos-version-min=2.2 is specified, change the triple from being
949// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
950// 9 as the default major Darwin number, and encode the iPhone OS version
951// number in the minor version and revision.
952
953// FIXME: We should have the driver do this instead.
954static void HandleIPhoneOSVersionMin(std::string &Triple) {
955 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
956 if (DarwinDashIdx == std::string::npos) {
957 fprintf(stderr,
958 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
959 exit(1);
960 }
961 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
962
963 // Remove the number.
964 Triple.resize(DarwinNumIdx);
965
966 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
967 bool IPhoneOSVersionMinIsInvalid = false;
968 int VersionNum = 0;
969 if (IPhoneOSVersionMin.size() < 3 ||
970 !isdigit(IPhoneOSVersionMin[0])) {
971 IPhoneOSVersionMinIsInvalid = true;
972 } else {
973 const char *Start = IPhoneOSVersionMin.c_str();
974 char *End = 0;
975 VersionNum = (int)strtol(Start, &End, 10);
976
977 // The version number must be in the range 0-9.
978 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
979
980 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
981 Triple += "9." + llvm::itostr(VersionNum);
982
983 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
984 // Add the period piece (.2) to the end of the triple. This gives us
985 // something like ...-darwin9.2.2
986 Triple += End;
987 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
988 IPhoneOSVersionMinIsInvalid = true;
989 }
990 }
991
992 if (IPhoneOSVersionMinIsInvalid) {
993 fprintf(stderr,
994 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
995 IPhoneOSVersionMin.c_str());
996 exit(1);
997 }
998}
999
Chris Lattner01de9c82008-09-30 20:16:56 +00001000/// CreateTargetTriple - Process the various options that affect the target
1001/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +00001002static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +00001003 // Initialize base triple. If a -triple option has been specified, use
1004 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +00001005 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +00001006 if (Triple.empty())
1007 Triple = llvm::sys::getHostTriple();
Chris Lattner2b168e02008-09-30 01:13:12 +00001008
1009 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1010 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +00001011 if (!MacOSVersionMin.empty())
1012 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +00001013 else if (!IPhoneOSVersionMin.empty())
1014 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +00001015
Chris Lattner2b168e02008-09-30 01:13:12 +00001016 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001017}
1018
1019//===----------------------------------------------------------------------===//
Chris Lattner94269d72009-04-21 05:40:52 +00001020// SourceManager initialization.
Chris Lattner4b009652007-07-25 00:24:17 +00001021//===----------------------------------------------------------------------===//
1022
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001023static bool InitializeSourceManager(Preprocessor &PP,
1024 const std::string &InFile) {
1025 // Figure out where to get and map in the main file.
1026 SourceManager &SourceMgr = PP.getSourceManager();
1027 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbarbb56def2009-04-27 21:19:07 +00001028
1029 if (EmptyInputOnly) {
1030 const char *EmptyStr = "";
1031 llvm::MemoryBuffer *SB =
1032 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1033 SourceMgr.createMainFileIDForMemBuffer(SB);
1034 } else if (InFile != "-") {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001035 const FileEntry *File = FileMgr.getFile(InFile);
1036 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1037 if (SourceMgr.getMainFileID().isInvalid()) {
1038 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1039 << InFile.c_str();
1040 return true;
1041 }
1042 } else {
1043 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1044
1045 // If stdin was empty, SB is null. Cons up an empty memory
1046 // buffer now.
1047 if (!SB) {
1048 const char *EmptyStr = "";
1049 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1050 }
1051
1052 SourceMgr.createMainFileIDForMemBuffer(SB);
1053 if (SourceMgr.getMainFileID().isInvalid()) {
1054 PP.getDiagnostics().Report(FullSourceLoc(),
1055 diag::err_fe_error_reading_stdin);
1056 return true;
1057 }
1058 }
1059
1060 return false;
1061}
1062
Chris Lattner47b6a162008-04-19 23:09:31 +00001063
Chris Lattner94269d72009-04-21 05:40:52 +00001064//===----------------------------------------------------------------------===//
1065// Preprocessor Initialization
1066//===----------------------------------------------------------------------===//
Sam Bishop61a20782008-04-14 14:41:57 +00001067
Chris Lattner94269d72009-04-21 05:40:52 +00001068// FIXME: Preprocessor builtins to support.
1069// -A... - Play with #assertions
1070// -undef - Undefine all predefined macros
Chris Lattnerb62396d2009-04-08 20:15:42 +00001071
Chris Lattner94269d72009-04-21 05:40:52 +00001072static llvm::cl::list<std::string>
1073D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1074 llvm::cl::desc("Predefine the specified macro"));
1075static llvm::cl::list<std::string>
1076U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1077 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001078
Chris Lattner94269d72009-04-21 05:40:52 +00001079static llvm::cl::list<std::string>
1080ImplicitIncludes("include", llvm::cl::value_desc("file"),
1081 llvm::cl::desc("Include file before parsing"));
1082static llvm::cl::list<std::string>
1083ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1084 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001085
Chris Lattner94269d72009-04-21 05:40:52 +00001086static llvm::cl::opt<std::string>
1087ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1088 llvm::cl::desc("Include precompiled header file"));
1089
1090static llvm::cl::opt<std::string>
1091ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1092 llvm::cl::desc("Include file before parsing"));
1093
Chris Lattner4b009652007-07-25 00:24:17 +00001094
1095//===----------------------------------------------------------------------===//
1096// Preprocessor include path information.
1097//===----------------------------------------------------------------------===//
1098
1099// This tool exports a large number of command line options to control how the
1100// preprocessor searches for header files. At root, however, the Preprocessor
1101// object takes a very simple interface: a list of directories to search for
1102//
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001103// FIXME: -nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001104// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001105//
Chris Lattner4b009652007-07-25 00:24:17 +00001106
1107static llvm::cl::opt<bool>
1108nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1109
1110// Various command line options. These four add directories to each chain.
1111static llvm::cl::list<std::string>
1112F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1113 llvm::cl::desc("Add directory to framework include search path"));
1114static llvm::cl::list<std::string>
1115I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1116 llvm::cl::desc("Add directory to include search path"));
1117static llvm::cl::list<std::string>
1118idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1119 llvm::cl::desc("Add directory to AFTER include search path"));
1120static llvm::cl::list<std::string>
1121iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1122 llvm::cl::desc("Add directory to QUOTE include search path"));
1123static llvm::cl::list<std::string>
1124isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1125 llvm::cl::desc("Add directory to SYSTEM include search path"));
1126
1127// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1128static llvm::cl::list<std::string>
1129iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1130 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1131static llvm::cl::list<std::string>
1132iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1133 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1134static llvm::cl::list<std::string>
1135iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1136 llvm::cl::Prefix,
1137 llvm::cl::desc("Set directory to include search path with prefix"));
1138
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001139static llvm::cl::opt<std::string>
1140isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1141 llvm::cl::desc("Set the system root directory (usually /)"));
1142
Chris Lattner4b009652007-07-25 00:24:17 +00001143// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001144
Chris Lattner4b009652007-07-25 00:24:17 +00001145/// InitializeIncludePaths - Process the -I options and set them in the
1146/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001147void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1148 FileManager &FM, const LangOptions &Lang) {
1149 InitHeaderSearch Init(Headers, Verbose, isysroot);
1150
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001151 // Handle -I... and -F... options, walking the lists in parallel.
1152 unsigned Iidx = 0, Fidx = 0;
1153 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1154 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001155 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001156 ++Iidx;
1157 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001158 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001159 ++Fidx;
1160 }
1161 }
Chris Lattner4b009652007-07-25 00:24:17 +00001162
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001163 // Consume what's left from whatever list was longer.
1164 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001165 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001166 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001167 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001168
1169 // Handle -idirafter... options.
1170 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001171 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1172 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001173
1174 // Handle -iquote... options.
1175 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001176 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001177
1178 // Handle -isystem... options.
1179 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001180 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001181
1182 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1183 // parallel, processing the values in order of occurance to get the right
1184 // prefixes.
1185 {
1186 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1187 unsigned iprefix_idx = 0;
1188 unsigned iwithprefix_idx = 0;
1189 unsigned iwithprefixbefore_idx = 0;
1190 bool iprefix_done = iprefix_vals.empty();
1191 bool iwithprefix_done = iwithprefix_vals.empty();
1192 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1193 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1194 if (!iprefix_done &&
1195 (iwithprefix_done ||
1196 iprefix_vals.getPosition(iprefix_idx) <
1197 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1198 (iwithprefixbefore_done ||
1199 iprefix_vals.getPosition(iprefix_idx) <
1200 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1201 Prefix = iprefix_vals[iprefix_idx];
1202 ++iprefix_idx;
1203 iprefix_done = iprefix_idx == iprefix_vals.size();
1204 } else if (!iwithprefix_done &&
1205 (iwithprefixbefore_done ||
1206 iwithprefix_vals.getPosition(iwithprefix_idx) <
1207 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001208 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1209 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001210 ++iwithprefix_idx;
1211 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1212 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001213 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1214 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001215 ++iwithprefixbefore_idx;
1216 iwithprefixbefore_done =
1217 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1218 }
1219 }
1220 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001221
Nico Weber770e3882008-08-22 09:25:22 +00001222 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001223
Daniel Dunbar4e604292009-02-21 20:52:41 +00001224 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001225 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001226 llvm::sys::Path::GetMainExecutable(Argv0,
1227 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001228 if (!MainExecutablePath.isEmpty()) {
1229 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1230 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001231
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001232 // Get foo/lib/clang/<version>/include
Daniel Dunbar4e604292009-02-21 20:52:41 +00001233 MainExecutablePath.appendComponent("lib");
1234 MainExecutablePath.appendComponent("clang");
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001235 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbar4e604292009-02-21 20:52:41 +00001236 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001237
1238 // We pass true to ignore sysroot so that we *always* look for clang headers
1239 // relative to our executable, never relative to -isysroot.
1240 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1241 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001242 }
1243
Nico Weber770e3882008-08-22 09:25:22 +00001244 if (!nostdinc)
1245 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001246
1247 // Now that we have collected all of the include paths, merge them all
1248 // together and tell the preprocessor about them.
1249
Nico Weber770e3882008-08-22 09:25:22 +00001250 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001251}
1252
Chris Lattner94269d72009-04-21 05:40:52 +00001253void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1254{
1255 // Add macros from the command line.
1256 unsigned d = 0, D = D_macros.size();
1257 unsigned u = 0, U = U_macros.size();
1258 while (d < D || u < U) {
1259 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1260 InitOpts.addMacroDef(D_macros[d++]);
1261 else
1262 InitOpts.addMacroUndef(U_macros[u++]);
1263 }
1264
1265 // If -imacros are specified, include them now. These are processed before
1266 // any -include directives.
1267 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1268 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1269
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001270 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1271 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattner94269d72009-04-21 05:40:52 +00001272 // We want to add these paths to the predefines buffer in order, make a
1273 // temporary vector to sort by their occurrence.
1274 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1275
1276 if (!ImplicitIncludePTH.empty())
1277 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1278 &ImplicitIncludePTH));
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001279 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1280 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1281 &ImplicitIncludePCH));
Chris Lattner94269d72009-04-21 05:40:52 +00001282 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1283 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1284 &ImplicitIncludes[i]));
1285 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1286
1287
1288 // Now that they are ordered by position, add to the predefines buffer.
1289 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1290 std::string *Ptr = OrderedPaths[i].second;
1291 if (!ImplicitIncludes.empty() &&
1292 Ptr >= &ImplicitIncludes[0] &&
1293 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1294 InitOpts.addInclude(*Ptr, false);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001295 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattner94269d72009-04-21 05:40:52 +00001296 InitOpts.addInclude(*Ptr, true);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001297 } else {
1298 // We end up here when we're producing preprocessed output and
1299 // we loaded a PCH file. In this case, just include the header
1300 // file that was used to build the precompiled header.
1301 assert(Ptr == &ImplicitIncludePCH);
1302 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1303 if (!OriginalFile.empty()) {
1304 InitOpts.addInclude(OriginalFile, false);
1305 ImplicitIncludePCH.clear();
1306 }
Chris Lattner94269d72009-04-21 05:40:52 +00001307 }
1308 }
1309 }
1310}
1311
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001312//===----------------------------------------------------------------------===//
1313// Driver PreprocessorFactory - For lazily generating preprocessors ...
1314//===----------------------------------------------------------------------===//
1315
1316namespace {
1317class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1318 Diagnostic &Diags;
1319 const LangOptions &LangInfo;
1320 TargetInfo &Target;
1321 SourceManager &SourceMgr;
1322 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001323
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001324public:
Eli Friedmane934dca2009-05-18 07:39:39 +00001325 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001326 TargetInfo &target, SourceManager &SM,
1327 HeaderSearch &Headers)
Eli Friedmane934dca2009-05-18 07:39:39 +00001328 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001329 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001330
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001331
1332 virtual ~DriverPreprocessorFactory() {}
1333
1334 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001335 llvm::OwningPtr<PTHManager> PTHMgr;
1336
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001337 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1338 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1339 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001340 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001341 }
1342
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001343 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001344 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1345 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001346 PTHMgr.reset(PTHManager::Create(x, &Diags,
1347 TokenCache.empty() ? Diagnostic::Error
1348 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001349 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001350
Ted Kremenek6348cc62009-03-22 06:42:39 +00001351 if (Diags.hasErrorOccurred())
1352 exit(1);
1353
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001354 // Create the Preprocessor.
1355 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1356 SourceMgr, HeaderInfo,
1357 PTHMgr.get()));
1358
1359 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1360 // That argument is used as the IdentifierInfoLookup argument to
1361 // IdentifierTable's ctor.
1362 if (PTHMgr) {
1363 PTHMgr->setPreprocessor(PP.get());
1364 PP->setPTHManager(PTHMgr.take());
1365 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001366
Chris Lattner94269d72009-04-21 05:40:52 +00001367 PreprocessorInitOptions InitOpts;
1368 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmane934dca2009-05-18 07:39:39 +00001369 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001370 return 0;
Chris Lattner94269d72009-04-21 05:40:52 +00001371
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001372 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001373 }
1374};
1375}
Chris Lattner4b009652007-07-25 00:24:17 +00001376
Chris Lattner4b009652007-07-25 00:24:17 +00001377//===----------------------------------------------------------------------===//
1378// Basic Parser driver
1379//===----------------------------------------------------------------------===//
1380
Chris Lattner9d818a22008-04-19 23:25:44 +00001381static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001382 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001383 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001384
1385 // Parsing the specified input file.
1386 P.ParseTranslationUnit();
1387 delete PA;
1388}
1389
1390//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001391// Code generation options
1392//===----------------------------------------------------------------------===//
1393
1394static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001395GenerateDebugInfo("g",
1396 llvm::cl::desc("Generate source level debug information"));
1397
Daniel Dunbar9101a632009-02-17 19:47:34 +00001398static llvm::cl::opt<std::string>
1399TargetCPU("mcpu",
1400 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1401
Daniel Dunbar07181d72009-05-06 03:16:41 +00001402static llvm::cl::list<std::string>
1403TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1404
Devang Patela3707f12009-06-04 23:32:02 +00001405
1406static llvm::cl::opt<bool>
1407DisableRedZone("disable-red-zone",
1408 llvm::cl::desc("Do not emit code that uses the red zone."),
1409 llvm::cl::init(false));
1410
Devang Patel62c2cca2009-06-05 22:05:48 +00001411static llvm::cl::opt<bool>
1412NoImplicitFloat("no-implicit-float",
1413 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1414 llvm::cl::init(false));
1415
Daniel Dunbar07181d72009-05-06 03:16:41 +00001416/// ComputeTargetFeatures - Recompute the target feature list to only
1417/// be the list of things that are enabled, based on the target cpu
1418/// and feature list.
1419static void ComputeFeatureMap(TargetInfo *Target,
1420 llvm::StringMap<bool> &Features) {
1421 assert(Features.empty() && "invalid map");
1422
1423 // Initialize the feature map based on the target.
1424 Target->getDefaultFeatures(TargetCPU, Features);
1425
1426 // Apply the user specified deltas.
1427 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1428 ie = TargetFeatures.end(); it != ie; ++it) {
1429 const char *Name = it->c_str();
1430
1431 // FIXME: Don't handle errors like this.
1432 if (Name[0] != '-' && Name[0] != '+') {
1433 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1434 Name);
1435 exit(1);
1436 }
Daniel Dunbar0838f962009-05-06 21:07:50 +00001437 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1438 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1439 Name + 1);
Daniel Dunbar07181d72009-05-06 03:16:41 +00001440 exit(1);
1441 }
Daniel Dunbar07181d72009-05-06 03:16:41 +00001442 }
1443}
1444
Chris Lattner8a9615c2009-03-16 18:41:18 +00001445static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001446 const LangOptions &LangOpts,
1447 const llvm::StringMap<bool> &Features) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001448 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001449 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard27b66b2009-06-02 22:07:45 +00001450
1451 if (DisableLLVMOptimizations) {
1452 Opts.OptimizationLevel = 0;
1453 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbard725b162008-10-29 07:56:11 +00001454 } else {
Daniel Dunbard27b66b2009-06-02 22:07:45 +00001455 if (OptSize) {
1456 // -Os implies -O2
1457 Opts.OptimizationLevel = 2;
1458 } else {
1459 Opts.OptimizationLevel = OptLevel;
1460 }
1461
1462 // We must always run at least the always inlining pass.
1463 if (Opts.OptimizationLevel > 1)
1464 Opts.Inlining = CompileOptions::NormalInlining;
1465 else
1466 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbard725b162008-10-29 07:56:11 +00001467 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001468
1469 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001470 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001471 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001472
1473#ifdef NDEBUG
1474 Opts.VerifyModule = 0;
1475#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001476
1477 Opts.CPU = TargetCPU;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001478 Opts.Features.clear();
1479 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1480 ie = Features.end(); it != ie; ++it) {
1481 // FIXME: If we are completely confident that we have the right
1482 // set, we only need to pass the minuses.
1483 std::string Name(it->second ? "+" : "-");
1484 Name += it->first();
1485 Opts.Features.push_back(Name);
1486 }
Chris Lattnere8f70712009-02-18 01:23:44 +00001487
Chris Lattnerf04a7562009-03-26 05:00:52 +00001488 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1489
Chris Lattnere8f70712009-02-18 01:23:44 +00001490 // Handle -ftime-report.
1491 Opts.TimePasses = TimeReport;
Devang Patela3707f12009-06-04 23:32:02 +00001492
1493 Opts.DisableRedZone = DisableRedZone;
Devang Patel62c2cca2009-06-05 22:05:48 +00001494 Opts.NoImplicitFloat = NoImplicitFloat;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001495}
1496
1497//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001498// Fix-It Options
1499//===----------------------------------------------------------------------===//
1500static llvm::cl::list<ParsedSourceLocation>
1501FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1502 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1503
1504//===----------------------------------------------------------------------===//
Eli Friedman35ba7a62009-05-18 22:39:16 +00001505// ObjC Rewriter Options
1506//===----------------------------------------------------------------------===//
1507static llvm::cl::opt<bool>
1508SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1509 llvm::cl::desc("Silence ObjC rewriting warnings"));
1510
1511//===----------------------------------------------------------------------===//
Eli Friedman4d03d382009-05-19 01:17:04 +00001512// Warning Options
1513//===----------------------------------------------------------------------===//
1514
1515// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1516// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1517// -Wextra, so we don't need to worry about it.
1518static llvm::cl::list<std::string>
1519OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1520
1521static llvm::cl::opt<bool> OptPedantic("pedantic");
1522static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1523static llvm::cl::opt<bool> OptNoWarnings("w");
1524
1525//===----------------------------------------------------------------------===//
Eli Friedmane2554252009-05-19 03:06:47 +00001526// Preprocessing (-E mode) Options
1527//===----------------------------------------------------------------------===//
1528static llvm::cl::opt<bool>
1529DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1530static llvm::cl::opt<bool>
1531EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1532static llvm::cl::opt<bool>
1533EnableMacroCommentOutput("CC",
1534 llvm::cl::desc("Enable comment output in -E mode, "
1535 "even from macro expansions"));
1536static llvm::cl::opt<bool>
1537DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1538 " normal output"));
1539static llvm::cl::opt<bool>
1540DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1541 "addition to normal output"));
Eli Friedmane595fe92009-05-19 03:35:57 +00001542
1543//===----------------------------------------------------------------------===//
1544// Dependency file options
1545//===----------------------------------------------------------------------===//
1546static llvm::cl::opt<std::string>
1547DependencyFile("dependency-file",
1548 llvm::cl::desc("Filename (or -) to write dependency output to"));
1549
1550static llvm::cl::opt<bool>
1551DependenciesIncludeSystemHeaders("sys-header-deps",
1552 llvm::cl::desc("Include system headers in dependency output"));
1553
1554static llvm::cl::list<std::string>
1555DependencyTargets("MT",
1556 llvm::cl::desc("Specify target for dependency"));
1557
1558// FIXME: Implement feature
1559static llvm::cl::opt<bool>
1560PhonyDependencyTarget("MP",
1561 llvm::cl::desc("Create phony target for each dependency "
1562 "(other than main file)"));
1563
Eli Friedmane2554252009-05-19 03:06:47 +00001564//===----------------------------------------------------------------------===//
Eli Friedman78a57622009-05-19 10:18:02 +00001565// Analysis options
1566//===----------------------------------------------------------------------===//
1567
1568static llvm::cl::list<Analyses>
1569AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1570llvm::cl::values(
1571#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1572clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001573#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001574clEnumValEnd));
1575
1576static llvm::cl::opt<AnalysisStores>
1577AnalysisStoreOpt("analyzer-store",
1578 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1579 llvm::cl::init(BasicStoreModel),
1580 llvm::cl::values(
1581#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1582clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001583#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001584clEnumValEnd));
1585
1586static llvm::cl::opt<AnalysisConstraints>
1587AnalysisConstraintsOpt("analyzer-constraints",
1588 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1589 llvm::cl::init(RangeConstraintsModel),
1590 llvm::cl::values(
1591#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1592clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001593#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001594clEnumValEnd));
1595
1596static llvm::cl::opt<AnalysisDiagClients>
1597AnalysisDiagOpt("analyzer-output",
1598 llvm::cl::desc("Source Code Analysis - Output Options"),
1599 llvm::cl::init(PD_HTML),
1600 llvm::cl::values(
1601#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1602clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001603#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001604clEnumValEnd));
1605
1606static llvm::cl::opt<bool>
1607VisualizeEGDot("analyzer-viz-egraph-graphviz",
1608 llvm::cl::desc("Display exploded graph using GraphViz"));
1609
1610static llvm::cl::opt<bool>
1611VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1612 llvm::cl::desc("Display exploded graph using Ubigraph"));
1613
1614static llvm::cl::opt<bool>
1615AnalyzeAll("analyzer-opt-analyze-headers",
1616 llvm::cl::desc("Force the static analyzer to analyze "
1617 "functions defined in header files"));
1618
1619static llvm::cl::opt<bool>
1620AnalyzerDisplayProgress("analyzer-display-progress",
1621 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1622
1623static llvm::cl::opt<bool>
1624PurgeDead("analyzer-purge-dead",
1625 llvm::cl::init(true),
1626 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1627 " processing a statement."));
1628
1629static llvm::cl::opt<bool>
1630EagerlyAssume("analyzer-eagerly-assume",
1631 llvm::cl::init(false),
1632 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1633 "symbolic constraints."));
1634
1635static llvm::cl::opt<std::string>
1636AnalyzeSpecificFunction("analyze-function",
1637 llvm::cl::desc("Run analysis on specific function"));
1638
1639static llvm::cl::opt<bool>
1640TrimGraph("trim-egraph",
1641 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1642
1643static AnalyzerOptions ReadAnalyzerOptions() {
1644 AnalyzerOptions Opts;
1645 Opts.AnalysisList = AnalysisList;
1646 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1647 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1648 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1649 Opts.VisualizeEGDot = VisualizeEGDot;
1650 Opts.VisualizeEGUbi = VisualizeEGUbi;
1651 Opts.AnalyzeAll = AnalyzeAll;
1652 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1653 Opts.PurgeDead = PurgeDead;
1654 Opts.EagerlyAssume = EagerlyAssume;
1655 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1656 Opts.TrimGraph = TrimGraph;
1657 return Opts;
1658}
1659
1660//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001661// -dump-build-information Stuff
1662//===----------------------------------------------------------------------===//
1663
1664static llvm::cl::opt<std::string>
1665DumpBuildInformation("dump-build-information",
1666 llvm::cl::value_desc("filename"),
1667 llvm::cl::desc("output a dump of some build information to a file"));
1668
1669static llvm::raw_ostream *BuildLogFile = 0;
1670
1671/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1672/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1673namespace {
1674class LoggingDiagnosticClient : public DiagnosticClient {
1675 llvm::OwningPtr<DiagnosticClient> Chain1;
1676 llvm::OwningPtr<DiagnosticClient> Chain2;
1677public:
1678
1679 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1680 // Output diags both where requested...
1681 Chain1.reset(Normal);
1682 // .. and to our log file.
1683 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1684 !NoShowColumn,
1685 !NoCaretDiagnostics,
1686 !NoShowLocation,
1687 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001688 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001689 !NoDiagnosticsFixIt,
1690 MessageLength));
Chris Lattner94859302009-04-17 21:05:01 +00001691 }
1692
1693 virtual void setLangOptions(const LangOptions *LO) {
1694 Chain1->setLangOptions(LO);
1695 Chain2->setLangOptions(LO);
1696 }
1697
1698 virtual bool IncludeInDiagnosticCounts() const {
1699 return Chain1->IncludeInDiagnosticCounts();
1700 }
1701
1702 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1703 const DiagnosticInfo &Info) {
1704 Chain1->HandleDiagnostic(DiagLevel, Info);
1705 Chain2->HandleDiagnostic(DiagLevel, Info);
1706 }
1707};
1708} // end anonymous namespace.
1709
1710static void SetUpBuildDumpLog(unsigned argc, char **argv,
1711 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1712
1713 std::string ErrorInfo;
1714 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1715 ErrorInfo);
1716
1717 if (!ErrorInfo.empty()) {
1718 llvm::errs() << "error opening -dump-build-information file '"
1719 << DumpBuildInformation << "', option ignored!\n";
1720 delete BuildLogFile;
1721 BuildLogFile = 0;
1722 DumpBuildInformation = "";
1723 return;
1724 }
1725
1726 (*BuildLogFile) << "clang-cc command line arguments: ";
1727 for (unsigned i = 0; i != argc; ++i)
1728 (*BuildLogFile) << argv[i] << ' ';
1729 (*BuildLogFile) << '\n';
1730
1731 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1732 // the diagnostic producers and the normal receiver.
1733 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1734}
1735
1736
1737
1738//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001739// Main driver
1740//===----------------------------------------------------------------------===//
1741
Eli Friedmana9c310842009-05-18 22:20:00 +00001742static llvm::raw_ostream* ComputeOutFile(const std::string& InFile,
1743 const char* Extension,
1744 bool Binary,
1745 llvm::sys::Path& OutPath) {
1746 llvm::raw_ostream* Ret;
1747 bool UseStdout = false;
1748 std::string OutFile;
1749 if (OutputFile == "-" || (OutputFile.empty() && InFile == "-")) {
1750 UseStdout = true;
1751 } else if (!OutputFile.empty()) {
1752 OutFile = OutputFile;
1753 } else if (Extension) {
1754 llvm::sys::Path Path(InFile);
1755 Path.eraseSuffix();
1756 Path.appendSuffix(Extension);
1757 OutFile = Path.toString();
1758 } else {
1759 UseStdout = true;
Chris Lattner7f902922009-02-18 01:20:05 +00001760 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001761
Eli Friedmana9c310842009-05-18 22:20:00 +00001762 if (UseStdout) {
1763 Ret = new llvm::raw_stdout_ostream();
1764 if (Binary)
1765 llvm::sys::Program::ChangeStdoutToBinary();
1766 } else {
1767 std::string Error;
1768 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Binary, Error);
1769 if (!Error.empty()) {
1770 // FIXME: Don't fail this way.
1771 llvm::cerr << "ERROR: " << Error << "\n";
1772 ::exit(1);
1773 }
1774 OutPath = OutFile;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001775 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001776
1777 return Ret;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001778}
1779
Chris Lattner4b009652007-07-25 00:24:17 +00001780/// ProcessInputFile - Process a single input file with the specified state.
1781///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001782static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001783 const std::string &InFile, ProgActions PA,
1784 const llvm::StringMap<bool> &Features) {
Eli Friedmana9c310842009-05-18 22:20:00 +00001785 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek50aab982008-08-08 02:46:37 +00001786 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001787 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001788 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00001789 bool CompleteTranslationUnit = true;
Eli Friedmana9c310842009-05-18 22:20:00 +00001790 llvm::sys::Path OutPath;
Douglas Gregor133d2552009-04-02 01:08:08 +00001791
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001792 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001793 default:
Eli Friedmana9c310842009-05-18 22:20:00 +00001794 fprintf(stderr, "Unexpected program action!\n");
1795 HadErrors = true;
1796 return;
1797
1798 case ASTPrint:
1799 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1800 Consumer.reset(CreateASTPrinter(OS.get()));
1801 break;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001802
Douglas Gregor8987c032009-05-21 20:55:50 +00001803 case ASTPrintXML:
1804 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
1805 Consumer.reset(CreateASTPrinterXML(OS.get()));
1806 break;
1807
Eli Friedmana9c310842009-05-18 22:20:00 +00001808 case ASTDump:
Douglas Gregor996677c2009-05-30 00:08:05 +00001809 Consumer.reset(CreateASTDumper());
Eli Friedmana9c310842009-05-18 22:20:00 +00001810 break;
1811
Eli Friedmana9c310842009-05-18 22:20:00 +00001812 case ASTView:
Douglas Gregor996677c2009-05-30 00:08:05 +00001813 Consumer.reset(CreateASTViewer());
Eli Friedmana9c310842009-05-18 22:20:00 +00001814 break;
1815
1816 case PrintDeclContext:
1817 Consumer.reset(CreateDeclContextPrinter());
1818 break;
1819
1820 case EmitHTML:
1821 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1822 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1823 break;
1824
1825 case InheritanceView:
1826 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1827 break;
1828
1829 case EmitAssembly:
1830 case EmitLLVM:
1831 case EmitBC:
1832 case EmitLLVMOnly: {
1833 BackendAction Act;
1834 if (ProgAction == EmitAssembly) {
1835 Act = Backend_EmitAssembly;
1836 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1837 } else if (ProgAction == EmitLLVM) {
1838 Act = Backend_EmitLL;
1839 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1840 } else if (ProgAction == EmitLLVMOnly) {
1841 Act = Backend_EmitNothing;
1842 } else {
1843 Act = Backend_EmitBC;
1844 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001845 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001846
Eli Friedmana9c310842009-05-18 22:20:00 +00001847 CompileOptions Opts;
1848 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1849 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1850 PP.getLangOptions(), Opts, InFile,
1851 OS.get()));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001852 break;
Eli Friedmana9c310842009-05-18 22:20:00 +00001853 }
1854
1855 case GeneratePCH:
1856 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1857 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
1858 CompleteTranslationUnit = false;
1859 break;
1860
1861 case RewriteObjC:
1862 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedman848763f2009-05-18 22:29:17 +00001863 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedman35ba7a62009-05-18 22:39:16 +00001864 PP.getLangOptions(),
1865 SilenceRewriteMacroWarning));
Eli Friedmana9c310842009-05-18 22:20:00 +00001866 break;
1867
1868 case RewriteBlocks:
1869 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1870 PP.getLangOptions()));
1871 break;
1872
Eli Friedman78a57622009-05-19 10:18:02 +00001873 case RunAnalysis: {
Eli Friedmana9c310842009-05-18 22:20:00 +00001874 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedman78a57622009-05-19 10:18:02 +00001875 PP.getLangOptions(), OutputFile,
1876 ReadAnalyzerOptions()));
Eli Friedmana9c310842009-05-18 22:20:00 +00001877 break;
Eli Friedman78a57622009-05-19 10:18:02 +00001878 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001879
Chris Lattneraf669fb2008-10-12 05:03:36 +00001880 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001881 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001882 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001883 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001884 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001885 RawLex.SetKeepWhitespaceMode(true);
1886
1887 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001888 RawLex.LexFromRawLexer(RawTok);
1889 while (RawTok.isNot(tok::eof)) {
1890 PP.DumpToken(RawTok, true);
1891 fprintf(stderr, "\n");
1892 RawLex.LexFromRawLexer(RawTok);
1893 }
1894 ClearSourceMgr = true;
1895 break;
1896 }
Chris Lattner4b009652007-07-25 00:24:17 +00001897 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001898 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001899 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001900 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001901 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001902 do {
1903 PP.Lex(Tok);
1904 PP.DumpToken(Tok, true);
1905 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001906 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001907 ClearSourceMgr = true;
1908 break;
1909 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001910 case RunPreprocessorOnly:
Chris Lattner4b009652007-07-25 00:24:17 +00001911 break;
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001912
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001913 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001914 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001915 if (OutputFile.empty() || OutputFile == "-") {
1916 // FIXME: Don't fail this way.
1917 // FIXME: Verify that we can actually seek in the given file.
1918 llvm::cerr << "ERROR: PTH requires an seekable file for output!\n";
1919 ::exit(1);
1920 }
1921 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1922 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001923 ClearSourceMgr = true;
1924 break;
1925 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001926
Chris Lattner772a7c12009-04-27 22:02:30 +00001927 case PrintPreprocessedInput:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001928 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Chris Lattner4b009652007-07-25 00:24:17 +00001929 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001930
Chris Lattner270d29a2009-04-27 21:45:14 +00001931 case ParseNoop:
Chris Lattner4b009652007-07-25 00:24:17 +00001932 break;
1933
Chris Lattnerefe33382009-02-18 01:51:21 +00001934 case ParsePrintCallbacks: {
1935 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001936 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1937 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattner4b009652007-07-25 00:24:17 +00001938 ClearSourceMgr = true;
1939 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001940 }
1941
1942 case ParseSyntaxOnly: { // -fsyntax-only
1943 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001944 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001945 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001946 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001947
1948 case RewriteMacros:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001949 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1950 RewriteMacrosInInput(PP, OS.get());
Chris Lattner1665a9f2008-05-08 06:52:13 +00001951 ClearSourceMgr = true;
1952 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001953
Eli Friedman4ae15b92009-05-19 01:02:07 +00001954 case RewriteTest:
1955 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1956 DoRewriteTest(PP, OS.get());
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001957 ClearSourceMgr = true;
1958 break;
Douglas Gregor133d2552009-04-02 01:08:08 +00001959
1960 case FixIt:
1961 llvm::TimeRegion Timer(ClangFrontendTimer);
1962 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001963 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001964 PP.getSourceManager(),
1965 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00001966 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001967 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001968
Chris Lattner38a4f182009-04-27 21:25:27 +00001969 if (FixItAtLocations.size() > 0) {
1970 // Even without the "-fixit" flag, with may have some specific
1971 // locations where the user has requested fixes. Process those
1972 // locations now.
1973 if (!FixItRewrite)
1974 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1975 PP.getSourceManager(),
1976 PP.getLangOptions());
Chris Lattner143fd6d2009-03-28 01:37:17 +00001977
Chris Lattner38a4f182009-04-27 21:25:27 +00001978 bool AddedFixitLocation = false;
1979 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1980 Idx != Last; ++Idx) {
1981 RequestedSourceLocation Requested;
1982 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1983 Requested)) {
1984 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1985 FixItAtLocations[Idx].FileName.c_str());
1986 } else {
1987 FixItRewrite->addFixItLocation(Requested);
1988 AddedFixitLocation = true;
Douglas Gregor24b48b02009-04-02 19:05:20 +00001989 }
1990 }
1991
Chris Lattner38a4f182009-04-27 21:25:27 +00001992 if (!AddedFixitLocation) {
1993 // All of the fix-it locations were bad. Don't fix anything.
1994 delete FixItRewrite;
1995 FixItRewrite = 0;
1996 }
1997 }
1998
1999 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner270d29a2009-04-27 21:45:14 +00002000 if (Consumer)
Chris Lattner143fd6d2009-03-28 01:37:17 +00002001 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
2002 PP.getSourceManager(),
2003 PP.getTargetInfo(),
2004 PP.getIdentifierTable(),
2005 PP.getSelectorTable(),
Chris Lattnerc46fcdd2009-06-14 01:54:56 +00002006 PP.getBuiltinInfo(),
Douglas Gregorda38c6c2009-04-22 18:49:13 +00002007 /* FreeMemory = */ !DisableFree,
Chris Lattnerc46fcdd2009-06-14 01:54:56 +00002008 /* size_reserve = */0));
2009
Chris Lattner772a7c12009-04-27 22:02:30 +00002010 llvm::OwningPtr<PCHReader> Reader;
2011 llvm::OwningPtr<ExternalASTSource> Source;
2012
Chris Lattner270d29a2009-04-27 21:45:14 +00002013 if (!ImplicitIncludePCH.empty()) {
Chris Lattner772a7c12009-04-27 22:02:30 +00002014 Reader.reset(new PCHReader(PP, ContextOwner.get()));
2015
Chris Lattner270d29a2009-04-27 21:45:14 +00002016 // The user has asked us to include a precompiled header. Load
2017 // the precompiled header into the AST context.
Chris Lattner270d29a2009-04-27 21:45:14 +00002018 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
2019 case PCHReader::Success: {
Douglas Gregor32de6312009-04-28 18:58:38 +00002020 // Set the predefines buffer as suggested by the PCH
2021 // reader. Typically, the predefines buffer will be empty.
2022 PP.setPredefines(Reader->getSuggestedPredefines());
2023
Chris Lattner270d29a2009-04-27 21:45:14 +00002024 // Attach the PCH reader to the AST context as an external AST
2025 // source, so that declarations will be deserialized from the
2026 // PCH file as needed.
Chris Lattner772a7c12009-04-27 22:02:30 +00002027 if (ContextOwner) {
2028 Source.reset(Reader.take());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002029 ContextOwner->setExternalSource(Source);
Chris Lattner772a7c12009-04-27 22:02:30 +00002030 }
Chris Lattner270d29a2009-04-27 21:45:14 +00002031 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002032 }
2033
Chris Lattner270d29a2009-04-27 21:45:14 +00002034 case PCHReader::Failure:
2035 // Unrecoverable failure: don't even try to process the input
2036 // file.
2037 return;
2038
2039 case PCHReader::IgnorePCH:
Douglas Gregor9ea9b162009-04-28 22:01:16 +00002040 // No suitable PCH file could be found. Return an error.
2041 return;
2042
2043#if 0
2044 // FIXME: We can recover from failed attempts to load PCH
2045 // files. This code will do so, if we ever want to enable it.
2046
Chris Lattner270d29a2009-04-27 21:45:14 +00002047 // We delayed the initialization of builtins in the hope of
2048 // loading the PCH file. Since the PCH file could not be
2049 // loaded, initialize builtins now.
2050 if (ContextOwner)
2051 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor9ea9b162009-04-28 22:01:16 +00002052#endif
Chris Lattner270d29a2009-04-27 21:45:14 +00002053 }
2054
2055 // Finish preprocessor initialization. We do this now (rather
2056 // than earlier) because this initialization creates new source
2057 // location entries in the source manager, which must come after
2058 // the source location entries for the PCH file.
2059 if (InitializeSourceManager(PP, InFile))
2060 return;
Ted Kremenek88eebed2009-01-28 04:29:29 +00002061 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002062
Chris Lattner270d29a2009-04-27 21:45:14 +00002063
2064 // If we have an ASTConsumer, run the parser with it.
2065 if (Consumer)
2066 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2067 CompleteTranslationUnit);
2068
2069 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2070 llvm::TimeRegion Timer(ClangFrontendTimer);
2071 Token Tok;
2072 // Start parsing the specified input file.
2073 PP.EnterMainSourceFile();
2074 do {
2075 PP.Lex(Tok);
2076 } while (Tok.isNot(tok::eof));
2077 ClearSourceMgr = true;
2078 } else if (PA == ParseNoop) { // -parse-noop
2079 llvm::TimeRegion Timer(ClangFrontendTimer);
2080 ParseFile(PP, new MinimalAction(PP));
2081 ClearSourceMgr = true;
Chris Lattner772a7c12009-04-27 22:02:30 +00002082 } else if (PA == PrintPreprocessedInput){ // -E mode.
2083 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmane2554252009-05-19 03:06:47 +00002084 if (DumpMacros)
2085 DoPrintMacros(PP, OS.get());
2086 else
2087 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2088 EnableMacroCommentOutput,
2089 DisableLineMarkers, DumpDefines);
Chris Lattner772a7c12009-04-27 22:02:30 +00002090 ClearSourceMgr = true;
Chris Lattner270d29a2009-04-27 21:45:14 +00002091 }
2092
Chris Lattner38a4f182009-04-27 21:25:27 +00002093 if (FixItRewrite)
2094 FixItRewrite->WriteFixedFile(InFile, OutputFile);
2095
2096 // If in -disable-free mode, don't deallocate ASTContext.
2097 if (DisableFree)
2098 ContextOwner.take();
2099 else
2100 ContextOwner.reset(); // Delete ASTContext
Eli Friedmana9c310842009-05-18 22:20:00 +00002101
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002102 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002103 if (CheckDiagnostics(PP))
2104 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00002105
Chris Lattner4b009652007-07-25 00:24:17 +00002106 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00002107 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00002108 PP.PrintStats();
2109 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00002110 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00002111 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00002112 fprintf(stderr, "\n");
2113 }
2114
2115 // For a multi-file compilation, some things are ok with nuking the source
2116 // manager tables, other require stable fileid/macroid's across multiple
2117 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00002118 if (ClearSourceMgr)
2119 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00002120
2121 if (DisableFree)
2122 Consumer.take();
Eli Friedmana9c310842009-05-18 22:20:00 +00002123 else
2124 Consumer.reset();
2125
2126 // Always delete the output stream because we don't want to leak file
2127 // handles. Also, we don't want to try to erase an open file.
2128 OS.reset();
2129
2130 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2131 !OutPath.isEmpty()) {
2132 // If we had errors, try to erase the output file.
2133 OutPath.eraseFromDisk();
2134 }
Chris Lattner4b009652007-07-25 00:24:17 +00002135}
2136
2137static llvm::cl::list<std::string>
2138InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2139
Chris Lattner4b009652007-07-25 00:24:17 +00002140int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00002141 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00002142 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00002143 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00002144 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Daniel Dunbarc583b1f2009-05-28 16:37:33 +00002145
Chris Lattner4d495682009-06-17 17:25:50 +00002146 llvm::InitializeAllTargets();
2147 llvm::InitializeAllAsmPrinters();
2148
Chris Lattnerefe33382009-02-18 01:51:21 +00002149 if (TimeReport)
2150 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2151
Daniel Dunbarc583b1f2009-05-28 16:37:33 +00002152 if (Verbose)
2153 fprintf(stderr, "clang-cc version 1.0 based upon " PACKAGE_STRING
2154 " hosted on " LLVM_HOSTTRIPLE "\n");
2155
Chris Lattner4b009652007-07-25 00:24:17 +00002156 // If no input was specified, read from stdin.
2157 if (InputFilenames.empty())
2158 InputFilenames.push_back("-");
Douglas Gregor965a13c2009-05-02 00:03:46 +00002159
Ted Kremenekb240e822007-12-11 23:28:38 +00002160 // Create the diagnostic client for reporting errors or for
2161 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00002162 llvm::OwningPtr<DiagnosticClient> DiagClient;
2163 if (VerifyDiagnostics) {
2164 // When checking diagnostics, just buffer them up.
2165 DiagClient.reset(new TextDiagnosticBuffer());
2166 if (InputFilenames.size() != 1) {
2167 fprintf(stderr, "-verify only works on single input files for now.\n");
2168 return 1;
2169 }
2170 if (!HTMLDiag.empty()) {
2171 fprintf(stderr, "-verify and -html-diags don't work together\n");
2172 return 1;
2173 }
2174 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00002175 // Print diagnostics to stderr by default.
Douglas Gregor965a13c2009-05-02 00:03:46 +00002176
2177 // If -fmessage-length=N was not specified, determine whether this
2178 // is a terminal and, if so, implicitly define -fmessage-length
2179 // appropriately.
2180 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregorc604d722009-05-11 18:06:49 +00002181 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor965a13c2009-05-02 00:03:46 +00002182
Edwin Törökeff37122009-06-04 07:18:23 +00002183 if (!NoColorDiagnostic) {
2184 NoColorDiagnostic.setValue(!llvm::sys::Process::StandardErrHasColors());
2185 }
2186
Chris Lattner5f7937d2009-04-17 20:40:01 +00002187 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00002188 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00002189 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00002190 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00002191 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00002192 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00002193 !NoDiagnosticsFixIt,
Edwin Törökeff37122009-06-04 07:18:23 +00002194 MessageLength,
2195 !NoColorDiagnostic));
Ted Kremenek5c341732008-08-07 17:49:57 +00002196 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00002197 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00002198 }
Chris Lattner94859302009-04-17 21:05:01 +00002199
2200 if (!DumpBuildInformation.empty()) {
2201 if (!HTMLDiag.empty()) {
2202 fprintf(stderr,
2203 "-dump-build-information and -html-diags don't work together\n");
2204 return 1;
2205 }
2206
2207 SetUpBuildDumpLog(argc, argv, DiagClient);
2208 }
2209
Ted Kremenek5c341732008-08-07 17:49:57 +00002210
Chris Lattner4b009652007-07-25 00:24:17 +00002211 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00002212 Diagnostic Diags(DiagClient.get());
Eli Friedman4d03d382009-05-19 01:17:04 +00002213 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2214 OptNoWarnings))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00002215 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00002216
Chris Lattner45a56e02007-12-05 23:24:17 +00002217 // -I- is a deprecated GCC feature, scan for it and reject it.
2218 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2219 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00002220 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00002221 I_dirs.erase(I_dirs.begin()+i);
2222 --i;
2223 }
2224 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002225
2226 // Get information about the target being compiled for.
2227 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00002228 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2229
Chris Lattner2c77d852008-03-14 06:12:05 +00002230 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00002231 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2232 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002233 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00002234 }
Chris Lattner45a56e02007-12-05 23:24:17 +00002235
Daniel Dunbar9c321102009-01-20 23:17:32 +00002236 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00002237 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00002238
Ted Kremenek2a4224a2008-06-06 22:42:39 +00002239 llvm::OwningPtr<SourceManager> SourceMgr;
2240
Chris Lattnere1be6022009-04-14 23:22:57 +00002241 // Create a file manager object to provide access to and cache the filesystem.
2242 FileManager FileMgr;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00002243
Daniel Dunbar07181d72009-05-06 03:16:41 +00002244 // Compute the feature set, unfortunately this effects the language!
2245 llvm::StringMap<bool> Features;
2246 ComputeFeatureMap(Target.get(), Features);
2247
Chris Lattner4b009652007-07-25 00:24:17 +00002248 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00002249 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00002250
Chris Lattner2b989562009-03-04 21:40:56 +00002251 /// Create a SourceManager object. This tracks and owns all the file
2252 /// buffers allocated to a translation unit.
2253 if (!SourceMgr)
2254 SourceMgr.reset(new SourceManager());
2255 else
2256 SourceMgr->clearIDTables();
2257
2258 // Initialize language options, inferring file types from input filenames.
2259 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00002260 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00002261
Chris Lattner2b989562009-03-04 21:40:56 +00002262 InitializeBaseLanguage();
2263 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002264 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar07181d72009-05-06 03:16:41 +00002265 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002266
2267 // Process the -I options and set them in the HeaderInfo.
2268 HeaderSearch HeaderInfo(FileMgr);
2269
Chris Lattnere1be6022009-04-14 23:22:57 +00002270
Chris Lattner2b989562009-03-04 21:40:56 +00002271 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2272
2273 // Set up the preprocessor with these options.
Eli Friedmane934dca2009-05-18 07:39:39 +00002274 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattner2b989562009-03-04 21:40:56 +00002275 *SourceMgr.get(), HeaderInfo);
2276
2277 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2278
2279 if (!PP)
2280 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002281
Eli Friedmane595fe92009-05-19 03:35:57 +00002282 // Handle generating dependencies, if requested
2283 if (!DependencyFile.empty()) {
2284 llvm::raw_ostream *DependencyOS;
2285 if (DependencyTargets.empty()) {
2286 // FIXME: Use a proper diagnostic
2287 llvm::cerr << "-dependency-file requires at least one -MT option\n";
2288 HadErrors = true;
2289 continue;
2290 }
2291 std::string ErrStr;
2292 DependencyOS =
2293 new llvm::raw_fd_ostream(DependencyFile.c_str(), false, ErrStr);
2294 if (!ErrStr.empty()) {
2295 // FIXME: Use a proper diagnostic
2296 llvm::cerr << "unable to open dependency file: " + ErrStr;
2297 HadErrors = true;
2298 continue;
2299 }
2300
2301 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2302 DependenciesIncludeSystemHeaders,
2303 PhonyDependencyTarget);
2304 }
2305
Chris Lattnerc46fcdd2009-06-14 01:54:56 +00002306 if (ImplicitIncludePCH.empty()) {
2307 if (InitializeSourceManager(*PP.get(), InFile))
2308 continue;
2309
2310 // Initialize builtin info.
2311 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattnerc46fcdd2009-06-14 01:54:56 +00002312 PP->getLangOptions().NoBuiltin);
2313 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00002314
Chris Lattner5f7937d2009-04-17 20:40:01 +00002315 if (!HTMLDiag.empty())
2316 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00002317
2318 // Process the source file.
Daniel Dunbar07181d72009-05-06 03:16:41 +00002319 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002320
Chris Lattner2961dc52009-04-17 20:16:08 +00002321 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00002322 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00002323 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002324
Mike Stumpc4ba6cd2009-04-28 01:19:10 +00002325 if (!NoCaretDiagnostics)
2326 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2327 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2328 (NumDiagnostics == 1 ? "" : "s"));
Chris Lattner4b009652007-07-25 00:24:17 +00002329
2330 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002331 FileMgr.PrintStats();
2332 fprintf(stderr, "\n");
2333 }
Chris Lattner94859302009-04-17 21:05:01 +00002334
2335 delete ClangFrontendTimer;
2336 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002337
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002338 // If verifying diagnostics and we reached here, all is well.
2339 if (VerifyDiagnostics)
2340 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002341
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002342 // Managed static deconstruction. Useful for making things like
2343 // -time-passes usable.
2344 llvm::llvm_shutdown();
2345
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002346 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002347}