blob: f2ccb80de3ce4cfeb7905e35f04a14feb86f2ad4 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattner39fb14e2009-02-18 01:17:01 +000020// -Wfatal-errors
Chris Lattner4b009652007-07-25 00:24:17 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Ted Kremenek377a3192009-03-31 18:58:14 +000025#include "clang-cc.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor133d2552009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000031#include "clang/Frontend/PathDiagnosticClients.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000032#include "clang/Frontend/TextDiagnosticBuffer.h"
33#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000034#include "clang/Analysis/PathDiagnostic.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Chris Lattnerfc318192009-03-28 04:31:31 +000039#include "clang/AST/ASTContext.h"
40#include "clang/AST/Decl.h"
Chris Lattnera17991f2009-03-29 16:50:03 +000041#include "clang/AST/DeclGroup.h"
Chris Lattner4b009652007-07-25 00:24:17 +000042#include "clang/Parse/Parser.h"
43#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000044#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000045#include "clang/Basic/FileManager.h"
46#include "clang/Basic/SourceManager.h"
47#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000048#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000049#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000050#include "llvm/ADT/StringExtras.h"
51#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000052#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000053#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000054#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000055#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000056#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000057#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000058#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000059#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000060#include "llvm/System/Signals.h"
Douglas Gregor24b48b02009-04-02 19:05:20 +000061#include <cstdlib>
62
Chris Lattner4b009652007-07-25 00:24:17 +000063using namespace clang;
64
65//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000066// Source Location Parser
67//===----------------------------------------------------------------------===//
68
69/// \brief A source location that has been parsed on the command line.
70struct ParsedSourceLocation {
71 std::string FileName;
72 unsigned Line;
73 unsigned Column;
74
75 /// \brief Try to resolve the file name of a parsed source location.
76 ///
77 /// \returns true if there was an error, false otherwise.
78 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
79};
80
81bool
82ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
83 RequestedSourceLocation &Result) {
84 const FileEntry *File = FileMgr.getFile(FileName);
85 if (!File)
86 return true;
87
88 Result.File = File;
89 Result.Line = Line;
90 Result.Column = Column;
91 return false;
92}
93
94namespace llvm {
95 namespace cl {
96 /// \brief Command-line option parser that parses source locations.
97 ///
98 /// Source locations are of the form filename:line:column.
99 template<>
100 class parser<ParsedSourceLocation>
101 : public basic_parser<ParsedSourceLocation> {
102 public:
103 bool parse(Option &O, const char *ArgName,
104 const std::string &ArgValue,
105 ParsedSourceLocation &Val);
106 };
107
108 bool
109 parser<ParsedSourceLocation>::
110 parse(Option &O, const char *ArgName, const std::string &ArgValue,
111 ParsedSourceLocation &Val) {
112 using namespace clang;
113
114 const char *ExpectedFormat
115 = "source location must be of the form filename:line:column";
116 std::string::size_type SecondColon = ArgValue.rfind(':');
117 if (SecondColon == std::string::npos) {
118 std::fprintf(stderr, "%s\n", ExpectedFormat);
119 return true;
120 }
121 char *EndPtr;
122 long Column
123 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
124 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
125 std::fprintf(stderr, "%s\n", ExpectedFormat);
126 return true;
127 }
128
129 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
130 if (SecondColon == std::string::npos) {
131 std::fprintf(stderr, "%s\n", ExpectedFormat);
132 return true;
133 }
134 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
135 if (EndPtr != ArgValue.c_str() + SecondColon) {
136 std::fprintf(stderr, "%s\n", ExpectedFormat);
137 return true;
138 }
139
140 Val.FileName = ArgValue.substr(0, FirstColon);
141 Val.Line = Line;
142 Val.Column = Column;
143 return false;
144 }
145 }
146}
147
148//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000149// Global options.
150//===----------------------------------------------------------------------===//
151
Chris Lattnerefe33382009-02-18 01:51:21 +0000152/// ClangFrontendTimer - The front-end activities should charge time to it with
153/// TimeRegion. The -ftime-report option controls whether this will do
154/// anything.
155llvm::Timer *ClangFrontendTimer = 0;
156
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000157static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000158
Chris Lattner4b009652007-07-25 00:24:17 +0000159static llvm::cl::opt<bool>
160Verbose("v", llvm::cl::desc("Enable verbose output"));
161static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000162Stats("print-stats",
163 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000164static llvm::cl::opt<bool>
165DisableFree("disable-free",
166 llvm::cl::desc("Disable freeing of memory on exit"),
167 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +0000168
169enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000170 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000171 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000172 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000173 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000174 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000175 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000176 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000177 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000178 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000179 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek397de012007-12-13 00:37:31 +0000180 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +0000181 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000182 ASTPrint, // Parse ASTs and print them.
183 ASTDump, // Parse ASTs and dump them.
184 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000185 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000186 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +0000187 ParsePrintCallbacks, // Parse and print each callback.
188 ParseSyntaxOnly, // Parse and perform semantic analysis.
189 ParseNoop, // Parse with noop callbacks.
190 RunPreprocessorOnly, // Just lex, no output.
191 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000192 DumpTokens, // Dump out preprocessed tokens.
193 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000194 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000195 GeneratePTH, // Generate pre-tokenized header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000196 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000197};
198
199static llvm::cl::opt<ProgActions>
200ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
201 llvm::cl::init(ParseSyntaxOnly),
202 llvm::cl::values(
203 clEnumValN(RunPreprocessorOnly, "Eonly",
204 "Just run preprocessor, no output (for timings)"),
205 clEnumValN(PrintPreprocessedInput, "E",
206 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000207 clEnumValN(DumpRawTokens, "dump-raw-tokens",
208 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000209 clEnumValN(RunAnalysis, "analyze",
210 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000211 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000212 "Run preprocessor, dump internal rep of tokens"),
213 clEnumValN(ParseNoop, "parse-noop",
214 "Run parser with noop callbacks (for timings)"),
215 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
216 "Run parser and perform semantic analysis"),
217 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
218 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000219 clEnumValN(EmitHTML, "emit-html",
220 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000221 clEnumValN(ASTPrint, "ast-print",
222 "Build ASTs and then pretty-print them"),
223 clEnumValN(ASTDump, "ast-dump",
224 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000225 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000226 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000227 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000228 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000229 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000230 "Generate pre-tokenized header file"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000231 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000232 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000233 clEnumValN(EmitAssembly, "S",
234 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000235 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000236 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000237 clEnumValN(EmitBC, "emit-llvm-bc",
238 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000239 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
240 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000241 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000242 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000243 clEnumValN(RewriteTest, "rewrite-test",
244 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000245 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000246 "Rewrite ObjC into C (code rewriter example)"),
247 clEnumValN(RewriteMacros, "rewrite-macros",
248 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000249 clEnumValN(RewriteBlocks, "rewrite-blocks",
250 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000251 clEnumValN(FixIt, "fixit",
252 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000253 clEnumValEnd));
254
Ted Kremenekd01eae62007-12-19 19:47:59 +0000255
256static llvm::cl::opt<std::string>
257OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000258 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000259 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000260
Ted Kremenek57f25b22008-12-02 19:57:31 +0000261
262//===----------------------------------------------------------------------===//
263// PTH.
264//===----------------------------------------------------------------------===//
265
266static llvm::cl::opt<std::string>
267TokenCache("token-cache", llvm::cl::value_desc("path"),
268 llvm::cl::desc("Use specified token cache file"));
269
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000270//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000271// Diagnostic Options
272//===----------------------------------------------------------------------===//
273
Ted Kremenek10389cf2007-09-26 19:42:19 +0000274static llvm::cl::opt<bool>
275VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000276 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000277
Ted Kremenekfd75e312008-03-27 06:17:42 +0000278static llvm::cl::opt<std::string>
279HTMLDiag("html-diags",
280 llvm::cl::desc("Generate HTML to report diagnostics"),
281 llvm::cl::value_desc("HTML directory"));
282
Nico Weber0e13eaa2008-08-05 23:33:20 +0000283static llvm::cl::opt<bool>
284NoShowColumn("fno-show-column",
285 llvm::cl::desc("Do not include column number on diagnostics"));
286
287static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000288NoShowLocation("fno-show-source-location",
289 llvm::cl::desc("Do not include source location information with"
290 " diagnostics"));
291
292static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000293NoCaretDiagnostics("fno-caret-diagnostics",
294 llvm::cl::desc("Do not include source line and caret with"
295 " diagnostics"));
296
Chris Lattner695a4f52009-03-13 01:08:23 +0000297static llvm::cl::opt<bool>
298PrintSourceRangeInfo("fprint-source-range-info",
299 llvm::cl::desc("Print source range spans in numeric form"));
300
Nico Weber0e13eaa2008-08-05 23:33:20 +0000301
Chris Lattner4b009652007-07-25 00:24:17 +0000302//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000303// C++ Visualization.
304//===----------------------------------------------------------------------===//
305
306static llvm::cl::opt<std::string>
307InheritanceViewCls("cxx-inheritance-view",
308 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000309 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000310
311//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000312// Builtin Options
313//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000314
315static llvm::cl::opt<bool>
316TimeReport("ftime-report",
317 llvm::cl::desc("Print the amount of time each "
318 "phase of compilation takes"));
319
Douglas Gregor23d23262009-02-14 20:49:29 +0000320static llvm::cl::opt<bool>
321Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000322 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000323 "freestanding environment"));
324
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000325static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000326AllowBuiltins("fbuiltin", llvm::cl::init(true),
327 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000328
329
330static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000331MathErrno("fmath-errno", llvm::cl::init(true),
332 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000333
Douglas Gregor23d23262009-02-14 20:49:29 +0000334//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000335// Language Options
336//===----------------------------------------------------------------------===//
337
338enum LangKind {
339 langkind_unspecified,
340 langkind_c,
341 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000342 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000343 langkind_cxx,
344 langkind_cxx_cpp,
345 langkind_objc,
346 langkind_objc_cpp,
347 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000348 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000349};
350
Chris Lattner4b009652007-07-25 00:24:17 +0000351static llvm::cl::opt<LangKind>
352BaseLang("x", llvm::cl::desc("Base language to compile"),
353 llvm::cl::init(langkind_unspecified),
354 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
355 clEnumValN(langkind_cxx, "c++", "C++"),
356 clEnumValN(langkind_objc, "objective-c", "Objective C"),
357 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000358 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000359 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000360 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
361 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000362 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000363 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000364 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
365 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000366 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000367 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000368 clEnumValN(langkind_c, "c-header",
369 "C header"),
370 clEnumValN(langkind_objc, "objective-c-header",
371 "Objective-C header"),
372 clEnumValN(langkind_cxx, "c++-header",
373 "C++ header"),
374 clEnumValN(langkind_objcxx, "objective-c++-header",
375 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000376 clEnumValEnd));
377
378static llvm::cl::opt<bool>
379LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
380 llvm::cl::Hidden);
381static llvm::cl::opt<bool>
382LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
383 llvm::cl::Hidden);
384
Ted Kremenek11ad8952007-12-05 23:49:08 +0000385/// InitializeBaseLanguage - Handle the -x foo options.
386static void InitializeBaseLanguage() {
387 if (LangObjC)
388 BaseLang = langkind_objc;
389 else if (LangObjCXX)
390 BaseLang = langkind_objcxx;
391}
392
393static LangKind GetLanguage(const std::string &Filename) {
394 if (BaseLang != langkind_unspecified)
395 return BaseLang;
396
397 std::string::size_type DotPos = Filename.rfind('.');
398
399 if (DotPos == std::string::npos) {
400 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000401 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000402 }
403
Ted Kremenek11ad8952007-12-05 23:49:08 +0000404 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
405 // C header: .h
406 // C++ header: .hh or .H;
407 // assembler no preprocessing: .s
408 // assembler: .S
409 if (Ext == "c")
410 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000411 else if (Ext == "S" ||
412 // If the compiler is run on a .s file, preprocess it as .S
413 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000414 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000415 else if (Ext == "i")
416 return langkind_c_cpp;
417 else if (Ext == "ii")
418 return langkind_cxx_cpp;
419 else if (Ext == "m")
420 return langkind_objc;
421 else if (Ext == "mi")
422 return langkind_objc_cpp;
423 else if (Ext == "mm" || Ext == "M")
424 return langkind_objcxx;
425 else if (Ext == "mii")
426 return langkind_objcxx_cpp;
427 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
428 Ext == "c++" || Ext == "cp" || Ext == "cxx")
429 return langkind_cxx;
430 else
431 return langkind_c;
432}
433
434
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000435static void InitializeCOptions(LangOptions &Options) {
436 // Do nothing.
437}
438
439static void InitializeObjCOptions(LangOptions &Options) {
440 Options.ObjC1 = Options.ObjC2 = 1;
441}
442
443
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000444static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000445 // FIXME: implement -fpreprocessed mode.
446 bool NoPreprocess = false;
447
Ted Kremenek11ad8952007-12-05 23:49:08 +0000448 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000449 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000450 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000451 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000452 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000453 case langkind_c_cpp:
454 NoPreprocess = true;
455 // FALLTHROUGH
456 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000457 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000458 break;
459 case langkind_cxx_cpp:
460 NoPreprocess = true;
461 // FALLTHROUGH
462 case langkind_cxx:
463 Options.CPlusPlus = 1;
464 break;
465 case langkind_objc_cpp:
466 NoPreprocess = true;
467 // FALLTHROUGH
468 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000469 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000470 break;
471 case langkind_objcxx_cpp:
472 NoPreprocess = true;
473 // FALLTHROUGH
474 case langkind_objcxx:
475 Options.ObjC1 = Options.ObjC2 = 1;
476 Options.CPlusPlus = 1;
477 break;
478 }
479}
480
481/// LangStds - Language standards we support.
482enum LangStds {
483 lang_unspecified,
484 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000485 lang_gnu_START,
486 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000487 lang_cxx98, lang_gnucxx98,
488 lang_cxx0x, lang_gnucxx0x
489};
490
491static llvm::cl::opt<LangStds>
492LangStd("std", llvm::cl::desc("Language standard to compile for"),
493 llvm::cl::init(lang_unspecified),
494 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
495 clEnumValN(lang_c89, "c90", "ISO C 1990"),
496 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
497 clEnumValN(lang_c94, "iso9899:199409",
498 "ISO C 1990 with amendment 1"),
499 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000500 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000501 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000502 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000503 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000504 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000505 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000506 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000507 clEnumValN(lang_gnu99, "gnu9x",
508 "ISO C 1999 with GNU extensions"),
509 clEnumValN(lang_cxx98, "c++98",
510 "ISO C++ 1998 with amendments"),
511 clEnumValN(lang_gnucxx98, "gnu++98",
512 "ISO C++ 1998 with amendments and GNU "
513 "extensions (default for C++)"),
514 clEnumValN(lang_cxx0x, "c++0x",
515 "Upcoming ISO C++ 200x with amendments"),
516 clEnumValN(lang_gnucxx0x, "gnu++0x",
517 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000518 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000519 clEnumValEnd));
520
521static llvm::cl::opt<bool>
522NoOperatorNames("fno-operator-names",
523 llvm::cl::desc("Do not treat C++ operator name keywords as "
524 "synonyms for operators"));
525
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000526static llvm::cl::opt<bool>
527PascalStrings("fpascal-strings",
528 llvm::cl::desc("Recognize and construct Pascal-style "
529 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000530
531static llvm::cl::opt<bool>
532MSExtensions("fms-extensions",
533 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000534 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000535
536static llvm::cl::opt<bool>
537WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000538 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000539
540static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000541NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000542 llvm::cl::desc("Disallow implicit conversions between "
543 "vectors with a different number of "
544 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000545
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000546static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000547EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000548
549static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000550EnableHeinousExtensions("fheinous-gnu-extensions",
551 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
552 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
553
554static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000555ObjCNonFragileABI("fobjc-nonfragile-abi",
556 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000557
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000558static llvm::cl::opt<bool>
559EmitAllDecls("femit-all-decls",
560 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000561
Daniel Dunbar91692d92008-08-11 17:36:14 +0000562// FIXME: This (and all GCC -f options) really come in -f... and
563// -fno-... forms, and additionally support automagic behavior when
564// they are not defined. For example, -fexceptions defaults to on or
565// off depending on the language. We should support this behavior in
566// some form (perhaps just add a facility for distinguishing when an
567// has its default value from when it has been set to its default
568// value).
569static llvm::cl::opt<bool>
570Exceptions("fexceptions",
571 llvm::cl::desc("Enable support for exception handling."));
572
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000573static llvm::cl::opt<bool>
574GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000575 llvm::cl::desc("Generate output compatible with the standard GNU "
576 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000577
578static llvm::cl::opt<bool>
579NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000580 llvm::cl::desc("Generate output compatible with the NeXT "
581 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000582
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000583
584
585static llvm::cl::opt<bool>
586Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
587
Chris Lattner738d3f62009-03-02 22:11:07 +0000588static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000589TargetFeatures("mattr", llvm::cl::CommaSeparated,
590 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
591
Douglas Gregor375733c2009-03-10 00:06:19 +0000592static llvm::cl::opt<unsigned>
593TemplateDepth("ftemplate-depth", llvm::cl::init(99),
594 llvm::cl::desc("Maximum depth of recursive template "
595 "instantiation"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000596
Anders Carlssondfd77642009-04-06 17:37:10 +0000597
598static llvm::cl::opt<bool>
599OptSize("Os", llvm::cl::desc("Optimize for size"));
600
601static llvm::cl::opt<bool>
602NoCommon("fno-common",
603 llvm::cl::desc("Compile common globals like normal definitions"),
604 llvm::cl::ValueDisallowed);
605
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000606static llvm::cl::opt<std::string>
607MainFileName("main-file-name",
608 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000609
610// It might be nice to add bounds to the CommandLine library directly.
611struct OptLevelParser : public llvm::cl::parser<unsigned> {
612 bool parse(llvm::cl::Option &O, const char *ArgName,
613 const std::string &Arg, unsigned &Val) {
614 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
615 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000616 if (Val > 3)
617 return O.error(": '" + Arg + "' invalid optimization level!");
618 return false;
619 }
620};
621static llvm::cl::opt<unsigned, false, OptLevelParser>
622OptLevel("O", llvm::cl::Prefix,
623 llvm::cl::desc("Optimization level"),
624 llvm::cl::init(0));
625
Daniel Dunbare079c712009-04-08 03:03:23 +0000626static llvm::cl::opt<unsigned>
627PICLevel("pic-level", llvm::cl::Prefix,
628 llvm::cl::desc("Value for __PIC__"),
629 llvm::cl::init(0));
630
Chris Lattner4b009652007-07-25 00:24:17 +0000631// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000632// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000633static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
634 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000635 // Allow the target to set the default the langauge options as it sees fit.
636 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000637
Chris Lattnerf6790a82009-03-03 19:56:18 +0000638 // If there are any -mattr options, pass them to the target for validation and
639 // processing. The driver should have already consolidated all the
640 // target-feature settings and passed them to us in the -mattr list. The
641 // -mattr list is treated by the code generator as a diff against the -mcpu
642 // setting, but the driver should pass all enabled options as "+" settings.
643 // This means that the target should only look at + settings.
644 if (!TargetFeatures.empty()
645 // FIXME: The driver is not quite yet ready for this.
646 && 0) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000647 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000648 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
649 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000650 if (Opt != -1) {
651 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000652 fprintf(stderr, "invalid feature '%s'\n",
653 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000654 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000655 fprintf(stderr, "feature '%s': %s\n",
656 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000657 exit(1);
658 }
659 }
660
Chris Lattner4b009652007-07-25 00:24:17 +0000661 if (LangStd == lang_unspecified) {
662 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000663 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000664 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000665 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000666 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000667 case langkind_c_cpp:
668 case langkind_objc:
669 case langkind_objc_cpp:
670 LangStd = lang_gnu99;
671 break;
672 case langkind_cxx:
673 case langkind_cxx_cpp:
674 case langkind_objcxx:
675 case langkind_objcxx_cpp:
676 LangStd = lang_gnucxx98;
677 break;
678 }
679 }
680
681 switch (LangStd) {
682 default: assert(0 && "Unknown language standard!");
683
684 // Fall through from newer standards to older ones. This isn't really right.
685 // FIXME: Enable specifically the right features based on the language stds.
686 case lang_gnucxx0x:
687 case lang_cxx0x:
688 Options.CPlusPlus0x = 1;
689 // FALL THROUGH
690 case lang_gnucxx98:
691 case lang_cxx98:
692 Options.CPlusPlus = 1;
693 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000694 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000695 // FALL THROUGH.
696 case lang_gnu99:
697 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000698 Options.C99 = 1;
699 Options.HexFloats = 1;
700 // FALL THROUGH.
701 case lang_gnu89:
702 Options.BCPLComment = 1; // Only for C99/C++.
703 // FALL THROUGH.
704 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000705 Options.Digraphs = 1; // C94, C99, C++.
706 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000707 case lang_c89:
708 break;
709 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000710
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000711 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
712 Options.GNUMode = LangStd >= lang_gnu_START;
713
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000714 if (Options.CPlusPlus) {
715 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000716 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000717 }
Chris Lattner4b009652007-07-25 00:24:17 +0000718
Chris Lattner6ab935b2008-04-05 06:32:51 +0000719 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
720 Options.ImplicitInt = 1;
721 else
722 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000723
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000724 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
725 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000726 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000727 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000728 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000729
Chris Lattner58d5ba52008-12-05 00:10:44 +0000730 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
731 // even if they are normally on for the target. In GNU modes (e.g.
732 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000733 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000734 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000735 Options.Blocks = 0;
736
Daniel Dunbar551236b2009-03-15 00:11:28 +0000737 // Never accept '$' in identifiers when preprocessing assembler.
738 if (LK != langkind_asm_cpp)
739 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000740 if (PascalStrings.getPosition())
741 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000742 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000743 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000744 if (NoLaxVectorConversions.getPosition())
745 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000746 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000747 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000748 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000749
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000750 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000751 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000752 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000753 Options.Freestanding = Options.NoBuiltin = 1;
754
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000755 if (EnableHeinousExtensions)
756 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000757
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000758 Options.MathErrno = MathErrno;
759
Douglas Gregor375733c2009-03-10 00:06:19 +0000760 Options.InstantiationDepth = TemplateDepth;
761
Chris Lattnerddae7102008-12-04 22:54:33 +0000762 // Override the default runtime if the user requested it.
763 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000764 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000765 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000766 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000767
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000768 if (ObjCNonFragileABI)
769 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000770
771 if (EmitAllDecls)
772 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000773
774 if (OptSize)
775 Options.OptimizeSize = 1;
776
777 // -Os implies -O2
778 if (Options.OptimizeSize || OptLevel)
779 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000780
781 assert(PICLevel <= 2 && "Invalid value for -pic-level");
782 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000783
784 if (MainFileName.getPosition())
785 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000786}
787
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000788static llvm::cl::opt<bool>
789ObjCExclusiveGC("fobjc-gc-only",
790 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000791 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000792
793static llvm::cl::opt<bool>
794ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000795 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000796
797void InitializeGCMode(LangOptions &Options) {
798 if (ObjCExclusiveGC)
799 Options.setGCMode(LangOptions::GCOnly);
800 else if (ObjCEnableGC)
801 Options.setGCMode(LangOptions::HybridGC);
802}
803
Fariborz Jahanian49343332009-04-03 03:28:57 +0000804static llvm::cl::opt<std::string>
805SymbolVisibility("fvisibility",
806 llvm::cl::desc("Set the default visibility to the specific option"));
807
808void InitializeSymbolVisibility(LangOptions &Options) {
809 if (SymbolVisibility.empty())
810 return;
811 std::string Visibility = SymbolVisibility;
812 const char *vkind = Visibility.c_str();
813 if (!strcmp(vkind, "default"))
814 Options.setVisibilityMode(LangOptions::DefaultVisibility);
815 else if (!strcmp(vkind, "protected"))
816 Options.setVisibilityMode(LangOptions::ProtectedVisibility);
817 else if (!strcmp(vkind, "hidden"))
818 Options.setVisibilityMode(LangOptions::HiddenVisibility);
819 else if (!strcmp(vkind, "internal"))
820 Options.setVisibilityMode(LangOptions::InternalVisibility);
821 else
822 fprintf(stderr,
823 "-fvisibility only valid for default|protected|hidden|internal\n");
824}
825
Mike Stumpdb789912009-04-01 20:28:16 +0000826static llvm::cl::opt<bool>
827OverflowChecking("ftrapv",
Mike Stumpf71b7742009-04-02 18:15:54 +0000828 llvm::cl::desc("Trap on integer overflow"),
Mike Stumpdb789912009-04-01 20:28:16 +0000829 llvm::cl::init(false));
830
831void InitializeOverflowChecking(LangOptions &Options) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000832 Options.OverflowChecking = OverflowChecking;
Mike Stumpdb789912009-04-01 20:28:16 +0000833}
Chris Lattner4b009652007-07-25 00:24:17 +0000834//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000835// Target Triple Processing.
836//===----------------------------------------------------------------------===//
837
838static llvm::cl::opt<std::string>
839TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000840 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000841
Chris Lattnerfc457002008-03-05 01:18:20 +0000842static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000843Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000844
Chris Lattner2b168e02008-09-30 01:13:12 +0000845static llvm::cl::opt<std::string>
846MacOSVersionMin("mmacosx-version-min",
847 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
848
Chris Lattner01de9c82008-09-30 20:16:56 +0000849// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
850// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000851
852// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000853static void HandleMacOSVersionMin(std::string &Triple) {
854 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
855 if (DarwinDashIdx == std::string::npos) {
856 fprintf(stderr,
857 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
858 exit(1);
859 }
860 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
861
Chris Lattner01de9c82008-09-30 20:16:56 +0000862 // Remove the number.
863 Triple.resize(DarwinNumIdx);
864
865 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
866 bool MacOSVersionMinIsInvalid = false;
867 int VersionNum = 0;
868 if (MacOSVersionMin.size() < 4 ||
869 MacOSVersionMin.substr(0, 3) != "10." ||
870 !isdigit(MacOSVersionMin[3])) {
871 MacOSVersionMinIsInvalid = true;
872 } else {
873 const char *Start = MacOSVersionMin.c_str()+3;
874 char *End = 0;
875 VersionNum = (int)strtol(Start, &End, 10);
876
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000877 // The version number must be in the range 0-9.
878 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
879
Chris Lattner01de9c82008-09-30 20:16:56 +0000880 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
881 Triple += llvm::itostr(VersionNum+4);
882
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000883 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
884 // Add the period piece (.7) to the end of the triple. This gives us
885 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000886 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000887 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
888 MacOSVersionMinIsInvalid = true;
889 }
890 }
891
892 if (MacOSVersionMinIsInvalid) {
893 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000894 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000895 MacOSVersionMin.c_str());
896 exit(1);
897 }
898}
899
900/// CreateTargetTriple - Process the various options that affect the target
901/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000902static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000903 // Initialize base triple. If a -triple option has been specified, use
904 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000905 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000906 if (Triple.empty())
907 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000908
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000909 // If -arch foo was specified, remove the architecture from the triple we have
910 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000911
912 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +0000913 if (!Arch.empty()) {
914 // Decompose the base triple into "arch" and suffix.
915 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000916
Chris Lattner2b168e02008-09-30 01:13:12 +0000917 if (FirstDashIdx == std::string::npos) {
918 fprintf(stderr,
919 "Malformed target triple: \"%s\" ('-' could not be found).\n",
920 Triple.c_str());
921 exit(1);
922 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +0000923
924 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
925 if (Arch == "ppc")
926 Arch = "powerpc";
927 else if (Arch == "ppc64")
928 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +0000929
Chris Lattner2b168e02008-09-30 01:13:12 +0000930 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
931 }
932
933 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
934 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000935 if (!MacOSVersionMin.empty())
936 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000937
Chris Lattner2b168e02008-09-30 01:13:12 +0000938 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000939}
940
941//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000942// Preprocessor Initialization
943//===----------------------------------------------------------------------===//
944
945// FIXME: Preprocessor builtins to support.
946// -A... - Play with #assertions
947// -undef - Undefine all predefined macros
948
Chris Lattner695a4f52009-03-13 01:08:23 +0000949// FIXME: -imacros
950
Chris Lattner4b009652007-07-25 00:24:17 +0000951static llvm::cl::list<std::string>
952D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
953 llvm::cl::desc("Predefine the specified macro"));
954static llvm::cl::list<std::string>
955U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
956 llvm::cl::desc("Undefine the specified macro"));
957
Chris Lattner008da782008-01-10 01:53:41 +0000958static llvm::cl::list<std::string>
959ImplicitIncludes("include", llvm::cl::value_desc("file"),
960 llvm::cl::desc("Include file before parsing"));
961
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000962static llvm::cl::opt<std::string>
963ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
964 llvm::cl::desc("Include file before parsing"));
965
Chris Lattner4b009652007-07-25 00:24:17 +0000966// Append a #define line to Buf for Macro. Macro should be of the form XXX,
967// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
968// "#define XXX Y z W". To get a #define with no value, use "XXX=".
969static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
970 const char *Command = "#define ") {
971 Buf.insert(Buf.end(), Command, Command+strlen(Command));
972 if (const char *Equal = strchr(Macro, '=')) {
973 // Turn the = into ' '.
974 Buf.insert(Buf.end(), Macro, Equal);
975 Buf.push_back(' ');
Chris Lattner39baafb2009-04-07 06:02:44 +0000976
977 // Per GCC -D semantics, the macro ends at \n if it exists.
978 const char *End = strpbrk(Equal, "\n\r");
Chris Lattner39c610d2009-04-07 18:18:09 +0000979 if (End) {
Chris Lattnerd93f7902009-04-08 03:36:03 +0000980 fprintf(stderr, "warning: macro '%s' contains embedded newline, text "
Chris Lattner39c610d2009-04-07 18:18:09 +0000981 "after the newline is ignored.\n",
982 std::string(Macro, Equal).c_str());
983 } else {
984 End = Equal+strlen(Equal);
985 }
Chris Lattner39baafb2009-04-07 06:02:44 +0000986
987 Buf.insert(Buf.end(), Equal+1, End);
Chris Lattner4b009652007-07-25 00:24:17 +0000988 } else {
989 // Push "macroname 1".
990 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
991 Buf.push_back(' ');
992 Buf.push_back('1');
993 }
994 Buf.push_back('\n');
995}
996
Chris Lattner008da782008-01-10 01:53:41 +0000997/// AddImplicitInclude - Add an implicit #include of the specified file to the
998/// predefines buffer.
999static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
1000 const char *Inc = "#include \"";
1001 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
1002 Buf.insert(Buf.end(), File.begin(), File.end());
1003 Buf.push_back('"');
1004 Buf.push_back('\n');
1005}
1006
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001007/// AddImplicitIncludePTH - Add an implicit #include using the original file
1008/// used to generate a PTH cache.
1009static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
1010 PTHManager *P = PP.getPTHManager();
1011 assert(P && "No PTHManager.");
1012 const char *OriginalFile = P->getOriginalSourceFile();
1013
1014 if (!OriginalFile) {
1015 assert(!ImplicitIncludePTH.empty());
1016 fprintf(stderr, "error: PTH file '%s' does not designate an original "
1017 "source header file for -include-pth\n",
1018 ImplicitIncludePTH.c_str());
1019 exit (1);
1020 }
1021
1022 AddImplicitInclude(Buf, OriginalFile);
1023}
Chris Lattner4b009652007-07-25 00:24:17 +00001024
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001025/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +00001026/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001027///
Chris Lattner9d818a22008-04-19 23:25:44 +00001028static bool InitializePreprocessor(Preprocessor &PP,
1029 bool InitializeSourceMgr,
1030 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +00001031 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +00001032
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001033 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +00001034 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001035
1036 if (InitializeSourceMgr) {
1037 if (InFile != "-") {
1038 const FileEntry *File = FileMgr.getFile(InFile);
1039 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +00001040 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001041 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1042 << InFile.c_str();
Chris Lattner9d818a22008-04-19 23:25:44 +00001043 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001044 }
1045 } else {
1046 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar99617162009-03-21 17:56:30 +00001047
1048 // If stdin was empty, SB is null. Cons up an empty memory
1049 // buffer now.
1050 if (!SB) {
1051 const char *EmptyStr = "";
1052 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1053 }
1054
1055 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +00001056 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001057 PP.getDiagnostics().Report(FullSourceLoc(),
1058 diag::err_fe_error_reading_stdin);
Chris Lattner9d818a22008-04-19 23:25:44 +00001059 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001060 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001061 }
Chris Lattner4b009652007-07-25 00:24:17 +00001062 }
Sam Bishop61a20782008-04-14 14:41:57 +00001063
Chris Lattner47b6a162008-04-19 23:09:31 +00001064 std::vector<char> PredefineBuffer;
1065
Chris Lattner4b009652007-07-25 00:24:17 +00001066 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +00001067 unsigned d = 0, D = D_macros.size();
1068 unsigned u = 0, U = U_macros.size();
1069 while (d < D || u < U) {
1070 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1071 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
1072 else
1073 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
1074 }
1075
Chris Lattner008da782008-01-10 01:53:41 +00001076 // FIXME: Read any files specified by -imacros.
1077
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001078 // Add implicit #includes from -include and -include-pth.
1079 bool handledPTH = ImplicitIncludePTH.empty();
1080 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc4ecf322009-03-20 00:40:03 +00001081 if (!handledPTH &&
1082 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001083 AddImplicitIncludePTH(PredefineBuffer, PP);
1084 handledPTH = true;
1085 }
1086
Chris Lattner008da782008-01-10 01:53:41 +00001087 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001088 }
1089 if (!handledPTH && !ImplicitIncludePTH.empty())
1090 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001091
Chris Lattner47b6a162008-04-19 23:09:31 +00001092 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001093 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +00001094 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001095
1096 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +00001097 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001098}
1099
1100//===----------------------------------------------------------------------===//
1101// Preprocessor include path information.
1102//===----------------------------------------------------------------------===//
1103
1104// This tool exports a large number of command line options to control how the
1105// preprocessor searches for header files. At root, however, the Preprocessor
1106// object takes a very simple interface: a list of directories to search for
1107//
1108// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001109// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001110//
Chris Lattner4b009652007-07-25 00:24:17 +00001111
1112static llvm::cl::opt<bool>
1113nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1114
1115// Various command line options. These four add directories to each chain.
1116static llvm::cl::list<std::string>
1117F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1118 llvm::cl::desc("Add directory to framework include search path"));
1119static llvm::cl::list<std::string>
1120I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1121 llvm::cl::desc("Add directory to include search path"));
1122static llvm::cl::list<std::string>
1123idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1124 llvm::cl::desc("Add directory to AFTER include search path"));
1125static llvm::cl::list<std::string>
1126iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1127 llvm::cl::desc("Add directory to QUOTE include search path"));
1128static llvm::cl::list<std::string>
1129isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1130 llvm::cl::desc("Add directory to SYSTEM include search path"));
1131
1132// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1133static llvm::cl::list<std::string>
1134iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1135 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1136static llvm::cl::list<std::string>
1137iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1138 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1139static llvm::cl::list<std::string>
1140iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1141 llvm::cl::Prefix,
1142 llvm::cl::desc("Set directory to include search path with prefix"));
1143
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001144static llvm::cl::opt<std::string>
1145isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1146 llvm::cl::desc("Set the system root directory (usually /)"));
1147
Chris Lattner4b009652007-07-25 00:24:17 +00001148// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001149
Chris Lattner4b009652007-07-25 00:24:17 +00001150/// InitializeIncludePaths - Process the -I options and set them in the
1151/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001152void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1153 FileManager &FM, const LangOptions &Lang) {
1154 InitHeaderSearch Init(Headers, Verbose, isysroot);
1155
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001156 // Handle -I... and -F... options, walking the lists in parallel.
1157 unsigned Iidx = 0, Fidx = 0;
1158 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1159 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001160 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001161 ++Iidx;
1162 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001163 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001164 ++Fidx;
1165 }
1166 }
Chris Lattner4b009652007-07-25 00:24:17 +00001167
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001168 // Consume what's left from whatever list was longer.
1169 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001170 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001171 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001172 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001173
1174 // Handle -idirafter... options.
1175 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001176 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1177 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001178
1179 // Handle -iquote... options.
1180 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001181 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001182
1183 // Handle -isystem... options.
1184 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001185 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001186
1187 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1188 // parallel, processing the values in order of occurance to get the right
1189 // prefixes.
1190 {
1191 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1192 unsigned iprefix_idx = 0;
1193 unsigned iwithprefix_idx = 0;
1194 unsigned iwithprefixbefore_idx = 0;
1195 bool iprefix_done = iprefix_vals.empty();
1196 bool iwithprefix_done = iwithprefix_vals.empty();
1197 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1198 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1199 if (!iprefix_done &&
1200 (iwithprefix_done ||
1201 iprefix_vals.getPosition(iprefix_idx) <
1202 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1203 (iwithprefixbefore_done ||
1204 iprefix_vals.getPosition(iprefix_idx) <
1205 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1206 Prefix = iprefix_vals[iprefix_idx];
1207 ++iprefix_idx;
1208 iprefix_done = iprefix_idx == iprefix_vals.size();
1209 } else if (!iwithprefix_done &&
1210 (iwithprefixbefore_done ||
1211 iwithprefix_vals.getPosition(iwithprefix_idx) <
1212 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001213 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1214 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001215 ++iwithprefix_idx;
1216 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1217 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001218 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1219 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001220 ++iwithprefixbefore_idx;
1221 iwithprefixbefore_done =
1222 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1223 }
1224 }
1225 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001226
Nico Weber770e3882008-08-22 09:25:22 +00001227 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001228
Daniel Dunbar4e604292009-02-21 20:52:41 +00001229 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001230 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001231 llvm::sys::Path::GetMainExecutable(Argv0,
1232 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001233 if (!MainExecutablePath.isEmpty()) {
1234 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1235 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001236
1237 // Get foo/lib/clang/1.0/include
1238 //
1239 // FIXME: Don't embed version here.
1240 MainExecutablePath.appendComponent("lib");
1241 MainExecutablePath.appendComponent("clang");
1242 MainExecutablePath.appendComponent("1.0");
1243 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001244
1245 // We pass true to ignore sysroot so that we *always* look for clang headers
1246 // relative to our executable, never relative to -isysroot.
1247 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1248 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001249 }
1250
Nico Weber770e3882008-08-22 09:25:22 +00001251 if (!nostdinc)
1252 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001253
1254 // Now that we have collected all of the include paths, merge them all
1255 // together and tell the preprocessor about them.
1256
Nico Weber770e3882008-08-22 09:25:22 +00001257 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001258}
1259
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001260//===----------------------------------------------------------------------===//
1261// Driver PreprocessorFactory - For lazily generating preprocessors ...
1262//===----------------------------------------------------------------------===//
1263
1264namespace {
1265class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001266 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001267 Diagnostic &Diags;
1268 const LangOptions &LangInfo;
1269 TargetInfo &Target;
1270 SourceManager &SourceMgr;
1271 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001272 bool InitializeSourceMgr;
1273
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001274public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001275 DriverPreprocessorFactory(const std::string &infile,
1276 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001277 TargetInfo &target, SourceManager &SM,
1278 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001279 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1280 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1281
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001282
1283 virtual ~DriverPreprocessorFactory() {}
1284
1285 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001286 llvm::OwningPtr<PTHManager> PTHMgr;
1287
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001288 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1289 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1290 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001291 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001292 }
1293
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001294 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001295 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1296 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001297 PTHMgr.reset(PTHManager::Create(x, &Diags,
1298 TokenCache.empty() ? Diagnostic::Error
1299 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001300 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001301
Ted Kremenek6348cc62009-03-22 06:42:39 +00001302 if (Diags.hasErrorOccurred())
1303 exit(1);
1304
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001305 // Create the Preprocessor.
1306 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1307 SourceMgr, HeaderInfo,
1308 PTHMgr.get()));
1309
1310 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1311 // That argument is used as the IdentifierInfoLookup argument to
1312 // IdentifierTable's ctor.
1313 if (PTHMgr) {
1314 PTHMgr->setPreprocessor(PP.get());
1315 PP->setPTHManager(PTHMgr.take());
1316 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001317
Chris Lattner9d818a22008-04-19 23:25:44 +00001318 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001319 return NULL;
1320 }
1321
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001322 /// FIXME: PP can only handle one callback
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001323 if (ProgAction != PrintPreprocessedInput) {
1324 std::string ErrStr;
1325 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1326 if (!DFG && !ErrStr.empty()) {
1327 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001328 return NULL;
1329 }
1330 }
1331
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001332 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001333 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001334 }
1335};
1336}
Chris Lattner4b009652007-07-25 00:24:17 +00001337
Chris Lattner4b009652007-07-25 00:24:17 +00001338//===----------------------------------------------------------------------===//
1339// Basic Parser driver
1340//===----------------------------------------------------------------------===//
1341
Chris Lattner9d818a22008-04-19 23:25:44 +00001342static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001343 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001344 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001345
1346 // Parsing the specified input file.
1347 P.ParseTranslationUnit();
1348 delete PA;
1349}
1350
1351//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001352// Code generation options
1353//===----------------------------------------------------------------------===//
1354
1355static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001356GenerateDebugInfo("g",
1357 llvm::cl::desc("Generate source level debug information"));
1358
Daniel Dunbar9101a632009-02-17 19:47:34 +00001359static llvm::cl::opt<std::string>
1360TargetCPU("mcpu",
1361 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1362
Chris Lattner8a9615c2009-03-16 18:41:18 +00001363static void InitializeCompileOptions(CompileOptions &Opts,
1364 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001365 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001366 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001367 if (OptSize) {
1368 // -Os implies -O2
1369 // FIXME: Diagnose conflicting options.
1370 Opts.OptimizationLevel = 2;
1371 } else {
1372 Opts.OptimizationLevel = OptLevel;
1373 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001374
1375 // FIXME: There are llvm-gcc options to control these selectively.
1376 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1377 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001378 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001379
1380#ifdef NDEBUG
1381 Opts.VerifyModule = 0;
1382#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001383
1384 Opts.CPU = TargetCPU;
1385 Opts.Features.insert(Opts.Features.end(),
1386 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001387
Chris Lattnerf04a7562009-03-26 05:00:52 +00001388 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1389
Chris Lattnere8f70712009-02-18 01:23:44 +00001390 // Handle -ftime-report.
1391 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001392}
1393
1394//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001395// Fix-It Options
1396//===----------------------------------------------------------------------===//
1397static llvm::cl::list<ParsedSourceLocation>
1398FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1399 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1400
1401//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001402// Main driver
1403//===----------------------------------------------------------------------===//
1404
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001405/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001406/// action. These consumers can operate on both ASTs that are freshly
1407/// parsed from source files as well as those deserialized from Bitcode.
1408/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001409static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001410 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001411 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001412 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001413 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001414 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001415 default:
1416 return NULL;
1417
1418 case ASTPrint:
1419 return CreateASTPrinter();
1420
1421 case ASTDump:
1422 return CreateASTDumper();
1423
1424 case ASTView:
1425 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001426
Chris Lattner7f902922009-02-18 01:20:05 +00001427 case PrintDeclContext:
1428 return CreateDeclContextPrinter();
1429
1430 case EmitHTML:
1431 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001432
Chris Lattner7f902922009-02-18 01:20:05 +00001433 case InheritanceView:
1434 return CreateInheritanceViewer(InheritanceViewCls);
1435
1436 case TestSerialization:
1437 return CreateSerializationTest(Diag, FileMgr);
1438
1439 case EmitAssembly:
1440 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001441 case EmitBC:
1442 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001443 BackendAction Act;
1444 if (ProgAction == EmitAssembly)
1445 Act = Backend_EmitAssembly;
1446 else if (ProgAction == EmitLLVM)
1447 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001448 else if (ProgAction == EmitLLVMOnly)
1449 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001450 else
1451 Act = Backend_EmitBC;
1452
1453 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001454 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001455 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001456 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001457 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001458
Chris Lattner7f902922009-02-18 01:20:05 +00001459 case SerializeAST:
1460 // FIXME: Allow user to tailor where the file is written.
1461 return CreateASTSerializer(InFile, OutputFile, Diag);
1462
1463 case RewriteObjC:
1464 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001465
Chris Lattner7f902922009-02-18 01:20:05 +00001466 case RewriteBlocks:
1467 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1468
1469 case RunAnalysis:
1470 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001471 }
1472}
1473
Chris Lattner4b009652007-07-25 00:24:17 +00001474/// ProcessInputFile - Process a single input file with the specified state.
1475///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001476static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001477 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001478 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001479 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001480 FixItRewriter *FixItRewrite = 0;
1481
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001482 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001483 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001484 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1485 PP.getFileManager(), PP.getLangOptions(),
1486 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001487
1488 if (!Consumer) {
1489 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001490 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001491 return;
1492 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001493
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001494 break;
1495
Chris Lattneraf669fb2008-10-12 05:03:36 +00001496 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001497 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001498 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001499 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001500 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001501 RawLex.SetKeepWhitespaceMode(true);
1502
1503 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001504 RawLex.LexFromRawLexer(RawTok);
1505 while (RawTok.isNot(tok::eof)) {
1506 PP.DumpToken(RawTok, true);
1507 fprintf(stderr, "\n");
1508 RawLex.LexFromRawLexer(RawTok);
1509 }
1510 ClearSourceMgr = true;
1511 break;
1512 }
Chris Lattner4b009652007-07-25 00:24:17 +00001513 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001514 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001515 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001516 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001517 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001518 do {
1519 PP.Lex(Tok);
1520 PP.DumpToken(Tok, true);
1521 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001522 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001523 ClearSourceMgr = true;
1524 break;
1525 }
1526 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001527 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001528 Token Tok;
1529 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001530 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001531 do {
1532 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001533 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001534 ClearSourceMgr = true;
1535 break;
1536 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001537
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001538 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001539 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001540 CacheTokens(PP, OutputFile);
1541 ClearSourceMgr = true;
1542 break;
1543 }
Chris Lattner4b009652007-07-25 00:24:17 +00001544
Chris Lattnerefe33382009-02-18 01:51:21 +00001545 case PrintPreprocessedInput: { // -E mode.
1546 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001547 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001548 ClearSourceMgr = true;
1549 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001550 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001551
Chris Lattnerefe33382009-02-18 01:51:21 +00001552 case ParseNoop: { // -parse-noop
1553 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001554 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001555 ClearSourceMgr = true;
1556 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001557 }
Chris Lattner4b009652007-07-25 00:24:17 +00001558
Chris Lattnerefe33382009-02-18 01:51:21 +00001559 case ParsePrintCallbacks: {
1560 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001561 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001562 ClearSourceMgr = true;
1563 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001564 }
1565
1566 case ParseSyntaxOnly: { // -fsyntax-only
1567 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001568 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001569 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001570 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001571
1572 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001573 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001574 ClearSourceMgr = true;
1575 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001576
Chris Lattnerefe33382009-02-18 01:51:21 +00001577 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001578 DoRewriteTest(PP, InFile, OutputFile);
1579 ClearSourceMgr = true;
1580 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001581 }
Douglas Gregor133d2552009-04-02 01:08:08 +00001582
1583 case FixIt:
1584 llvm::TimeRegion Timer(ClangFrontendTimer);
1585 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001586 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Douglas Gregor133d2552009-04-02 01:08:08 +00001587 PP.getSourceManager());
Douglas Gregor133d2552009-04-02 01:08:08 +00001588 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001589 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001590
1591 if (Consumer) {
Chris Lattner143fd6d2009-03-28 01:37:17 +00001592 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner143fd6d2009-03-28 01:37:17 +00001593
Douglas Gregor24b48b02009-04-02 19:05:20 +00001594 if (FixItAtLocations.size() > 0) {
1595 // Even without the "-fixit" flag, with may have some specific
1596 // locations where the user has requested fixes. Process those
1597 // locations now.
1598 if (!FixItRewrite)
1599 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1600 PP.getSourceManager());
1601
1602 bool AddedFixitLocation = false;
1603 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1604 Idx != Last; ++Idx) {
1605 RequestedSourceLocation Requested;
1606 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1607 Requested)) {
1608 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1609 FixItAtLocations[Idx].FileName.c_str());
1610 } else {
1611 FixItRewrite->addFixItLocation(Requested);
1612 AddedFixitLocation = true;
1613 }
1614 }
1615
1616 if (!AddedFixitLocation) {
1617 // All of the fix-it locations were bad. Don't fix anything.
1618 delete FixItRewrite;
1619 FixItRewrite = 0;
1620 }
1621 }
1622
Chris Lattner143fd6d2009-03-28 01:37:17 +00001623 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1624 PP.getSourceManager(),
1625 PP.getTargetInfo(),
1626 PP.getIdentifierTable(),
1627 PP.getSelectorTable(),
1628 /* FreeMemory = */ !DisableFree));
Chris Lattner143fd6d2009-03-28 01:37:17 +00001629
1630
Chris Lattner07b08c02009-03-28 04:13:34 +00001631 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner143fd6d2009-03-28 01:37:17 +00001632
Douglas Gregor133d2552009-04-02 01:08:08 +00001633 if (FixItRewrite)
1634 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1635
Chris Lattner143fd6d2009-03-28 01:37:17 +00001636 // If in -disable-free mode, don't deallocate these when they go out of
1637 // scope.
Chris Lattner07b08c02009-03-28 04:13:34 +00001638 if (DisableFree)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001639 ContextOwner.take();
Ted Kremenek88eebed2009-01-28 04:29:29 +00001640 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001641
1642 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001643 if (CheckDiagnostics(PP))
1644 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001645
Chris Lattner4b009652007-07-25 00:24:17 +00001646 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001647 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001648 PP.PrintStats();
1649 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001650 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001651 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001652 fprintf(stderr, "\n");
1653 }
1654
1655 // For a multi-file compilation, some things are ok with nuking the source
1656 // manager tables, other require stable fileid/macroid's across multiple
1657 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001658 if (ClearSourceMgr)
1659 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001660
1661 if (DisableFree)
1662 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001663}
1664
Ted Kremenek80d53372007-12-12 23:41:08 +00001665static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1666 FileManager& FileMgr) {
1667
1668 if (VerifyDiagnostics) {
1669 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1670 exit (1);
1671 }
1672
1673 llvm::sys::Path Filename(InFile);
1674
1675 if (!Filename.isValid()) {
1676 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1677 exit (1);
1678 }
1679
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001680 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner06459ae2009-03-28 03:49:26 +00001681
1682 // Create the memory buffer that contains the contents of the file.
1683 llvm::OwningPtr<llvm::MemoryBuffer>
1684 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1685
1686 if (MBuffer)
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001687 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001688
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001689 if (!Ctx) {
Ted Kremenek2bd42412007-12-13 18:11:11 +00001690 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1691 InFile.c_str());
1692 exit (1);
1693 }
1694
Ted Kremenekab749372007-12-19 19:27:38 +00001695 // Observe that we use the source file name stored in the deserialized
1696 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001697 llvm::OwningPtr<ASTConsumer>
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001698 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001699 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001700
Ted Kremenek80d53372007-12-12 23:41:08 +00001701 if (!Consumer) {
1702 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1703 exit (1);
1704 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001705
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001706 Consumer->Initialize(*Ctx);
Nico Weberd2a6ac92008-08-10 19:59:06 +00001707
Chris Lattner8d72ee02008-02-06 01:42:25 +00001708 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001709 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1710 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1711 I != E; ++I)
Chris Lattnera17991f2009-03-29 16:50:03 +00001712 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek80d53372007-12-12 23:41:08 +00001713}
1714
1715
Chris Lattner4b009652007-07-25 00:24:17 +00001716static llvm::cl::list<std::string>
1717InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1718
Ted Kremenek80d53372007-12-12 23:41:08 +00001719static bool isSerializedFile(const std::string& InFile) {
1720 if (InFile.size() < 4)
1721 return false;
1722
1723 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00001724 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00001725}
1726
Chris Lattner4b009652007-07-25 00:24:17 +00001727
1728int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001729 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001730 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001731 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001732 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001733
Chris Lattnerefe33382009-02-18 01:51:21 +00001734 if (TimeReport)
1735 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1736
Chris Lattner4b009652007-07-25 00:24:17 +00001737 // If no input was specified, read from stdin.
1738 if (InputFilenames.empty())
1739 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001740
Chris Lattner4b009652007-07-25 00:24:17 +00001741 // Create a file manager object to provide access to and cache the filesystem.
1742 FileManager FileMgr;
1743
Ted Kremenekb240e822007-12-11 23:28:38 +00001744 // Create the diagnostic client for reporting errors or for
1745 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001746 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001747
Ted Kremenek5c341732008-08-07 17:49:57 +00001748 if (!VerifyDiagnostics) {
1749 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001750 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1751 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001752 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00001753 !NoShowLocation,
1754 PrintSourceRangeInfo);
Ted Kremenek5c341732008-08-07 17:49:57 +00001755 } else {
1756 // When checking diagnostics, just buffer them up.
1757 TextDiagClient = new TextDiagnosticBuffer();
1758
1759 if (InputFilenames.size() != 1) {
1760 fprintf(stderr,
1761 "-verify only works on single input files for now.\n");
1762 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001763 }
1764 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001765
Chris Lattner4b009652007-07-25 00:24:17 +00001766 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001767 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1768 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001769 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001770 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001771
Chris Lattner45a56e02007-12-05 23:24:17 +00001772 // -I- is a deprecated GCC feature, scan for it and reject it.
1773 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1774 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001775 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001776 I_dirs.erase(I_dirs.begin()+i);
1777 --i;
1778 }
1779 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001780
1781 // Get information about the target being compiled for.
1782 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001783 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1784
Chris Lattner2c77d852008-03-14 06:12:05 +00001785 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001786 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1787 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001788 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001789 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001790
Daniel Dunbar9c321102009-01-20 23:17:32 +00001791 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001792 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001793
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001794 llvm::OwningPtr<SourceManager> SourceMgr;
1795
Chris Lattner4b009652007-07-25 00:24:17 +00001796 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001797 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001798
Ted Kremenek5c341732008-08-07 17:49:57 +00001799 if (isSerializedFile(InFile)) {
1800 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001801 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00001802 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001803 }
Chris Lattner2b989562009-03-04 21:40:56 +00001804
1805 /// Create a SourceManager object. This tracks and owns all the file
1806 /// buffers allocated to a translation unit.
1807 if (!SourceMgr)
1808 SourceMgr.reset(new SourceManager());
1809 else
1810 SourceMgr->clearIDTables();
1811
1812 // Initialize language options, inferring file types from input filenames.
1813 LangOptions LangInfo;
1814 InitializeBaseLanguage();
1815 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001816 InitializeLangOptions(LangInfo, LK);
Chris Lattner2b989562009-03-04 21:40:56 +00001817 InitializeGCMode(LangInfo);
Fariborz Jahanian49343332009-04-03 03:28:57 +00001818 InitializeSymbolVisibility(LangInfo);
Mike Stumpdb789912009-04-01 20:28:16 +00001819 InitializeOverflowChecking(LangInfo);
Chris Lattner2b989562009-03-04 21:40:56 +00001820 InitializeLanguageStandard(LangInfo, LK, Target.get());
1821
1822 // Process the -I options and set them in the HeaderInfo.
1823 HeaderSearch HeaderInfo(FileMgr);
1824
1825 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1826
1827 // Set up the preprocessor with these options.
1828 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1829 *SourceMgr.get(), HeaderInfo);
1830
1831 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1832
1833 if (!PP)
1834 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001835
Chris Lattner2b989562009-03-04 21:40:56 +00001836 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1837 // always reset to using TextDiagClient.
1838 llvm::OwningPtr<DiagnosticClient> TmpClient;
1839
1840 if (!HTMLDiag.empty()) {
1841 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1842 &PPFactory));
1843 Diags.setClient(TmpClient.get());
Ted Kremenek80d53372007-12-12 23:41:08 +00001844 }
Chris Lattner2b989562009-03-04 21:40:56 +00001845 else
1846 Diags.setClient(TextDiagClient);
1847
1848 // Process the source file.
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001849 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattner2b989562009-03-04 21:40:56 +00001850
1851 HeaderInfo.ClearFileInfo();
Chris Lattner4b009652007-07-25 00:24:17 +00001852 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001853
Mike Stump91d01352009-01-28 02:43:35 +00001854 if (Verbose)
1855 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1856 " hosted on " LLVM_HOSTTRIPLE "\n");
1857
Ted Kremenekec6c5252008-08-07 18:13:12 +00001858 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001859 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1860 (NumDiagnostics == 1 ? "" : "s"));
1861
1862 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001863 FileMgr.PrintStats();
1864 fprintf(stderr, "\n");
1865 }
1866
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001867 // If verifying diagnostics and we reached here, all is well.
1868 if (VerifyDiagnostics)
1869 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001870
1871 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001872
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001873 // Managed static deconstruction. Useful for making things like
1874 // -time-passes usable.
1875 llvm::llvm_shutdown();
1876
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001877 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001878}