blob: 13e43891594f03940ece080dea5fea2ceca50a5f [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Ted Kremenekc2542b62009-03-31 18:58:14 +000025#include "clang-cc.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000031#include "clang/Frontend/PathDiagnosticClients.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000032#include "clang/Frontend/TextDiagnosticBuffer.h"
33#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000034#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000039#include "clang/AST/ASTContext.h"
40#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000041#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000042#include "clang/Parse/Parser.h"
43#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000044#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045#include "clang/Basic/FileManager.h"
46#include "clang/Basic/SourceManager.h"
47#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000048#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000049#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000050#include "llvm/ADT/StringExtras.h"
51#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000052#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000053#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000054#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000055#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000056#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000057#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000058#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000059#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000060#include "llvm/System/Signals.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000061#include <cstdlib>
62
Reid Spencer5f016e22007-07-11 17:01:13 +000063using namespace clang;
64
65//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-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//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000149// Global options.
150//===----------------------------------------------------------------------===//
151
Chris Lattner47099742009-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 Dunbard3db4012008-10-16 16:54:18 +0000157static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000158
Reid Spencer5f016e22007-07-11 17:01:13 +0000159static llvm::cl::opt<bool>
160Verbose("v", llvm::cl::desc("Enable verbose output"));
161static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +0000162Stats("print-stats",
163 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-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));
Reid Spencer5f016e22007-07-11 17:01:13 +0000168
169enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000170 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000171 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000172 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000173 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000174 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000175 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000176 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000178 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +0000179 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000180 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +0000181 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-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 Xu2d75d6f2009-01-13 01:29:24 +0000185 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000186 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerc106c102008-10-12 05:03:36 +0000192 DumpTokens, // Dump out preprocessed tokens.
193 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000194 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000195 GeneratePTH, // Generate pre-tokenized header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000196 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerc106c102008-10-12 05:03:36 +0000207 clEnumValN(DumpRawTokens, "dump-raw-tokens",
208 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000209 clEnumValN(RunAnalysis, "analyze",
210 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000211 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek6a340832008-03-18 21:19:49 +0000219 clEnumValN(EmitHTML, "emit-html",
220 "Output input source as HTML"),
Chris Lattner3b427b32007-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 Lattnerea254db2007-10-11 00:37:43 +0000225 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000226 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000227 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000228 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000229 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000230 "Generate pre-tokenized header file"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000231 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000232 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000233 clEnumValN(EmitAssembly, "S",
234 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000236 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000237 clEnumValN(EmitBC, "emit-llvm-bc",
238 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000239 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
240 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000241 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000242 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000243 clEnumValN(RewriteTest, "rewrite-test",
244 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000245 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-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 Naroff13188952008-09-18 14:10:13 +0000249 clEnumValN(RewriteBlocks, "rewrite-blocks",
250 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000251 clEnumValN(FixIt, "fixit",
252 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 clEnumValEnd));
254
Ted Kremenekccc76472007-12-19 19:47:59 +0000255
256static llvm::cl::opt<std::string>
257OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000258 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000259 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000260
Ted Kremenekc2e72992008-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 Guptae8b9f5b2008-05-08 08:54:20 +0000270//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000271// Diagnostic Options
272//===----------------------------------------------------------------------===//
273
Ted Kremenek41193e42007-09-26 19:42:19 +0000274static llvm::cl::opt<bool>
275VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000276 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000277
Ted Kremenek88f5cde2008-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 Weberfd54ebc2008-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 Lattner65f5e642009-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 Weberfd54ebc2008-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 Lattner1fbee5d2009-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 Weberfd54ebc2008-08-05 23:33:20 +0000301
Reid Spencer5f016e22007-07-11 17:01:13 +0000302//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-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 Dunbard77b2512009-01-14 18:56:36 +0000309 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000310
311//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000312// Builtin Options
313//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-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 Gregor3573c0c2009-02-14 20:49:29 +0000320static llvm::cl::opt<bool>
321Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000322 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000323 "freestanding environment"));
324
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000325static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000326AllowBuiltins("fbuiltin", llvm::cl::init(true),
327 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000328
329
330static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000331MathErrno("fmath-errno", llvm::cl::init(true),
332 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000333
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000334//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000335// Language Options
336//===----------------------------------------------------------------------===//
337
338enum LangKind {
339 langkind_unspecified,
340 langkind_c,
341 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000342 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 langkind_cxx,
344 langkind_cxx_cpp,
345 langkind_objc,
346 langkind_objc_cpp,
347 langkind_objcxx,
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000348 langkind_objcxx_cpp
Reid Spencer5f016e22007-07-11 17:01:13 +0000349};
350
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbard2ea3862009-01-29 23:50:47 +0000358 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000360 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
361 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000363 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
365 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000366 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-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"),
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek8904f152007-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 Lattner9b2f6c42008-01-04 19:12:28 +0000401 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 }
403
Ted Kremenek8904f152007-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 Lattnerd9cd4c92009-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 Lattnera778d7d2008-10-22 17:29:21 +0000414 return langkind_asm_cpp;
Ted Kremenek8904f152007-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 Kremenek85888962008-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 Dunbar0b5b0da2009-04-01 05:09:09 +0000444static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000445 // FIXME: implement -fpreprocessed mode.
446 bool NoPreprocess = false;
447
Ted Kremenek8904f152007-12-05 23:49:08 +0000448 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000450 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000451 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000452 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 case langkind_c_cpp:
454 NoPreprocess = true;
455 // FALLTHROUGH
456 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000457 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek85888962008-10-21 00:54:44 +0000469 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenekea644d82008-09-03 21:22:16 +0000485 lang_gnu_START,
486 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000487 lang_cxx98, lang_gnucxx98,
488 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000489};
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 Lattner50748f42009-04-06 17:17:55 +0000500 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000502 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000504 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000506 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +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++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000514 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 Greif5f8d1db2009-03-11 23:07:18 +0000518 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +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 Carlssonee98ac52007-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 Naroffd62701b2008-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 Gupta56cf96b2008-05-08 08:28:14 +0000534 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000535
536static llvm::cl::opt<bool>
537WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000538 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000539
540static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000541NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-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 Lattnerae0ee032008-12-04 23:20:07 +0000545
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000546static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000547EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000548
549static llvm::cl::opt<bool>
Chris Lattner810f6d52009-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 Stumpa0f02aa2009-02-02 22:57:57 +0000555ObjCNonFragileABI("fobjc-nonfragile-abi",
556 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000557
Daniel Dunbard604c402009-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 Kremenek01d9dbf2008-04-29 04:37:03 +0000561
Daniel Dunbar6379a7a2008-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 Dunbarf77ac862008-08-11 21:35:06 +0000573static llvm::cl::opt<bool>
574GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000575 llvm::cl::desc("Generate output compatible with the standard GNU "
576 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000577
578static llvm::cl::opt<bool>
579NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000580 llvm::cl::desc("Generate output compatible with the NeXT "
581 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000582
Ted Kremenekea644d82008-09-03 21:22:16 +0000583
584
585static llvm::cl::opt<bool>
586Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
587
Chris Lattner16167a62009-03-02 22:11:07 +0000588static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000589TargetFeatures("mattr", llvm::cl::CommaSeparated,
590 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
591
Douglas Gregor26dce442009-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 Lattner16167a62009-03-02 22:11:07 +0000596
Anders Carlsson4ca076f2009-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 Dunbarc9abc042009-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 Carlsson4ca076f2009-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 Carlsson4ca076f2009-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 Dunbar9fd0b1f2009-04-08 03:03:23 +0000626static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000627PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
628
629static llvm::cl::opt<bool>
630StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000631
Reid Spencer5f016e22007-07-11 17:01:13 +0000632// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000633// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000634static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
635 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000636 // Allow the target to set the default the langauge options as it sees fit.
637 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000638
Chris Lattner6328cc32009-03-03 19:56:18 +0000639 // If there are any -mattr options, pass them to the target for validation and
640 // processing. The driver should have already consolidated all the
641 // target-feature settings and passed them to us in the -mattr list. The
642 // -mattr list is treated by the code generator as a diff against the -mcpu
643 // setting, but the driver should pass all enabled options as "+" settings.
644 // This means that the target should only look at + settings.
645 if (!TargetFeatures.empty()
646 // FIXME: The driver is not quite yet ready for this.
647 && 0) {
Chris Lattner16167a62009-03-02 22:11:07 +0000648 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000649 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
650 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000651 if (Opt != -1) {
652 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000653 fprintf(stderr, "invalid feature '%s'\n",
654 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000655 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000656 fprintf(stderr, "feature '%s': %s\n",
657 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000658 exit(1);
659 }
660 }
661
Reid Spencer5f016e22007-07-11 17:01:13 +0000662 if (LangStd == lang_unspecified) {
663 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000664 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000665 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000666 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000667 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 case langkind_c_cpp:
669 case langkind_objc:
670 case langkind_objc_cpp:
671 LangStd = lang_gnu99;
672 break;
673 case langkind_cxx:
674 case langkind_cxx_cpp:
675 case langkind_objcxx:
676 case langkind_objcxx_cpp:
677 LangStd = lang_gnucxx98;
678 break;
679 }
680 }
681
682 switch (LangStd) {
683 default: assert(0 && "Unknown language standard!");
684
685 // Fall through from newer standards to older ones. This isn't really right.
686 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000687 case lang_gnucxx0x:
688 case lang_cxx0x:
689 Options.CPlusPlus0x = 1;
690 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 case lang_gnucxx98:
692 case lang_cxx98:
693 Options.CPlusPlus = 1;
694 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000695 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 // FALL THROUGH.
697 case lang_gnu99:
698 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 Options.C99 = 1;
700 Options.HexFloats = 1;
701 // FALL THROUGH.
702 case lang_gnu89:
703 Options.BCPLComment = 1; // Only for C99/C++.
704 // FALL THROUGH.
705 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000706 Options.Digraphs = 1; // C94, C99, C++.
707 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000708 case lang_c89:
709 break;
710 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000711
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000712 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
713 Options.GNUMode = LangStd >= lang_gnu_START;
714
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000715 if (Options.CPlusPlus) {
716 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000717 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000718 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000719
Chris Lattnerd658b562008-04-05 06:32:51 +0000720 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
721 Options.ImplicitInt = 1;
722 else
723 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000724
Daniel Dunbard573d262009-04-07 22:13:21 +0000725 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
726 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000727 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000728 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000729 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000730
Chris Lattner802db9b2008-12-05 00:10:44 +0000731 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
732 // even if they are normally on for the target. In GNU modes (e.g.
733 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000734 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000735 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000736 Options.Blocks = 0;
737
Daniel Dunbar85c49102009-03-15 00:11:28 +0000738 // Never accept '$' in identifiers when preprocessing assembler.
739 if (LK != langkind_asm_cpp)
740 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000741 if (PascalStrings.getPosition())
742 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000743 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000744 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000745 if (NoLaxVectorConversions.getPosition())
746 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000747 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000748 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000749 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000750
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000751 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000752 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000753 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000754 Options.Freestanding = Options.NoBuiltin = 1;
755
Chris Lattner810f6d52009-03-13 17:38:01 +0000756 if (EnableHeinousExtensions)
757 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000758
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000759 Options.MathErrno = MathErrno;
760
Douglas Gregor26dce442009-03-10 00:06:19 +0000761 Options.InstantiationDepth = TemplateDepth;
762
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000763 // Override the default runtime if the user requested it.
764 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000765 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000766 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000767 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000768
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000769 if (ObjCNonFragileABI)
770 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000771
772 if (EmitAllDecls)
773 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000774
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000775 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
776 // support.
777 Options.OptimizeSize = 0;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000778
779 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000780 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000781 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000782
783 assert(PICLevel <= 2 && "Invalid value for -pic-level");
784 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000785
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000786 Options.GNUInline = !Options.C99;
787 // FIXME: This is affected by other options (-fno-inline).
788 Options.NoInline = !OptSize && !OptLevel;
789
790 Options.Static = StaticDefine;
791
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000792 if (MainFileName.getPosition())
793 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000794}
795
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000796static llvm::cl::opt<bool>
797ObjCExclusiveGC("fobjc-gc-only",
798 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000799 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000800
801static llvm::cl::opt<bool>
802ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000803 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000804
805void InitializeGCMode(LangOptions &Options) {
806 if (ObjCExclusiveGC)
807 Options.setGCMode(LangOptions::GCOnly);
808 else if (ObjCEnableGC)
809 Options.setGCMode(LangOptions::HybridGC);
810}
811
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +0000812static llvm::cl::opt<std::string>
813SymbolVisibility("fvisibility",
814 llvm::cl::desc("Set the default visibility to the specific option"));
815
816void InitializeSymbolVisibility(LangOptions &Options) {
817 if (SymbolVisibility.empty())
818 return;
819 std::string Visibility = SymbolVisibility;
820 const char *vkind = Visibility.c_str();
821 if (!strcmp(vkind, "default"))
822 Options.setVisibilityMode(LangOptions::DefaultVisibility);
823 else if (!strcmp(vkind, "protected"))
824 Options.setVisibilityMode(LangOptions::ProtectedVisibility);
825 else if (!strcmp(vkind, "hidden"))
826 Options.setVisibilityMode(LangOptions::HiddenVisibility);
827 else if (!strcmp(vkind, "internal"))
828 Options.setVisibilityMode(LangOptions::InternalVisibility);
829 else
830 fprintf(stderr,
831 "-fvisibility only valid for default|protected|hidden|internal\n");
832}
833
Mike Stump2add4732009-04-01 20:28:16 +0000834static llvm::cl::opt<bool>
835OverflowChecking("ftrapv",
Mike Stump035cf892009-04-02 18:15:54 +0000836 llvm::cl::desc("Trap on integer overflow"),
Mike Stump2add4732009-04-01 20:28:16 +0000837 llvm::cl::init(false));
838
839void InitializeOverflowChecking(LangOptions &Options) {
Mike Stump035cf892009-04-02 18:15:54 +0000840 Options.OverflowChecking = OverflowChecking;
Mike Stump2add4732009-04-01 20:28:16 +0000841}
Reid Spencer5f016e22007-07-11 17:01:13 +0000842//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000843// Target Triple Processing.
844//===----------------------------------------------------------------------===//
845
846static llvm::cl::opt<std::string>
847TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000848 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000849
Chris Lattner42e67372008-03-05 01:18:20 +0000850static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000851Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000852
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000853static llvm::cl::opt<std::string>
854MacOSVersionMin("mmacosx-version-min",
855 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
856
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000857// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
858// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000859
860// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000861static void HandleMacOSVersionMin(std::string &Triple) {
862 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
863 if (DarwinDashIdx == std::string::npos) {
864 fprintf(stderr,
865 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
866 exit(1);
867 }
868 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
869
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000870 // Remove the number.
871 Triple.resize(DarwinNumIdx);
872
873 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
874 bool MacOSVersionMinIsInvalid = false;
875 int VersionNum = 0;
876 if (MacOSVersionMin.size() < 4 ||
877 MacOSVersionMin.substr(0, 3) != "10." ||
878 !isdigit(MacOSVersionMin[3])) {
879 MacOSVersionMinIsInvalid = true;
880 } else {
881 const char *Start = MacOSVersionMin.c_str()+3;
882 char *End = 0;
883 VersionNum = (int)strtol(Start, &End, 10);
884
Chris Lattner079f2c462008-09-30 20:30:12 +0000885 // The version number must be in the range 0-9.
886 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
887
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000888 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
889 Triple += llvm::itostr(VersionNum+4);
890
Chris Lattner079f2c462008-09-30 20:30:12 +0000891 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
892 // Add the period piece (.7) to the end of the triple. This gives us
893 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000894 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000895 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
896 MacOSVersionMinIsInvalid = true;
897 }
898 }
899
900 if (MacOSVersionMinIsInvalid) {
901 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000902 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000903 MacOSVersionMin.c_str());
904 exit(1);
905 }
906}
907
908/// CreateTargetTriple - Process the various options that affect the target
909/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000910static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000911 // Initialize base triple. If a -triple option has been specified, use
912 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000913 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000914 if (Triple.empty())
915 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +0000916
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000917 // If -arch foo was specified, remove the architecture from the triple we have
918 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000919
920 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000921 if (!Arch.empty()) {
922 // Decompose the base triple into "arch" and suffix.
923 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000924
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000925 if (FirstDashIdx == std::string::npos) {
926 fprintf(stderr,
927 "Malformed target triple: \"%s\" ('-' could not be found).\n",
928 Triple.c_str());
929 exit(1);
930 }
Chris Lattner37e217c2009-03-24 16:18:41 +0000931
932 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
933 if (Arch == "ppc")
934 Arch = "powerpc";
935 else if (Arch == "ppc64")
936 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +0000937
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000938 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
939 }
940
941 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
942 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000943 if (!MacOSVersionMin.empty())
944 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000945
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000946 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000947}
948
949//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000950// Preprocessor Initialization
951//===----------------------------------------------------------------------===//
952
953// FIXME: Preprocessor builtins to support.
954// -A... - Play with #assertions
955// -undef - Undefine all predefined macros
956
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000957// FIXME: -imacros
958
Reid Spencer5f016e22007-07-11 17:01:13 +0000959static llvm::cl::list<std::string>
960D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
961 llvm::cl::desc("Predefine the specified macro"));
962static llvm::cl::list<std::string>
963U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
964 llvm::cl::desc("Undefine the specified macro"));
965
Chris Lattner64299f82008-01-10 01:53:41 +0000966static llvm::cl::list<std::string>
967ImplicitIncludes("include", llvm::cl::value_desc("file"),
968 llvm::cl::desc("Include file before parsing"));
969
Ted Kremenek748d5d62009-03-20 00:26:38 +0000970static llvm::cl::opt<std::string>
971ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
972 llvm::cl::desc("Include file before parsing"));
973
Reid Spencer5f016e22007-07-11 17:01:13 +0000974// Append a #define line to Buf for Macro. Macro should be of the form XXX,
975// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
976// "#define XXX Y z W". To get a #define with no value, use "XXX=".
977static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
978 const char *Command = "#define ") {
979 Buf.insert(Buf.end(), Command, Command+strlen(Command));
980 if (const char *Equal = strchr(Macro, '=')) {
981 // Turn the = into ' '.
982 Buf.insert(Buf.end(), Macro, Equal);
983 Buf.push_back(' ');
Chris Lattner0b514152009-04-07 06:02:44 +0000984
985 // Per GCC -D semantics, the macro ends at \n if it exists.
986 const char *End = strpbrk(Equal, "\n\r");
Chris Lattner3eb2fc82009-04-07 18:18:09 +0000987 if (End) {
Chris Lattner56473d32009-04-08 03:36:03 +0000988 fprintf(stderr, "warning: macro '%s' contains embedded newline, text "
Chris Lattner3eb2fc82009-04-07 18:18:09 +0000989 "after the newline is ignored.\n",
990 std::string(Macro, Equal).c_str());
991 } else {
992 End = Equal+strlen(Equal);
993 }
Chris Lattner0b514152009-04-07 06:02:44 +0000994
995 Buf.insert(Buf.end(), Equal+1, End);
Reid Spencer5f016e22007-07-11 17:01:13 +0000996 } else {
997 // Push "macroname 1".
998 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
999 Buf.push_back(' ');
1000 Buf.push_back('1');
1001 }
1002 Buf.push_back('\n');
1003}
1004
Chris Lattner64299f82008-01-10 01:53:41 +00001005/// AddImplicitInclude - Add an implicit #include of the specified file to the
1006/// predefines buffer.
1007static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
1008 const char *Inc = "#include \"";
1009 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
1010 Buf.insert(Buf.end(), File.begin(), File.end());
1011 Buf.push_back('"');
1012 Buf.push_back('\n');
1013}
1014
Ted Kremenek748d5d62009-03-20 00:26:38 +00001015/// AddImplicitIncludePTH - Add an implicit #include using the original file
1016/// used to generate a PTH cache.
1017static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
1018 PTHManager *P = PP.getPTHManager();
1019 assert(P && "No PTHManager.");
1020 const char *OriginalFile = P->getOriginalSourceFile();
1021
1022 if (!OriginalFile) {
1023 assert(!ImplicitIncludePTH.empty());
1024 fprintf(stderr, "error: PTH file '%s' does not designate an original "
1025 "source header file for -include-pth\n",
1026 ImplicitIncludePTH.c_str());
1027 exit (1);
1028 }
1029
1030 AddImplicitInclude(Buf, OriginalFile);
1031}
Reid Spencer5f016e22007-07-11 17:01:13 +00001032
Chris Lattner53b0dab2007-10-09 22:10:18 +00001033/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +00001034/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +00001035///
Chris Lattner51574ea2008-04-19 23:25:44 +00001036static bool InitializePreprocessor(Preprocessor &PP,
1037 bool InitializeSourceMgr,
1038 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +00001039 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +00001040
Chris Lattner53b0dab2007-10-09 22:10:18 +00001041 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +00001042 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +00001043
1044 if (InitializeSourceMgr) {
1045 if (InFile != "-") {
1046 const FileEntry *File = FileMgr.getFile(InFile);
1047 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +00001048 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001049 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1050 << InFile.c_str();
Chris Lattner51574ea2008-04-19 23:25:44 +00001051 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001052 }
1053 } else {
1054 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar56743882009-03-21 17:56:30 +00001055
1056 // If stdin was empty, SB is null. Cons up an empty memory
1057 // buffer now.
1058 if (!SB) {
1059 const char *EmptyStr = "";
1060 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1061 }
1062
1063 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +00001064 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001065 PP.getDiagnostics().Report(FullSourceLoc(),
1066 diag::err_fe_error_reading_stdin);
Chris Lattner51574ea2008-04-19 23:25:44 +00001067 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001068 }
Chris Lattner53b0dab2007-10-09 22:10:18 +00001069 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 }
Sam Bishop1102d6b2008-04-14 14:41:57 +00001071
Chris Lattneraa391972008-04-19 23:09:31 +00001072 std::vector<char> PredefineBuffer;
1073
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +00001075 unsigned d = 0, D = D_macros.size();
1076 unsigned u = 0, U = U_macros.size();
1077 while (d < D || u < U) {
1078 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1079 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
1080 else
1081 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
1082 }
1083
Chris Lattner64299f82008-01-10 01:53:41 +00001084 // FIXME: Read any files specified by -imacros.
1085
Ted Kremenek748d5d62009-03-20 00:26:38 +00001086 // Add implicit #includes from -include and -include-pth.
1087 bool handledPTH = ImplicitIncludePTH.empty();
1088 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc53b60a2009-03-20 00:40:03 +00001089 if (!handledPTH &&
1090 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek748d5d62009-03-20 00:26:38 +00001091 AddImplicitIncludePTH(PredefineBuffer, PP);
1092 handledPTH = true;
1093 }
1094
Chris Lattner64299f82008-01-10 01:53:41 +00001095 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001096 }
1097 if (!handledPTH && !ImplicitIncludePTH.empty())
1098 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner53b0dab2007-10-09 22:10:18 +00001099
Chris Lattneraa391972008-04-19 23:09:31 +00001100 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +00001101 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +00001102 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +00001103
1104 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +00001105 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001106}
1107
1108//===----------------------------------------------------------------------===//
1109// Preprocessor include path information.
1110//===----------------------------------------------------------------------===//
1111
1112// This tool exports a large number of command line options to control how the
1113// preprocessor searches for header files. At root, however, the Preprocessor
1114// object takes a very simple interface: a list of directories to search for
1115//
1116// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001117// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001118//
Reid Spencer5f016e22007-07-11 17:01:13 +00001119
1120static llvm::cl::opt<bool>
1121nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1122
1123// Various command line options. These four add directories to each chain.
1124static llvm::cl::list<std::string>
1125F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1126 llvm::cl::desc("Add directory to framework include search path"));
1127static llvm::cl::list<std::string>
1128I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1129 llvm::cl::desc("Add directory to include search path"));
1130static llvm::cl::list<std::string>
1131idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1132 llvm::cl::desc("Add directory to AFTER include search path"));
1133static llvm::cl::list<std::string>
1134iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1135 llvm::cl::desc("Add directory to QUOTE include search path"));
1136static llvm::cl::list<std::string>
1137isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1138 llvm::cl::desc("Add directory to SYSTEM include search path"));
1139
1140// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1141static llvm::cl::list<std::string>
1142iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1143 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1144static llvm::cl::list<std::string>
1145iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1146 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1147static llvm::cl::list<std::string>
1148iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1149 llvm::cl::Prefix,
1150 llvm::cl::desc("Set directory to include search path with prefix"));
1151
Chris Lattner0c946412007-08-26 17:47:35 +00001152static llvm::cl::opt<std::string>
1153isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1154 llvm::cl::desc("Set the system root directory (usually /)"));
1155
Reid Spencer5f016e22007-07-11 17:01:13 +00001156// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001157
Reid Spencer5f016e22007-07-11 17:01:13 +00001158/// InitializeIncludePaths - Process the -I options and set them in the
1159/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001160void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1161 FileManager &FM, const LangOptions &Lang) {
1162 InitHeaderSearch Init(Headers, Verbose, isysroot);
1163
Ted Kremenekf3721112008-05-31 00:27:00 +00001164 // Handle -I... and -F... options, walking the lists in parallel.
1165 unsigned Iidx = 0, Fidx = 0;
1166 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1167 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001168 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001169 ++Iidx;
1170 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001171 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001172 ++Fidx;
1173 }
1174 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001175
Ted Kremenekf3721112008-05-31 00:27:00 +00001176 // Consume what's left from whatever list was longer.
1177 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001178 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001179 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001180 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001181
1182 // Handle -idirafter... options.
1183 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001184 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1185 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001186
1187 // Handle -iquote... options.
1188 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001189 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001190
1191 // Handle -isystem... options.
1192 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001193 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001194
1195 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1196 // parallel, processing the values in order of occurance to get the right
1197 // prefixes.
1198 {
1199 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1200 unsigned iprefix_idx = 0;
1201 unsigned iwithprefix_idx = 0;
1202 unsigned iwithprefixbefore_idx = 0;
1203 bool iprefix_done = iprefix_vals.empty();
1204 bool iwithprefix_done = iwithprefix_vals.empty();
1205 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1206 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1207 if (!iprefix_done &&
1208 (iwithprefix_done ||
1209 iprefix_vals.getPosition(iprefix_idx) <
1210 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1211 (iwithprefixbefore_done ||
1212 iprefix_vals.getPosition(iprefix_idx) <
1213 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1214 Prefix = iprefix_vals[iprefix_idx];
1215 ++iprefix_idx;
1216 iprefix_done = iprefix_idx == iprefix_vals.size();
1217 } else if (!iwithprefix_done &&
1218 (iwithprefixbefore_done ||
1219 iwithprefix_vals.getPosition(iwithprefix_idx) <
1220 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001221 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1222 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 ++iwithprefix_idx;
1224 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1225 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001226 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1227 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 ++iwithprefixbefore_idx;
1229 iwithprefixbefore_done =
1230 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1231 }
1232 }
1233 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001234
Nico Weber0fca0222008-08-22 09:25:22 +00001235 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001236
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001237 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001238 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001239 llvm::sys::Path::GetMainExecutable(Argv0,
1240 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001241 if (!MainExecutablePath.isEmpty()) {
1242 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1243 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001244
1245 // Get foo/lib/clang/1.0/include
1246 //
1247 // FIXME: Don't embed version here.
1248 MainExecutablePath.appendComponent("lib");
1249 MainExecutablePath.appendComponent("clang");
1250 MainExecutablePath.appendComponent("1.0");
1251 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001252
1253 // We pass true to ignore sysroot so that we *always* look for clang headers
1254 // relative to our executable, never relative to -isysroot.
1255 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1256 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001257 }
1258
Nico Weber0fca0222008-08-22 09:25:22 +00001259 if (!nostdinc)
1260 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001261
1262 // Now that we have collected all of the include paths, merge them all
1263 // together and tell the preprocessor about them.
1264
Nico Weber0fca0222008-08-22 09:25:22 +00001265 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001266}
1267
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001268//===----------------------------------------------------------------------===//
1269// Driver PreprocessorFactory - For lazily generating preprocessors ...
1270//===----------------------------------------------------------------------===//
1271
1272namespace {
1273class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001274 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001275 Diagnostic &Diags;
1276 const LangOptions &LangInfo;
1277 TargetInfo &Target;
1278 SourceManager &SourceMgr;
1279 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001280 bool InitializeSourceMgr;
1281
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001282public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001283 DriverPreprocessorFactory(const std::string &infile,
1284 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001285 TargetInfo &target, SourceManager &SM,
1286 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001287 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1288 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1289
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001290
1291 virtual ~DriverPreprocessorFactory() {}
1292
1293 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001294 llvm::OwningPtr<PTHManager> PTHMgr;
1295
Ted Kremenek748d5d62009-03-20 00:26:38 +00001296 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1297 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1298 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001299 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001300 }
1301
Ted Kremenek72b1b152009-01-15 18:47:46 +00001302 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001303 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1304 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001305 PTHMgr.reset(PTHManager::Create(x, &Diags,
1306 TokenCache.empty() ? Diagnostic::Error
1307 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001308 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001309
Ted Kremenek22f0d092009-03-22 06:42:39 +00001310 if (Diags.hasErrorOccurred())
1311 exit(1);
1312
Ted Kremenek72b1b152009-01-15 18:47:46 +00001313 // Create the Preprocessor.
1314 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1315 SourceMgr, HeaderInfo,
1316 PTHMgr.get()));
1317
1318 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1319 // That argument is used as the IdentifierInfoLookup argument to
1320 // IdentifierTable's ctor.
1321 if (PTHMgr) {
1322 PTHMgr->setPreprocessor(PP.get());
1323 PP->setPTHManager(PTHMgr.take());
1324 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001325
Chris Lattner51574ea2008-04-19 23:25:44 +00001326 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001327 return NULL;
1328 }
1329
Daniel Dunbar750c3582008-10-24 22:12:41 +00001330 /// FIXME: PP can only handle one callback
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001331 if (ProgAction != PrintPreprocessedInput) {
1332 std::string ErrStr;
1333 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1334 if (!DFG && !ErrStr.empty()) {
1335 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar750c3582008-10-24 22:12:41 +00001336 return NULL;
1337 }
1338 }
1339
Ted Kremenek339b9c22008-04-17 22:31:54 +00001340 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001341 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001342 }
1343};
1344}
Reid Spencer5f016e22007-07-11 17:01:13 +00001345
Reid Spencer5f016e22007-07-11 17:01:13 +00001346//===----------------------------------------------------------------------===//
1347// Basic Parser driver
1348//===----------------------------------------------------------------------===//
1349
Chris Lattner51574ea2008-04-19 23:25:44 +00001350static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001352 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001353
1354 // Parsing the specified input file.
1355 P.ParseTranslationUnit();
1356 delete PA;
1357}
1358
1359//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001360// Code generation options
1361//===----------------------------------------------------------------------===//
1362
1363static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001364GenerateDebugInfo("g",
1365 llvm::cl::desc("Generate source level debug information"));
1366
Daniel Dunbara034ba82009-02-17 19:47:34 +00001367static llvm::cl::opt<std::string>
1368TargetCPU("mcpu",
1369 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1370
Chris Lattner7afae712009-03-16 18:41:18 +00001371static void InitializeCompileOptions(CompileOptions &Opts,
1372 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001373 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001374 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001375 if (OptSize) {
1376 // -Os implies -O2
1377 // FIXME: Diagnose conflicting options.
1378 Opts.OptimizationLevel = 2;
1379 } else {
1380 Opts.OptimizationLevel = OptLevel;
1381 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001382
1383 // FIXME: There are llvm-gcc options to control these selectively.
1384 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1385 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001386 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001387
1388#ifdef NDEBUG
1389 Opts.VerifyModule = 0;
1390#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001391
1392 Opts.CPU = TargetCPU;
1393 Opts.Features.insert(Opts.Features.end(),
1394 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001395
Chris Lattnerbd360642009-03-26 05:00:52 +00001396 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1397
Chris Lattner44502662009-02-18 01:23:44 +00001398 // Handle -ftime-report.
1399 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001400}
1401
1402//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001403// Fix-It Options
1404//===----------------------------------------------------------------------===//
1405static llvm::cl::list<ParsedSourceLocation>
1406FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1407 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1408
1409//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001410// Main driver
1411//===----------------------------------------------------------------------===//
1412
Ted Kremenekdb094a22007-12-05 18:27:04 +00001413/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001414/// action. These consumers can operate on both ASTs that are freshly
1415/// parsed from source files as well as those deserialized from Bitcode.
1416/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001417static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001418 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001419 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001420 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001421 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001422 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001423 default:
1424 return NULL;
1425
1426 case ASTPrint:
1427 return CreateASTPrinter();
1428
1429 case ASTDump:
1430 return CreateASTDumper();
1431
1432 case ASTView:
1433 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001434
Chris Lattner8a5c8092009-02-18 01:20:05 +00001435 case PrintDeclContext:
1436 return CreateDeclContextPrinter();
1437
1438 case EmitHTML:
1439 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001440
Chris Lattner8a5c8092009-02-18 01:20:05 +00001441 case InheritanceView:
1442 return CreateInheritanceViewer(InheritanceViewCls);
1443
1444 case TestSerialization:
1445 return CreateSerializationTest(Diag, FileMgr);
1446
1447 case EmitAssembly:
1448 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001449 case EmitBC:
1450 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001451 BackendAction Act;
1452 if (ProgAction == EmitAssembly)
1453 Act = Backend_EmitAssembly;
1454 else if (ProgAction == EmitLLVM)
1455 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001456 else if (ProgAction == EmitLLVMOnly)
1457 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001458 else
1459 Act = Backend_EmitBC;
1460
1461 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001462 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001463 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001464 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001465 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001466
Chris Lattner8a5c8092009-02-18 01:20:05 +00001467 case SerializeAST:
1468 // FIXME: Allow user to tailor where the file is written.
1469 return CreateASTSerializer(InFile, OutputFile, Diag);
1470
1471 case RewriteObjC:
1472 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001473
Chris Lattner8a5c8092009-02-18 01:20:05 +00001474 case RewriteBlocks:
1475 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1476
1477 case RunAnalysis:
1478 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001479 }
1480}
1481
Reid Spencer5f016e22007-07-11 17:01:13 +00001482/// ProcessInputFile - Process a single input file with the specified state.
1483///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001484static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001485 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001486 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001487 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001488 FixItRewriter *FixItRewrite = 0;
1489
Ted Kremenek85888962008-10-21 00:54:44 +00001490 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001492 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1493 PP.getFileManager(), PP.getLangOptions(),
1494 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001495
1496 if (!Consumer) {
1497 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001498 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001499 return;
1500 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001501
Ted Kremenekdb094a22007-12-05 18:27:04 +00001502 break;
1503
Chris Lattnerc106c102008-10-12 05:03:36 +00001504 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001505 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001506 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001507 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001508 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001509 RawLex.SetKeepWhitespaceMode(true);
1510
1511 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001512 RawLex.LexFromRawLexer(RawTok);
1513 while (RawTok.isNot(tok::eof)) {
1514 PP.DumpToken(RawTok, true);
1515 fprintf(stderr, "\n");
1516 RawLex.LexFromRawLexer(RawTok);
1517 }
1518 ClearSourceMgr = true;
1519 break;
1520 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001521 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001522 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001523 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001524 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001525 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 do {
1527 PP.Lex(Tok);
1528 PP.DumpToken(Tok, true);
1529 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001530 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001531 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 break;
1533 }
1534 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001535 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001536 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001538 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 do {
1540 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001541 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001542 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 break;
1544 }
Ted Kremenek85888962008-10-21 00:54:44 +00001545
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001546 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001547 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001548 CacheTokens(PP, OutputFile);
1549 ClearSourceMgr = true;
1550 break;
1551 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001552
Chris Lattner47099742009-02-18 01:51:21 +00001553 case PrintPreprocessedInput: { // -E mode.
1554 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001555 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001556 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 break;
Chris Lattner47099742009-02-18 01:51:21 +00001558 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001559
Chris Lattner47099742009-02-18 01:51:21 +00001560 case ParseNoop: { // -parse-noop
1561 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001562 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001563 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 break;
Chris Lattner47099742009-02-18 01:51:21 +00001565 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001566
Chris Lattner47099742009-02-18 01:51:21 +00001567 case ParsePrintCallbacks: {
1568 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001569 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001570 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 break;
Chris Lattner47099742009-02-18 01:51:21 +00001572 }
1573
1574 case ParseSyntaxOnly: { // -fsyntax-only
1575 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001576 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001577 break;
Chris Lattner47099742009-02-18 01:51:21 +00001578 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001579
1580 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001581 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001582 ClearSourceMgr = true;
1583 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001584
Chris Lattner47099742009-02-18 01:51:21 +00001585 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001586 DoRewriteTest(PP, InFile, OutputFile);
1587 ClearSourceMgr = true;
1588 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001589 }
Douglas Gregor558cb562009-04-02 01:08:08 +00001590
1591 case FixIt:
1592 llvm::TimeRegion Timer(ClangFrontendTimer);
1593 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001594 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Douglas Gregor558cb562009-04-02 01:08:08 +00001595 PP.getSourceManager());
Douglas Gregor558cb562009-04-02 01:08:08 +00001596 break;
Chris Lattner47099742009-02-18 01:51:21 +00001597 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001598
1599 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001600 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001601
Douglas Gregor26df2f02009-04-02 19:05:20 +00001602 if (FixItAtLocations.size() > 0) {
1603 // Even without the "-fixit" flag, with may have some specific
1604 // locations where the user has requested fixes. Process those
1605 // locations now.
1606 if (!FixItRewrite)
1607 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1608 PP.getSourceManager());
1609
1610 bool AddedFixitLocation = false;
1611 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1612 Idx != Last; ++Idx) {
1613 RequestedSourceLocation Requested;
1614 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1615 Requested)) {
1616 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1617 FixItAtLocations[Idx].FileName.c_str());
1618 } else {
1619 FixItRewrite->addFixItLocation(Requested);
1620 AddedFixitLocation = true;
1621 }
1622 }
1623
1624 if (!AddedFixitLocation) {
1625 // All of the fix-it locations were bad. Don't fix anything.
1626 delete FixItRewrite;
1627 FixItRewrite = 0;
1628 }
1629 }
1630
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001631 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1632 PP.getSourceManager(),
1633 PP.getTargetInfo(),
1634 PP.getIdentifierTable(),
1635 PP.getSelectorTable(),
1636 /* FreeMemory = */ !DisableFree));
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001637
1638
Chris Lattner3599dbe2009-03-28 04:13:34 +00001639 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001640
Douglas Gregor558cb562009-04-02 01:08:08 +00001641 if (FixItRewrite)
1642 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1643
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001644 // If in -disable-free mode, don't deallocate these when they go out of
1645 // scope.
Chris Lattner3599dbe2009-03-28 04:13:34 +00001646 if (DisableFree)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001647 ContextOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001648 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001649
1650 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001651 if (CheckDiagnostics(PP))
1652 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001653
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001655 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 PP.PrintStats();
1657 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001658 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001659 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001660 fprintf(stderr, "\n");
1661 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001662
1663 // For a multi-file compilation, some things are ok with nuking the source
1664 // manager tables, other require stable fileid/macroid's across multiple
1665 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001666 if (ClearSourceMgr)
1667 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001668
1669 if (DisableFree)
1670 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001671}
1672
Ted Kremenek20e97482007-12-12 23:41:08 +00001673static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1674 FileManager& FileMgr) {
1675
1676 if (VerifyDiagnostics) {
1677 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1678 exit (1);
1679 }
1680
1681 llvm::sys::Path Filename(InFile);
1682
1683 if (!Filename.isValid()) {
1684 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1685 exit (1);
1686 }
1687
Chris Lattner557c5b12009-03-28 04:27:18 +00001688 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner5f737cc2009-03-28 03:49:26 +00001689
1690 // Create the memory buffer that contains the contents of the file.
1691 llvm::OwningPtr<llvm::MemoryBuffer>
1692 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1693
1694 if (MBuffer)
Chris Lattner557c5b12009-03-28 04:27:18 +00001695 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001696
Chris Lattner557c5b12009-03-28 04:27:18 +00001697 if (!Ctx) {
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001698 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1699 InFile.c_str());
1700 exit (1);
1701 }
1702
Ted Kremenek63ea8632007-12-19 19:27:38 +00001703 // Observe that we use the source file name stored in the deserialized
1704 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001705 llvm::OwningPtr<ASTConsumer>
Chris Lattner557c5b12009-03-28 04:27:18 +00001706 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001707 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001708
Ted Kremenek20e97482007-12-12 23:41:08 +00001709 if (!Consumer) {
1710 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1711 exit (1);
1712 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001713
Chris Lattner557c5b12009-03-28 04:27:18 +00001714 Consumer->Initialize(*Ctx);
Nico Weber7bfaaae2008-08-10 19:59:06 +00001715
Chris Lattnere66b65c2008-02-06 01:42:25 +00001716 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattner557c5b12009-03-28 04:27:18 +00001717 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1718 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1719 I != E; ++I)
Chris Lattner682bf922009-03-29 16:50:03 +00001720 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek20e97482007-12-12 23:41:08 +00001721}
1722
1723
Reid Spencer5f016e22007-07-11 17:01:13 +00001724static llvm::cl::list<std::string>
1725InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1726
Ted Kremenek20e97482007-12-12 23:41:08 +00001727static bool isSerializedFile(const std::string& InFile) {
1728 if (InFile.size() < 4)
1729 return false;
1730
1731 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001732 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001733}
1734
Reid Spencer5f016e22007-07-11 17:01:13 +00001735
1736int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001738 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001739 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001740 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001741
Chris Lattner47099742009-02-18 01:51:21 +00001742 if (TimeReport)
1743 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1744
Reid Spencer5f016e22007-07-11 17:01:13 +00001745 // If no input was specified, read from stdin.
1746 if (InputFilenames.empty())
1747 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001748
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 // Create a file manager object to provide access to and cache the filesystem.
1750 FileManager FileMgr;
1751
Ted Kremenek31e703b2007-12-11 23:28:38 +00001752 // Create the diagnostic client for reporting errors or for
1753 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001754 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001755
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001756 if (!VerifyDiagnostics) {
1757 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001758 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1759 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001760 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001761 !NoShowLocation,
1762 PrintSourceRangeInfo);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001763 } else {
1764 // When checking diagnostics, just buffer them up.
1765 TextDiagClient = new TextDiagnosticBuffer();
1766
1767 if (InputFilenames.size() != 1) {
1768 fprintf(stderr,
1769 "-verify only works on single input files for now.\n");
1770 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001771 }
1772 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001773
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001775 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1776 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001777 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001778 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001779
Chris Lattner4f037832007-12-05 23:24:17 +00001780 // -I- is a deprecated GCC feature, scan for it and reject it.
1781 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1782 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001783 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001784 I_dirs.erase(I_dirs.begin()+i);
1785 --i;
1786 }
1787 }
Chris Lattner11215192008-03-14 06:12:05 +00001788
1789 // Get information about the target being compiled for.
1790 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001791 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1792
Chris Lattner11215192008-03-14 06:12:05 +00001793 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001794 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1795 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001796 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001797 }
Chris Lattner4f037832007-12-05 23:24:17 +00001798
Daniel Dunbard4270232009-01-20 23:17:32 +00001799 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001800 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001801
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001802 llvm::OwningPtr<SourceManager> SourceMgr;
1803
Reid Spencer5f016e22007-07-11 17:01:13 +00001804 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001805 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001806
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001807 if (isSerializedFile(InFile)) {
1808 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001809 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001810 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001811 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001812
1813 /// Create a SourceManager object. This tracks and owns all the file
1814 /// buffers allocated to a translation unit.
1815 if (!SourceMgr)
1816 SourceMgr.reset(new SourceManager());
1817 else
1818 SourceMgr->clearIDTables();
1819
1820 // Initialize language options, inferring file types from input filenames.
1821 LangOptions LangInfo;
1822 InitializeBaseLanguage();
1823 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001824 InitializeLangOptions(LangInfo, LK);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001825 InitializeGCMode(LangInfo);
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +00001826 InitializeSymbolVisibility(LangInfo);
Mike Stump2add4732009-04-01 20:28:16 +00001827 InitializeOverflowChecking(LangInfo);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001828 InitializeLanguageStandard(LangInfo, LK, Target.get());
1829
1830 // Process the -I options and set them in the HeaderInfo.
1831 HeaderSearch HeaderInfo(FileMgr);
1832
1833 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1834
1835 // Set up the preprocessor with these options.
1836 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1837 *SourceMgr.get(), HeaderInfo);
1838
1839 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1840
1841 if (!PP)
1842 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001843
Chris Lattnerf63aea32009-03-04 21:40:56 +00001844 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1845 // always reset to using TextDiagClient.
1846 llvm::OwningPtr<DiagnosticClient> TmpClient;
1847
1848 if (!HTMLDiag.empty()) {
1849 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1850 &PPFactory));
1851 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001852 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001853 else
1854 Diags.setClient(TextDiagClient);
1855
1856 // Process the source file.
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001857 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001858
1859 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 }
Chris Lattner11215192008-03-14 06:12:05 +00001861
Mike Stump007f2a92009-01-28 02:43:35 +00001862 if (Verbose)
1863 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1864 " hosted on " LLVM_HOSTTRIPLE "\n");
1865
Ted Kremenek7a08e282008-08-07 18:13:12 +00001866 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001867 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1868 (NumDiagnostics == 1 ? "" : "s"));
1869
1870 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 FileMgr.PrintStats();
1872 fprintf(stderr, "\n");
1873 }
1874
Daniel Dunbar276373d2008-10-27 22:10:13 +00001875 // If verifying diagnostics and we reached here, all is well.
1876 if (VerifyDiagnostics)
1877 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001878
1879 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001880
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001881 // Managed static deconstruction. Useful for making things like
1882 // -time-passes usable.
1883 llvm::llvm_shutdown();
1884
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001885 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001886}